Bouncy Castle vs Java默认RSA与OAEP
作者:互联网
有人可以向我解释为什么这段代码抛出javax.crypto.BadPaddingException:解密密钥时最后一行的解密错误?
// 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” 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?
无论哪种方式,我都会感谢外行人对不同之处的解释.
解决方法:
有关更多信息的类似Stackoverflow问题,请参阅Maarten Bodewes和this的Maarten Bodewes个答案.
转换字符串的“模式”部分无效.问题是不同提供商使用的默认值不同.这是不幸的,非常不是最理想的.我们应该责怪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的默认值.
标签:jce,java,encryption,rsa,bouncycastle 来源: https://codeday.me/bug/20191006/1862813.html