Pycrypto RSA PKCS1 OAEP SHA256与Java的互操作性

时间:2018-05-17 15:05:02

标签: java python rsa pycrypto pycryptodome

我在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)

1 个答案:

答案 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。