我在当前项目中使用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中是否有类似的功能?
答案 0 :(得分:5)
我遇到了同样的问题并且花了太多时间,但我最终找到了一条路。
我找到并使用了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);
希望这可能会有所帮助。
答案 1 :(得分:1)
解密数据
示例数据:
MIICTgYJKoZIhvcNAQcDoIICPzCCAjsCAQAxggHGMIIBwgIBADCBqTCBmzELMAkGA1UEBhMCREUxEjAQBgNVBAgMCUZyYW5jb25pYTEQMA4GA1UEBwwHQW5zYmFjaDEVMBMGA1UECgwMU3RlZmFuIFNpZWdsMRIwEAYDVQQLDAlHZWllcmxlaW4xFjAUBgNVBAMMDUdlaWVybGVpbiBERVYxIzAhBgkqhkiG9w0BCQEWFHN0ZXNpZUBicm9rZW5waXBlLmRlAgkA1FQcQNg14vMwDQYJKoZIhvcNAQEBBQAEggEAJhWQz5SniCd1w3A8uKVZEfc8Tp21I7FMfFqou + UOVsZCq7kcEa9uv2DIj3o7zD8wbLK1fuyFi4SJxTwxkR0a6V4bbonIpXPPJ1f615dc4LydAi2tv5w14LJ1Js5XCgGVnkAmQHDaW3EHXB7XT4w9PR3 + TCS / 5YAnWaM6Es38zCKHd7TnHpuakplIkwSK9rBFAyA1g / IyTPI + ktrEEHcVuJcz / 7eTlF6wJEa2HL8F1TVWuL0p / 0GsJP / 8y0MYGdCdtr + TIVO // 3YGhoBlN4tnheFT / jRAzfCZtflDdgAukW24CekrJ1sG2M42p5cKQ5rGFQtzNy / n8EjtUutOHD5YITBsBgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBBmlpfy3WrYj3uWW7 + xNEiHgEAm2mfSF5xFPLEqqFkvKTM4w8PfhnF0ehmfQNApvoWQRQanNWLCT + Q9GHx6DCFjTUHl + 53x88BrCl1E7FhYPs92
let data = '-----BEGIN PKCS7-----\r\n' + body + '\r\n-----END PKCS7-----\r\n';
let p7d = forge.pkcs7.messageFromPem(data)
let privateCert = forge.pki.decryptRsaPrivateKey(fs.readFileSync(privateCertPath),'password');
p7d.decrypt(p7d.recipients[0], privateCert);
console.log(p7d.content)