Bouncy Castle 与 Java 默认 RSA 与 OAEP

Bouncy Castle vs Java default RSA with OAEP

有人可以向我解释为什么这段代码在解密密钥时在最后一行抛出 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);

来自 的以下陈述是否也适用于带有 OAEP 的 RSA?

"RSA/ECB/PKCS1Padding" actually doesn't implement ECB mode encryption. It should have been called "RSA/None/PKCS1Padding" as it can only be used to encrypt a single block of plaintext (or, indeed a secret key). This is just a naming mistake of Sun/Oracle.

如果是这样,我希望这些转换是等效的,并且我上面的测试能够通过。两者都指定了相同的填充,那么为什么 BadPaddingException?

无论哪种方式,我都会感谢外行人对区别的解释。

有关更多信息的类似 Whosebug 问题,请参阅 Maarten Bodewes answers to and

转换字符串的 "mode" 部分无效。问题是不同的提供商使用不同的默认值。这是不幸的,而且绝对不是最优的。我们应该责怪 Sun/Oracle 吗?除了对结果不满意,我没有别的意见。

OAEP 是一个相当复杂的结构,有两个不同的哈希函数作为参数。密码转换字符串允许您指定其中之一,您已将其指定为 SHA-256。但是,MGF1 函数也由您无法在密码转换字符串中指定的哈希函数进行参数化。 Oracle 提供程序默认为 SHA1,而 BouncyCastle 提供程序默认为 SHA-256。因此,实际上,存在一个对互操作性至关重要的隐藏参数。

解决方案是通过向 Cipher.init(...) 方法提供 OAEPParameterSpec 来更完整地指定这些隐藏参数是什么,如下例所示:

Cipher encryptionCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1",
                MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParameterSpec);
// ...
// ...
// ...
Cipher decryptionCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1",
                MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
decryptionCipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParameterSpec);

第一个实际上是空操作,因为它们已经是 Bouncycastle 的默认值。