RSA算法解密 javax.crypto.BadPaddingException: Decryption error 异常

背景

最近需要对接京东的一个会员管家嵌入到小程序当中,在进行接口请求时,需要对敏感的字段进行RSA加密处理,所以想写一个工具类方便调用。
生成秘钥、加密明文都没问题,就是在解密的时候时候出现了一下异常:
RSA算法解密 javax.crypto.BadPaddingException: Decryption error 异常_第1张图片

原因

在使用公钥加密的时候,最后我用了Base64进行了编码

Base64.getEncoder().encodeToString(encryptedData)

而在我进行解密的时候,直接使用了字符串的getByte获取了字节数组,导致得到的字节数组无法被秘钥解密。应该先使用Base64进行解码获取字节数组,

byte[] encryptedData = Base64.getDecoder().decode(encryptedDataString);

完整代码

  • 公共参数
   /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 获取公钥的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;
  • 生成密钥对
/**
     * 

* 生成密钥对(公钥和私钥) *

* * @return * @throws Exception */
public static Map<String, String> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, String> keyMap = new HashMap<String, String>(2); keyMap.put(PUBLIC_KEY, Base64.getEncoder().encodeToString(publicKey.getEncoded())); keyMap.put(PRIVATE_KEY, Base64.getEncoder().encodeToString(privateKey.getEncoded())); return keyMap; }
  • 公钥加密
 /**
     * 

* 公钥加密 *

* * @param dataBase64String 源数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */
public static String encryptByPublicKey(String dataBase64String, String publicKey) throws Exception { byte[] data = dataBase64String.getBytes(); byte[] keyBytes = Base64.getDecoder().decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return Base64.getEncoder().encodeToString(encryptedData); }
  • 私钥解密
/**
     * 

* 私钥解密 *

* * @param encryptedDataString 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */
public static String decryptByPrivateKey(String encryptedDataString, String privateKey) throws Exception { //byte[] encryptedData = encryptedDataString.getBytes(); //应该先使用Base64方式进行解码 byte[] encryptedData = Base64.getDecoder().decode(encryptedDataString); byte[] keyBytes = Base64.getDecoder().decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return new String(decryptedData); }
  • 测试代码
public static void main(String[] args) throws Exception {
        Map<String, String> stringObjectMap = genKeyPair();
        String rsaPublicKey = stringObjectMap.get("RSAPublicKey");
        String rsaPrivateKey = stringObjectMap.get("RSAPrivateKey");
        System.out.println("公钥为:" + rsaPublicKey);
        System.out.println("私钥为:" + rsaPrivateKey);
        String text = "!1Qq@2Ww哈哈";

        String publicText = encryptByPublicKey(text, rsaPublicKey);
        System.out.println("公钥加密的信息为:" + publicText);

        String privateText = decryptByPrivateKey(publicText, rsaPrivateKey);
        System.out.println("私钥解密的信息为" + privateText);

    }

总结

其实,加密和解密都是对字节数组进行的操作,只要保证加密后的字节数组和解密前的字节数组一致就可以,以上我犯的错误就是加了一层Base64编码,但是没有使用Base64解码导致的,以后还是得更新细心鸭

你可能感兴趣的:(java基础,RSA算法解密,BadPadding,Decryptionerror,base64)