【发布时间】:2018-05-11 19:02:32
【问题描述】:
有人可以向我解释为什么这段代码在解密密钥时会在最后一行抛出javax.crypto.BadPaddingException: Decryption error 吗?
// Given an RSA key pair...
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// ... and an AES key:
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
SecretKey aesKey = keyGenerator.generateKey();
// When I encrypt the key with this Bouncy Castle cipher:
Cipher encryptionCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC");
encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedKey = encryptionCipher.doFinal(aesKey.getEncoded());
// Then trying to decrypt the key with this cipher...
Cipher decryptionCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
decryptionCipher.init(Cipher.DECRYPT_MODE, privateKey);
// ... throws `javax.crypto.BadPaddingException: Decryption error` here:
decryptionCipher.doFinal(encryptedKey);
https://stackoverflow.com/a/27886397/66722 的以下陈述是否也适用于带有 OAEP 的 RSA?
“RSA/ECB/PKCS1Padding”实际上没有实现ECB模式加密。 它应该被称为“RSA/None/PKCS1Padding”,因为它只能是 用于加密单个明文块(或者,实际上是密钥)。 这只是 Sun/Oracle 的命名错误。
如果是这样,我希望这些转换是等效的,并且我上面的测试能够通过。两者都指定了相同的填充,那么为什么BadPaddingException?
无论哪种方式,我都希望外行能解释一下两者之间的区别。
【问题讨论】:
-
这些转换是等价的。没有 RSA 的“模式”,它不能那样工作。
标签: java encryption rsa bouncycastle jce