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

Pycrypto RSA PKCS1 OAEP SHA256 Interoperability with Java

我在 Python + Pycryptodome(Pycrypto 分支)中使用以下代码使用 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)

在Sun JCE中,RSA/ECB/OAEPWithSHA-256AndMGF1Padding实际上意味着:

  • 哈希 = SHA256
  • MGF1 = SHA1

另一方面,Pycrypto(包括 Pycryptodome)在使用 PKCS1_OAEP.new(hashAlgo=SHA256) 时假设如下:

  • 哈希 = SHA256
  • MGF1 = SHA256

要使 Pycrypto 与 Sun JCE 兼容,您需要通过传递 mgfunc 参数来配置 Pycrypto 的 OAEP MGF1 函数以使用 SHA1:

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)

值得注意的是,根据 ,BouncyCastle 对 Hash 和 MGF1 使用 SHA256 的方式与 Pycrypto 相同。