[英]Generate Base64 MD5 hash of byte array
我在我的 c# web api 中实现了以下安全编码:
string testStr = "test";
ASCIIEncoding encoding = new ASCIIEncoding(); //using System.Text;
byte[] byteData = encoding.GetBytes(testStr);
MD5 md5 = MD5.Create(); //using System.Security.Cryptography;
string hash = md5.ComputeHash(byteData);
string md5Base64 = Convert.ToBase64String(hash);
我将这个md5Base64
字符串绑定在标头中并在 API 请求中进行比较。 当我从 C# 代码点击 API 时,这很好用。 现在我需要在 javascript 中使用它,因此需要与上述代码等效的 js。
我试过以下,但它给出了不同的输出:
var testStr = 'test';
var byteData = testStr.split ('').map(function (c) { return c.charCodeAt (0); });
var hash = MD5(value.join(','));
var md5Base64 = btoa(hash);
这里使用的MD5
函数来自https://stackoverflow.com/a/33486055/7519287
请让我知道这里有什么问题。
您的 JavaScript 代码的问题在于您进行了不必要的转换: MD5
已经接受了一个字符串。 此外,散列后需要更多的转换。
如果我们有以下 C# 代码:
string tmp = "test";
byte[] bTmp = System.Text.Encoding.UTF8.GetBytes(tmp);
byte[] hashed = null;
using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
{
hashed = md5.ComputeHash(bTmp);
}
Console.WriteLine(Convert.ToBase64String(hashed));
那么等效的 JavaScript 代码是:
var tmp = 'test';
var hashed = hex2a(MD5(tmp)); // md5 src: https://stackoverflow.com/a/33486055/7519287
// src: https://stackoverflow.com/a/3745677/3181933
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
alert(btoa(hashed));
因为 MD5 返回一个十六进制字符串,所以您必须先将其转换为 ASCII,然后才能对其进行 base64 编码。 我想知道你是否需要base64编码? MD5 通常表示为十六进制字符串。 也许在 C# 方面,您可以使用BitConverter.ToString(hashed).Replace("-", "")
来获取 MD5 哈希的十六进制字符串,而不是Convert.ToBase64String(hashed)
? 然后你可以简单地在 JavaScript 中使用MD5(tmp)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.