PKCS7在Node.js中encryption解密
我在当前项目中使用pkcs7encryption解密。 我想从PHP更改为Node.js。 Node.js中是否有pkcs7encryption/解密?
在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! } ?>
解密
<?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"); } ?>
在Node.js中是否有类似的函数?
我面临同样的问题,花了太多的时间来find一个合适的方法。
我find并使用伪造开源的lib。 您可以简单地添加到您的项目如下:
npm install node-forge
然后,下面的代码片段使用PKCS#7
格式执行encryption。
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();
此代码块将encryption您提供的内容,并返回DER
输出格式的字节数组。
您可以通过以下方式将字节数组转换为UTF-8
string:
var str = Buffer.from(bytes, 'binary').toString('utf8');
你可以解密内容如下:
var recipient = p7.findRecipient(cert); // decrypt p7.decrypt(p7.recipients[0], privateKey);
希望这可能有帮助。