Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PKCS7 encrypt decrypt in Node.js

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,

to decrypt

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

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

PKCS7 encrypt decrypt in Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×