PKCS7 encrypt decrypt in Node.js

Problem

I am using pkcs7 encrypt decrypt in current project. I want to change from PHP to Node.js. Is there pkcs7 encrypt/decrypt in Node.js ?

In PHP,

<?php

$data = <<<EOD
Hello world
EOD;

// load key
$key = file_get_contents("mypublickey.crt");

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,array())) {
    // message encrypted - send it!

}
?>

to decrypt

<?php
// The certification stuff
$public = file_get_contents("mypublickey.crt");
$private = array(file_get_contents("myprivatekey.pem"), "mypassword");

$infile = tempnam("", "enc");
file_put_contents($infile, $encrypted); 
$outfile = tempnam("", "dec");

if(openssl_pkcs7_decrypt("enc.txt", "dec.txt", $public, $private))
{
    // Decryption successful
    echo file_get_contents("dec.txt");
}
?>

Is there any similar function like this in Node.js ?

Problem courtesy of: saturngod

Solution

I've faced the same issue and spent too much time to find an appropriate way.

I found and used forge open source lib. You can simply add to your project by following:

npm install node-forge

Then, code snippet below performs encryption with PKCS#7 format.

var forge = require('node-forge');

// create cert object
var cert = forge.pki.certificateFromPem(certOrPemString);
// create envelop data
var p7 = forge.pkcs7.createEnvelopedData();
// add certificate as recipient
p7.addRecipient(cert);
// set content 
p7.content = forge.util.createBuffer();
p7.content.putString('content to be encrypted');

// encrypt
p7.encrypt();

// obtain encrypted data with DER format
var bytes = forge.asn1.toDer(p7.toAsn1()).getBytes();

This code block will encrypt the content you provided and return a byte array with DER output format.

You can convert byte array to UTF-8 string by following:

var str = Buffer.from(bytes, 'binary').toString('utf8');

And you can decrypt the content as follows:

var recipient = p7.findRecipient(cert);
// decrypt
p7.decrypt(p7.recipients[0], privateKey); 

Hope this may help.

Solution courtesy of: gokhanakkurt

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.