天天看點

RSA加解密

前言

        最近項目中需要利用RSA進行加解密,RSA是目前最流行的,也是最為安全的一種加密方式,RSA利用公鑰和私鑰來作為密鑰,可以私鑰加密公鑰解密,也可以私鑰解密公鑰加密。

        坑點:

        當伺服器端給到我私鑰的時候(利用openssL生成),我無論怎麼去解析私鑰,都會抛出私鑰非法,後來發現在生成私鑰的時候并沒有轉換成PCK8标準的,由于背景是php,php中是不需要轉換的,是以在這點上花了些時間踩坑。

RSATools.java工具類:

public class RSATools {

    //密鑰對
    static String privateKeyWubo ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJh2onB7uwPvO/Ir80erf8m5zotww/NvOH7TYEYkhrmSK18XHeHoxUlBiXd+NoSPYR+E8dQHmNNfiVVRFDxf5nOJ6hwCXFMwJIr0o9DNLAj79+zboW9AGEi6rhB7qeGp1hWH6WTDVInw/rjXCdUxkXuaFkzzesZz471UrHOy5MPNAgMBAAECgYA9x3SzF7AEPCCSVPTTic7SMxRatGrybZL68TQFuC9PasdgVMGrFOM8d+34GZCFzoOQfhJv1FQ88m13wM7uV/3NG2CVVG2LAu3tqJ3WbguH78VRL43wuxX5xdkotnTeLudFmk9Fwaj1WcbfYxMXaNByeW2ETdGcDMRdXr1dmqR9gQJBAMqUrdH4RfFhzl/C5ggdb8Vvmb2jZABDm+MVZYbf0mib6V6arS9oFtb+6ue8b/dXIyancqvrS5OxFvH7L5WHHIUCQQDAqsHHBGPE8MWKoGB0wZM0UpASeKl9YpFZvyohgPGQ1vPjFMyfY2q1KaF+ruPISM/4CoC2BDjCz6VQgRnuEjCpAkAMuRHBoioiYtYnRYJU+CRQ7hVlx6E8MwLTXECoG96HG2OowWYnGA53KkNuknMlwZ8/ijy1d22jtPeP8wqmBXpRAkEAnCMF7PoivHx/Kmv0H0qsuA9c0ItWl9Vkg73HL+WmXsHEXjgB5/2SgYReayLiV/KiD5q7WkarlTzf9RDa6bN2GQJAOB8h9ICVJfn3C/LkXCgTwVgxTmPVFdx1dpZHZL/zdl/0LCYkBxY2GPdXEfgo/t7139rw+T9vomxT5erxeFZ/5g==";

    /**
     * 私鑰
     */
    private RSAPrivateKey privateKey;

    /**
     * 公鑰
     */
    private RSAPublicKey publicKey;

