我正在使用下面的代码加密和解密密码。

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在
com.moneygram.webpoe.util.SecurityProvider.decrypt(SecurityProvider.java:171)
[4/4/14 12:36:59:524 CDT] 00000024 SystemErr R在
com.moneygram.webpoe.util.SecurityProvider.decrypt(SecurityProvider.java:137)


如果有人对此有任何解决方案,请帮助我?如果这是不完整的信息,我可以提供。我被困住了!!!

最佳答案

我不确定您的问题,但我确实知道您过多地依赖默认值-密钥,字符集和加密+填充模式。

请尝试以下操作,请指出是否可以解决您的问题:

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);
}

09-30 11:28