[英]Match C# MD5 hashing algorithm with node.js
I am having trouble matching a C# hashing algorithm with node, the problem seems to be the Unicode encoding. 我在将C#哈希算法与节点匹配时遇到麻烦,问题似乎是Unicode编码。 Is there a way to convert a string to Unicode then hash it and output it as hexadecimal?
有没有一种方法可以将字符串转换为Unicode,然后对其进行散列并将其输出为十六进制? Unfortunately I cannot change the c# code, it is out of my control.
不幸的是,我无法更改c#代码,这是我无法控制的。
node algorithm 节点算法
function createMd5(message) {
var crypto = require("crypto");
var md5 = crypto.createHash("md5");
return md5.update(message).digest('hex');
}
c# hashing algorithm C#哈希算法
private static string GetMD5(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
using (MD5 hasher = new MD5CryptoServiceProvider())
{
string hex = "";
hashValue = hasher.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex.ToLower();
}
}
Your suspicion of this being an encoding problem is correct. 您怀疑这是编码问题是正确的。 You can fix your node code with the following alteration, which will convert your message string into utf-16 (which is what .NET's default encoding is):
您可以通过以下更改来修复节点代码,该更改会将您的消息字符串转换为utf-16(.NET的默认编码是):
function createMd5(message) {
var crypto = require("crypto");
var md5 = crypto.createHash("md5");
return md5.update(new Buffer(message, 'ucs-2')).digest('hex');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.