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

2024-04-19 14:57:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python+Pycryptodome(pycryptofork)中的以下代码使用RSA PKCS\1oaep 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代码进行解密:

^{pr2}$

但是,我得到了:

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)

Tags: 代码fromimportjavacryptorsaatsun
1条回答
网友
1楼 · 发布于 2024-04-19 14:57:50

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

值得注意的是,根据breaking down RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING,BouncyCastle使用SHA256作为散列和MGF1,方法与Pycrypto相同。在

相关问题 更多 >