无法在 python 中使用 OAEP 解密

unable to use OAEP decryption in python

这是我的代码:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
from Crypto import Hash
import base64

key = RSA.import_key("""-----BEGIN PRIVATE KEY-----
MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqPfgaTEWEP3S9w0t
gsicURfo+nLW09/0KfOPinhYZ4ouzU+3xC4pSlEp8Ut9FgL0AgqNslNaK34Kq+NZ
jO9DAQIDAQABAkAgkuLEHLaqkWhLgNKagSajeobLS3rPT0Agm0f7k55FXVt743hw
Ngkp98bMNrzy9AQ1mJGbQZGrpr4c8ZAx3aRNAiEAoxK/MgGeeLui385KJ7ZOYktj
hLBNAB69fKwTZFsUNh0CIQEJQRpFCcydunv2bENcN/oBTRw39E8GNv2pIcNxZkcb
NQIgbYSzn3Py6AasNj6nEtCfB+i1p3F35TK/87DlPSrmAgkCIQDJLhFoj1gbwRbH
/bDRPrtlRUDDx44wHoEhSDRdy77eiQIgE6z/k6I+ChN1LLttwX0galITxmAYrOBh
BVl433tgTTQ=
-----END PRIVATE KEY-----""")

ciphertext = "h3j3zLT2jXCaZuwF7cgUE/Zmc/5IsIfKbaTiBhpCJo86AiyuoA3Yvni+Lrm5wu2OGv2h5R7Zu3voFcHugiystw=="

ciphertextBytes = base64.decodebytes(ciphertext.encode('ascii'))

cipher = PKCS1_OAEP.new(key, Hash.MD5, Hash.SHA1)
plaintext = cipher.decrypt(ciphertextBytes)

print(plaintext)

这是我得到的错误:

Traceback (most recent call last):
  File "test.py", line 23, in <module>
    plaintext = cipher.decrypt(ciphertextBytes)
  File "C:\Users\neubert\AppData\Local\Programs\Python\Python38\lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 183, in decrypt
    seedMask = self._mgf(maskedDB, hLen)
TypeError: 'module' object is not callable

我做错了什么?我是 运行 Python 3.8.3.

掩码生成函数的 mgfunc 参数(第 3 个参数)在发布的代码中指定不正确。根据Crypto.Cipher.PKCS1_OAEP.new()的描述:

mgfunc (callable) – A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. If not specified, the standard MGF1 consistent with hashAlgo is used (a safe choice).

其中 hashAlgo(第二个参数)表示 OAEP 摘要。

Crypto.Signature.pss 上下文中的文档中描述了使用具有明确指定的摘要的 MGF1,请参阅 Crypto.Signature.pss.MGF1() and Crypto.Signature.pss.new(). However, MGF1 is also available in Crypto.Cipher.PKCS1_OAEP (where it is imported from Crypto.Signature.pss in the source code)。

由于默认情况下 MGF1 与第二个参数 (hashAlgo) 中指定的 OAEP 摘要一起使用,因此只要两个摘要不同,就需要明确指定掩码生成函数或 MGF1,即,如这个例子中,OAEP 摘要是 MD5,MGF1 摘要是 SHA1。

如果代码中使用了下面一行:

cipher = PKCS1_OAEP.new(key, Hash.MD5, mgfunc = lambda x,y: PKCS1_OAEP.MGF1(x, y, Hash.SHA1))

然后解密工作,b'test' 作为解密值返回。

请注意,MD5 and SHA1 are deprecated. RFC8017 只推荐 SHA-1 和 SHA-2 用于 RSAES-OAEP。