Encrypting using node-forge and decrypting using python with RSA-OAEP

喜夏-厌秋 提交于 2019-12-12 01:45:25

问题


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"

I exported public and private keys using

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

I exported the encrypted text using

ciphertext_base64 = forge.util.encode64(ciphertext)

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.
>>> 

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

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


回答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))


来源:https://stackoverflow.com/questions/35544547/encrypting-using-node-forge-and-decrypting-using-python-with-rsa-oaep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!