3

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

1 回答 1

6

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

值得注意的是,根据分解 RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING,BouncyCastle 以与 Pycrypto 相同的方式对 Hash 和 MGF1 使用 SHA256。

于 2018-05-17T15:05:02.410 回答