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

标签 java python rsa pycrypto pycryptodome

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

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

关于java - Pycrypto RSA PKCS1 OAEP SHA256 与 Java 的互操作性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50394730/

相关文章:

java - 并行执行静态同步方法

java - 性能差异: map() vs peek() with setters

python - 如何反转标签的 One-Hot Encoding 以评估 ML/DL 模型?

security - 带有 RSA 公钥和私钥的 JWT

java - 用于查找超过 3 小时的条目的 Hibernate HQL 查询

java - 相当于ant中的mvn build-classpath

python - 使用 cElementTree : dealing with errors and line number in the file 在 python 中解析 XML 文件

Python JSON解析重复记录

rsa - 获取用于密码加密私钥的密码

java - Java 的 RSA 实现,BC 的替代方案