2012-12-26 155 views
4

我在当前项目中使用pkcs7加密解密。我想从PHP更改为Node.js. Node.js中是否有pkcs7加密/解密?在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

感谢PHP中pkcs7加密的简明示例:) – thomastiger

+0

嘿!你有没有找到任何方法在Node.js中实现? – gokhanakkurt

+0

没有运气。那为什么使用PHP进行项目。 – saturngod

回答

2

我面临同样的问题,并花费太多时间来找到合适的方法。

我找到并使用了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); 

希望这有助于。

+0

解密怎么样? – saturngod

+1

@saturngod请看[this](https://github.com/digitalbazaar/forge#pkcs7)部分。有一个'decrypt()'方法提供。 – gokhanakkurt

+0

无法加载私钥。现在,我得到了与'var pem = forge.pkcs7.messageToPem(p7);'相同的pkcs7加密base64。但是,还不能解密。 – saturngod