【问题标题】:Why do I get a BadPaddingException from RSA decryption?为什么我会从 RSA 解密中得到 BadPaddingException?
【发布时间】:2014-10-13 18:10:26
【问题描述】:

我使用 RSA 算法进行加密和解密。当我加密一个字符串时,它工作正常。当我解密时,我得到一个错误。下面,我发布我的代码。

public final String modulusString ="..............";
public final String publicExponentString = "AQAB";

/* Encryption */
byte[] modulebytes = Base64.decode(modulusString);
byte[] exponentbytes = Base64.decode(publicExponentString);
BigInteger module = new BigInteger(1,modulebytes);
BigInteger publicexponent = new BigInteger(1,exponentbytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(module, publicexponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);

byte[] plainBytes = EncryptionValue.getBytes("UTF-8");
byte[] cipherData = cipher.doFinal( plainBytes );
String encryptedString = Base64.encode(cipherData);

return encryptedString;

/* Decryption */
byte[] modulebytes = Base64.decode(modulusString);
byte[] exponentbytes = Base64.decode(publicExponentString);

BigInteger modulus = new BigInteger(1, modulebytes );
BigInteger exponent = new BigInteger(1, exponentbytes);

RSAPrivateKeySpec rsaPrivKey = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(rsaPrivKey);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privKey);

byte[] base64String = Base64.decode(DecryptionValue);
byte[] plainBytes = new String(base64String).getBytes("UTF-8");
plainBytes = cipher.update(plainBytes);
byte[] values = cipher.doFinal(plainBytes);

return new String(values, "UTF-8");
线程“主”javax.crypto.BadPaddingException 中的异常:解密错误 在 sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380) 在 sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291) 在 com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363) 在 com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389) 在 javax.crypto.Cipher.doFinal(Cipher.java:2121) 在 cryptocodefinal.CryptoCodeFinal.DecryptionValue(CryptoCodeFinal.java:79) 在cryptocodefinal.CryptoCodeFinal.main(CryptoCodeFinal.java:148)

【问题讨论】:

    标签: java rsa badpaddingexception


    【解决方案1】:

    您似乎正在使用公钥解密。那是行不通的。您需要使用与用于加密的公共指数一起使用的私有指数进行解密。

    没有私钥就无法解密。这就是非对称密码学的重点。

    【讨论】:

    • 如果是签名,可以用公钥解密
    • @KirillBazarov 是的,但这与这个问题无关。
    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 2011-02-24
    • 2020-07-14
    • 2018-01-17
    • 2018-09-15
    • 2012-12-02
    • 1970-01-01
    相关资源
    最近更新 更多