Node js中的RSACryptoServiceProvider

时间:2017-04-10 18:14:47

标签: c# node.js signature

我必须在节点js中签名一个字符串,就像使用RSACryptoServiceProvider的C#应用​​程序一样。实际上它使用

X509Certificate2 certificate = new X509Certificate2("file.pfx", "aPassword", 
X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create();
rsa.FromXmlString(certificate.PrivateKey.ToXmlString(true));
signer = new RSAPKCS1SignatureFormatter(rsa);
signer.SetHashAlgorithm("SHA256");

byte[] signedData = signer.CreateSignature("a string");
string signedString = Convert.ToBase64String(signedData);

我尝试在节点js中做同样的事情,到目前为止,以这种方式使用jsonwebtoken

var kdrPrivateKey = fs.readFileSync('private_key.pem');
var authorizationSigned = jwt.sign("a string", kdrPrivateKey, { algorithm: 'RS256'});
var authorizationBase64 = Base64.encode(authorizationSigned);

我也以这种方式从file.pfx获得了private_key

openssl pkcs12 -in file.pfx -nocerts -out private_key.pem -nodes

我的问题,最后是,节点js代码是否等同于C#代码?如果没有,我如何以节点js的方式制作C#代码?

谢谢!

2 个答案:

答案 0 :(得分:0)

请参阅以下链接以实施数据签名:https://nodejs.org/api/crypto.html

答案 1 :(得分:0)

对节点使用RSA XML解密器。通过Node.js中的RSA XML C#私钥解密字符串。

var RSAXML = require('rsa-xml'),

// base64 encoded private rsa xml key
var privateKey1 = 'PFJTQUtleVZhbHVlPjxNb2R1bHVzPjUxbCtyaHRzRmQvQ3NOb0U5VW9kdWorS0Vqd0F2YWZUZmI1N3Zldit3b3ZRbjdoVURrdzlCbVVMOTdSSC9zaC9udVN2Qkl3RGRlVVZTZzJDaXo4bE5McmY0WTVlMmI1NUtNZVBzR3lIV29abXhpbkdQUzd1cjRLSkhPZmVCYStHeGRDOC80cFdCSjZFK3BCajNkQ2JQRFBLWVZ6N0RRTUhkWGNRWjRCcTR2OD08L01vZHVsdXM+PEV4cG9uZW50PkFRQUI8L0V4cG9uZW50PjxQPitRdkdsTE14anZMaHJFZ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XUrcGdnZ0hZUDNVQVA2RWdDODBzUzB6TzB1T2h0UGIzNDllOSs2WnhlMjJhaWV0WTFabFlQT201di9YbE5HZlhOZWQvbjhUYUJZRHB3YnZTVUw0T2M1eFJOeWFnU2x4Mi9GN1h3NHBkQmw0cG9LZ1U9PC9EPjwvUlNBS2V5VmFsdWU+';
var encBase64_2 = '4TkhLlVNK27LQXSRIftGCbwOI2qnBGD0eR61g53KAdw5J+BTpczLpdWGn/9v3I6xGPQYvTB1F2cmbcuBboNGa18b+8gigwbat9vTEuLjD/OKl2V+jpqKf3xxwYYuz1s05HyV8KWxbS01M/iwjWPrcNRWh3vWff9pRAu8Z6KQAQc=';

var rsa = new RSAXML();
// a private key
rsa.importKey(privateKey1, 'pKey1');
var decrypted1 = rsa.decrypt(encBase64_1, 'pKey1');
console.log('decrypted:', decrypted1);

// another private key
rsa.importKey(privateKey2, 'pKey2');
var decrypted2 = rsa.decrypt(encBase64_2, 'pKey2');
console.log('decrypted:', decrypted2);