简体   繁体   中英

Decryption with openssl of a string encrypted with nodejs crypto (public private key pair)

I'm quite new in the encryption world and I'm facing a problem not sure if I can resolve or if my previous steps were wrong.

Situation :

The user generate a public/private key pair with this command :

openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
openssl rsa -pubout -in private_key.pem -out public_key.pem

I will then encrypt a generated UUID in a nodejs application with the public key with this code :

import * as crypto from "crypto";

// ...

const uuidBuffer = Buffer.from(generatedUUID);
const encryptedUUID = crypto.publicEncrypt(publicKey, keyBuffer).toString("base64");

Then this encrypted UUID is stored in a DB.

Later the user can download in my frontend the encrypted UUID coming from the DB in a .txt file.

const blob = new Blob([encryptedUUID], { type: "txt" });
saveAs(blob, "encrypted-password.txt");

And then it should be able to decrypt the generated UUID from the .txt file with this command (which is not working) :

openssl pkeyutl -decrypt -inkey private_key.pem -in encrypted-password.txt -out decrypted-password.txt

I have this error :

Public Key operation error
40A79CA2EC7F0000:error:0200006C:rsa routines:rsa_ossl_private_decrypt:data greater than mod len:../crypto/rsa/rsa_ossl.c:406:

I understand based on my research it's related to the size of what's encrypted, but I'm really confused because if I decrypt using nodejs with this code it's working :

import * as crypto from "crypto";

// ...
const dec1 = crypto.privateDecrypt(
  privateKey,
  Buffer.from(encryptedUUID, "base64")
);
console.log(decryptedUUID.toString());

Am I doing something wrong during the key generation, encryption or the openssl decryption?

In advance any help is much appreciated :) Thanks

Was able to solve it with some more research and help in the comments thanks Dave.

The missing step was to convert back the encrypted password text file from base64.

openssl base64 -d -A <encrypted-password.txt >encrypted.bin

Then I can use the openssl command to decrypt the encrypted.bin file.

openssl rsautl -decrypt -inkey private_key.pem -in encrypted.bin -out decrypted-password.txt -oaep

Important note, I needed to add the -oaep argument also because node crypto use OAEP . without this argument there was still an error because of the padding that time!

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