PKCS7加密在Node.js中解密 [英] PKCS7 encrypt decrypt in Node.js
问题描述
我在当前项目中使用pkcs7加密解密.我想从PHP更改为Node.js. Node.js中是否有pkcs7加密/解密?
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 ?
在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中是否有类似的功能?
Is there any similar function like this in Node.js ?
推荐答案
我遇到了同样的问题,花了太多时间,但最终找到了解决方法.
I've faced the same issue and spent too much time but I found a way in the end.
我找到并使用了 forge 开源库.您只需按照以下步骤将其添加到您的项目中:
I found and used forge open source lib. You can simply add to your project by following:
npm install node-forge
然后,下面的代码段以PKCS#7
格式执行加密.
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();
此代码块将对您提供的内容进行加密,并返回具有DER
输出格式的字节数组.
This code block will encrypt the content you provided and return a byte array with DER
output format.
您可以通过以下操作将字节数组转换为UTF-8
字符串:
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);
希望这会有所帮助.
这篇关于PKCS7加密在Node.js中解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!