使用 node-forge 加密并使用 python 和 RSA-OAEP 解密 [英] Encrypting using node-forge and decrypting using python with RSA-OAEP

查看:263
本文介绍了使用 node-forge 加密并使用 python 和 RSA-OAEP 解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以用 Javascript 加密:

I have following code to encrypt in Javascript:

var rsa = forge.pki.rsa;

var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001});

var ciphertext = keypair.publicKey.encrypt("zz xx yy", 'RSA-OAEP', {
  md: forge.md.sha256.create(),
  mgf1: {
    md: forge.md.sha1.create()
  }
});

keypair.privateKey.decrypt(ciphertext, 'RSA-OAEP', {
  md: forge.md.sha256.create(),
  mgf1: {
    md: forge.md.sha1.create()
  }
});
"zz xx yy"

我使用

forge.pki.privateKeyToPem(keypair.privateKey) // stored in pv.key
forge.pki.publicKeyToPem(keypair.publicKey) // stored in pb.key

我使用

ciphertext_base64 = forge.util.encode64(ciphertext)

我正在尝试使用 Crypto 库在 python 中解密它,如下所示,但出现错误:

I am trying to decrypt it in python using Crypto library as follows but getting an error:

>>> key = RSA.importKey(open('pv.key').read())
>>> cipher = PKCS1_OAEP.new(key)
>>> import base64
>>> ciphertext = base64.b64decode(ciphertext_base64)
>>> cipher.decrypt(ciphertext)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/PKCS1_OAEP.py", line 227, in decrypt
    raise ValueError("Incorrect decryption.")
ValueError: Incorrect decryption.
>>> 

如果我使用 python 中 pv.key 和 pb.key 中存在的密钥加密和解密一些文本字符串,它工作正常.

If I encrypt and decrypt some text string using the keys present in pv.key and pb.key in python, it works fine.

如何在python中进行伪造加密和解密工作?

How to get encryption in forge and decryption in python working?

推荐答案

pyCrypto 默认使用 SHA1 进行散列和 MGF1.如果您传入 SHA-256 进行散列,它也将用于 MGF1 (代码参考).所以需要专门设置hash为SHA-256,MGF1为SHA-1:

pyCrypto uses SHA1 for both hashing and MGF1 by default. If you pass in SHA-256 for hashing, it will also use that for MGF1 (code reference). So you need to specifically set hashing to SHA-256 and MGF1 to SHA-1:

cipher = PKCS1_OAEP.new(key, Crypto.Hash.SHA256, \
        lambda x,y: Crypto.Signature.PKCS1_PSS.MGF1(x,y, Crypto.Hash.SHA1))

这篇关于使用 node-forge 加密并使用 python 和 RSA-OAEP 解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