我在Python + Pycryptodome(Pycrypto fork)中使用以下代码使用RSA PKCS加密消息#1 OAEP SHA256(RSA/ECB/OAEPWithSHA-256AndMGF1Padding
):
from Crypto.Cipher import PKCS1_OAEP
from Cryptodome.Hash import SHA256
cipher = PKCS1_OAEP.new(key=self.key, hashAlgo=SHA256))
ciphertext = cipher.encrypt(cek)
以及Java中的以下代码来解密它:
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cek = cipher.doFinal(ciphertext);
但是,我得到了:
Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadOAEP(RSAPadding.java:499)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:293)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
答案 0 :(得分:2)
在Sun JCE中,RSA/ECB/OAEPWithSHA-256AndMGF1Padding
实际上是指使用SHA1的Hash = SHA256和MGF1。另一方面,当Hash = SHA256时,Pycrypto *假定为MGF1 + SHA256。
您需要通过将正确的Hash机制传递给MGF1函数来相应地配置Pycrypto *:
from Cryptodome.Cipher import PKCS1_OAEP
from Cryptodome.Hash import SHA256, SHA1
from Cryptodome.Signature import pss
cipher = PKCS1_OAEP.new(key=self.key, hashAlgo=SHA256, mgfunc=lambda x,y: pss.MGF1(x,y, SHA1))
ciphertext = cipher.encrypt(cek)
值得注意的是,根据breaking down RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING,BouncyCastle以与Pycrypto *相同的方式对Hash和MGF1使用SHA256。