    /**
     * 位元組資料轉字元串專用集合
     */
    private static final char[] HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};


    /**
     * 擷取私鑰
     * @return 目前的私鑰對象
     */
    public RSAPrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * 擷取公鑰
     * @return 目前的公鑰對象
     */
    public RSAPublicKey getPublicKey() {
        return publicKey;
    }

    /**
     * 随機生成密鑰對
     */
    public void genKeyPair(){
        KeyPairGenerator keyPairGen= null;
        try {
            keyPairGen= KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyPairGen.initialize(, new SecureRandom());
        KeyPair keyPair= keyPairGen.generateKeyPair();
        this.privateKey= (RSAPrivateKey) keyPair.getPrivate();
        this.publicKey= (RSAPublicKey) keyPair.getPublic();
    }

    /**
     * 從檔案中輸入流中加載公鑰
     * @param in 公鑰輸入流
     * @throws Exception 加載公鑰時産生的異常
     */
    public void loadPublicKey(InputStream in) throws Exception{
        try {
            BufferedReader br= new BufferedReader(new InputStreamReader(in));
            String readLine= null;
            StringBuilder sb= new StringBuilder();
            while((readLine= br.readLine())!=null){
                if(readLine.charAt()=='-'){
                    continue;
                }else{
                    sb.append(readLine);
                    sb.append('\r');
                }
            }
            loadPublicKey(sb.toString());
        } catch (IOException e) {
            throw new Exception("公鑰資料流讀取錯誤");
        } catch (NullPointerException e) {
            throw new Exception("公鑰輸入流為空");
        }
    }


    /**
     * 從字元串中加載公鑰
     * @param publicKeyStr 公鑰資料字元串
     * @throws Exception 加載公鑰時産生的異常
     */
    public void loadPublicKey(String publicKeyStr) throws Exception{
        try {
            BASE64Decoder base64Decoder= new BASE64Decoder();
            byte[] buffer= base64Decoder.decodeBuffer(publicKeyStr);
            KeyFactory keyFactory= KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer);
            this.publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公鑰非法");
        } catch (IOException e) {
            throw new Exception("公鑰資料内容讀取錯誤");
        } catch (NullPointerException e) {
            throw new Exception("公鑰資料為空");
        }
    }

    /**
     * 從檔案中加載私鑰
     * @param keyFileName 私鑰檔案名
     * @return 是否成功
     * @throws Exception
     */
    public void loadPrivateKey(InputStream in) throws Exception{
        try {
            BufferedReader br= new BufferedReader(new InputStreamReader(in));
            String readLine= null;
            StringBuilder sb= new StringBuilder();
            while((readLine= br.readLine())!=null){
                if(readLine.charAt()=='-'){
                    continue;
                }else{
                    sb.append(readLine);
                    sb.append('\r');
                }
            }
            loadPrivateKey(sb.toString());
        } catch (IOException e) {
            throw new Exception("私鑰資料讀取錯誤");
        } catch (NullPointerException e) {
            throw new Exception("私鑰輸入流為空");
        }
    }

    public void loadPrivateKey(String privateKeyStr) throws Exception{
        try {
            BASE64Decoder base64Decoder= new BASE64Decoder();
            byte[] buffer= base64Decoder.decodeBuffer(privateKeyStr);
            PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory= KeyFactory.getInstance("RSA");
            this.privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私鑰非法");
        } catch (IOException e) {
            throw new Exception("私鑰資料内容讀取錯誤");
        } catch (NullPointerException e) {
            throw new Exception("私鑰資料為空");
        }
    }

    /**
     * 私鑰加密過程
     * @param rsaPrivateKey 私鑰
     * @param plainTextData 明文資料
     * @return
     * @throws Exception 加密過程中的異常資訊
     */
    public byte[] encrypt(RSAPrivateKey rsaPrivateKey,byte[] plainTextData)throws Exception{
        if (privateKey== null){
            try {
                throw new Exception("解密私鑰為空, 請設定");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(plainTextData);
            return result;
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此加密算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("加密公鑰非法,請檢查");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文資料已損壞");
        }
        return null;
    }



    /**
     * 解密過程
     * @param rsaPublicKey 公鑰
     * @param cipherData 密文資料
     * @return 明文
     * @throws Exception 解密過程中的異常資訊
     */
    //公鑰解密
    public String decrypt(RSAPublicKey rsaPublicKey,byte[] cipherData) throws Exception{
        try {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] result = cipher.doFinal(cipherData);
            return new String(result);
        } catch (InvalidKeyException e) {
            throw new Exception("解密私鑰非法,請檢查");
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此解密算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("解密私鑰非法,請檢查");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文資料已損壞");
        }
    }

 /**
     * 加密過程
     * @param publicKey 公鑰
     * @param plainTextData 明文資料
     * @return
     * @throws Exception 加密過程中的異常資訊
     */
    public byte[] gonyaoEncrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception{
        if(publicKey== null){
            throw new Exception("加密公鑰為空, 請設定");
        }
        Cipher cipher= null;
        try {
            cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output= cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }catch (InvalidKeyException e) {
            throw new Exception("加密公鑰非法,請檢查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文資料已損壞");
        }
    }

    /**
     * 解密過程
     * @param privateKey 私鑰
     * @param cipherData 密文資料
     * @return 明文
     * @throws Exception 解密過程中的異常資訊
     */
    public byte[] siyaoDecrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception{
        if (privateKey== null){
            throw new Exception("解密私鑰為空, 請設定");
        }
        Cipher cipher= null;
        try {
            cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output= cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }catch (InvalidKeyException e) {
            throw new Exception("解密私鑰非法,請檢查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文資料已損壞");
        }        
    }


    /**
     * 位元組資料轉十六進制字元串
     * @param data 輸入資料
     * @return 十六進制内容
     */
    public static String byteArrayToString(byte[] data){
        StringBuilder stringBuilder= new StringBuilder();
        for (int i=; i<data.length; i++){
            //取出位元組的高四位 作為索引得到相應的十六進制辨別符 注意無符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & )>>> ]);
            //取出位元組的低四位 作為索引得到相應的十六進制辨別符
            stringBuilder.append(HEX_CHAR[(data[i] & )]);
            if (i<data.length-){
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }



}
           

測試函數:

public static void main(String[] args){
        RSATools rsaEncrypt= new RSATools();
        //加載公鑰
        try {
           // rsaEncrypt.loadPublicKey(new FileInputStream("rsa_public_key.pem"));
            rsaEncrypt.loadPublicKey(publicKeyWubo);
            System.out.println("加載公鑰成功");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.err.println("加載公鑰失敗");
        }

        //加載私鑰
        try {
          //  rsaEncrypt.loadPrivateKey(new FileInputStream("rsa_private_key.pem"));
            rsaEncrypt.loadPrivateKey(privateKeyWubo);
            System.out.println("加載私鑰成功");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.err.println("加載私鑰失敗");
        }

        //測試字元串
        String encryptStr= "test";
        System.out.println("加密前:");
        System.out.println(encryptStr);
        try {
            //加密
            byte[] enResult = rsaEncrypt.siyaoEncrypt(rsaEncrypt.getPrivateKey(), encryptStr.getBytes());   
            //解密
            String result = rsaEncrypt.gongyaoDecrypt(rsaEncrypt.getPublicKey(), enResult);

            System.out.println("加密後:"+com.yctc.test.Base64.encode(enResult));

            System.out.println("解密後:"+result);

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
           

       無論是公鑰加密私鑰解密,還是公鑰解密私鑰加密,都是一樣的,關鍵在于私鑰加密就必須要公鑰解密,公鑰加密就必須要私鑰解密。