使用Base64的decrypt方法中的javax.crypto.BadPaddingException

时间:2014-04-07 17:33:43

标签: java security encryption

我正在使用低于代码加密和解密密码。

public static String encrypt(String data, Key key) throws Exception {

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes());
    byte[] base64Bytes = Base64.encodeBase64(encryptedBytes);
    String base64EncodedString = new String(base64Bytes);
    return base64EncodedString;
}

public static String decrypt(String encrypted, Key key) throws Exception {

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decoded = Base64.decodeBase64(encrypted.getBytes());
    byte[] decrypted = cipher.doFinal(decoded);
    return new String(decrypted);
}

加密工作正常。例外情况是抛出解密方法的 doFinal 方法。

例外:

  

[4/4/14 12:36:59:522 CDT] 00000024 SystemErr R引起:    javax.crypto.BadPaddingException:不是PKCS#1块类型2或零填充 [4/4/14 12:36:59:523 CDT] 00000024 SystemErr R at   com.ibm.crypto.provider.RSA.engineDoFinal(未知来源)[4/4/14   12:36:59:523 CDT] 00000024 SystemErr R at   javax.crypto.Cipher.doFinal(未知来源)[4/4/14 12:36:59:523 CDT]   00000024 SystemErr R at   com.moneygram.webpoe.util.SecurityProvider.decrypt(SecurityProvider.java:171)   [4/4/14 12:36:59:524 CDT] 00000024 SystemErr R at   com.moneygram.webpoe.util.SecurityProvider.decrypt(SecurityProvider.java:137)

如果有人对此有任何解决方案,请帮帮我吗?如果这是一个不完整的信息,我可以提供。我坚持这个!!!

1 个答案:

答案 0 :(得分:0)

我不确定你的问题,但我确实知道你过分依赖默认值 - 关键字,字符集和加密模式+填充模式。

请尝试以下操作,并说明是否可以解决您的问题:

public static String encrypt(String data, RSAPublicKey key) throws Exception {

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
    return Base64.encodeBase64String(encryptedBytes);
}

public static String decrypt(String encrypted, RSAPrivateKey key) throws Exception {

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decoded = Base64.decodeBase64(encrypted);
    byte[] decrypted = cipher.doFinal(decoded);
    return new String(decrypted, StandardCharsets.UTF_8);
}