【问题标题】:Pycrypto RSA PKCS1 OAEP SHA256 Interoperability with JavaPycrypto RSA PKCS1 OAEP SHA256 与 Java 的互操作性
【发布时间】:2018-05-17 15:05:02
【问题描述】:

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

【问题讨论】:

    标签: java python rsa pycrypto pycryptodome


    【解决方案1】:

    在 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 对 Hash 和 MGF1 使用 SHA256,就像 Pycrypto 一样。

    【讨论】:

      猜你喜欢
      • 2013-06-11
      • 2014-05-23
      • 1970-01-01
      • 2013-09-27
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多