我有一个将C#代码转换为NodeJS的任务。我陷入了转换。对我来说看起来有点复杂。任何帮助将不胜感激。
byte[] str = ASCIIEncoding.Unicode.GetBytes('mystring');
SHA1 sha1 = SHA1.Create();
byte[] hashdata = sha1.ComputeHash(str);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(PrivateKey);
byte[] signature = rsa.SignData(hashdata, new SHA1CryptoServiceProvider());
return Convert.ToBase64String(signature);
这就是我想出的。但这不会产生与C#代码相同的结果。
var convertString = require('convert-string');
var sha1 = require('js-sha1');
var rsaSign = require('jsrsasign');
var rsaUtil = require('jsrsasign-util');
var privateKeyFile = 'files/pvtKey'; //Its a PEM Private Key converted from XML Private Key.
/* -----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCYeml ...
-----END RSA PRIVATE KEY-----*/
var bytesArray = convertString.stringToBytes('mystring');
var messageDigest = sha1(bytesArray);
var privateKeyContent = rsaUtil.readFile(privateKeyFile);
var privateKey = rsaSign.KEYUTIL.getKey(privateKeyContent);
var sig = new rsaSign.KJUR.crypto.Signature({'alg': 'SHA1withRSA'});
sig.init(privateKey);
sig.updateHex(messageDigest);
var signedMsgDigest = sig.sign();
return Buffer.from(signedMsgDigest).toString('base64');
答案 0 :(得分:0)
经过长期的奋斗,我设法改变了自己。只是留在这里。可以为某人节省时间。
authhelper.js
var sha1 = require('js-sha1');
var rsaSign = require('jsrsasign');
var rsaUtil = require('jsrsasign-util');
var authhelper = {
generateAuthKey: function (str, privateKeyFile) {
// Change to bytes array with UTF-16 encoding
var bytesArray = this.stringToByteArray(str, 'utf16le');
// Hash result of step b with SHA1 algorithm to get message digest
var messageDigest = sha1(bytesArray);
// Sign message digest using private key (SHA1 with RSA)
var privateKeyContent = rsaUtil.readFile(privateKeyFile);
var privateKey = rsaSign.KEYUTIL.getKey(privateKeyContent);
var sig = new rsaSign.KJUR.crypto.Signature({'alg': 'SHA1withRSA'});
sig.init(privateKey);
sig.updateHex(messageDigest);
var signedMsgDigest = sig.sign();
// Encode with Base64
var authKey = Buffer.from(signedMsgDigest, 'hex').toString('base64');
return authKey;
},
stringToByteArray: function (str, encoding) {
var byteArr = [];
var buffer = new Buffer(str, encoding);
for (var i = 0; i < buffer.length; i++) {
byteArr.push(buffer[i]);
}
return byteArr;
}
};
module.exports = authhelper;
在routes.js中,导入authhelper.js并按以下方式使用它。
var authHelper = require('authhelper');
var str = 'mystring';
var privateKeyFile = 'files/pvtKey';
var authKey = authHelper.generateAuthKey(str, privateKeyFile);