简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM