我在当前项目中使用 pkcs7 加密解密。我想从 PHP 更改为 Node.js。 Node.js 中是否有 pkcs7 加密/解密?
在 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 中有类似的功能吗?
最佳答案
我遇到过同样的问题,花了太多时间,但我最终找到了办法。
我找到并使用了 forge开源库。您可以通过以下方式简单地添加到您的项目中:
npm install node-forge
然后,下面的代码片段以PKCS#7
格式进行加密。
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
的字节数组。
您可以通过以下方式将字节数组转换为 UTF-8
字符串:
var str = Buffer.from(bytes, 'binary').toString('utf8');
并且可以解密内容如下:
var recipient = p7.findRecipient(cert);
// decrypt
p7.decrypt(p7.recipients[0], privateKey);
希望这可能有所帮助。
关于node.js - PKCS7 在 Node.js 中加密解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14037917/