0

我在我的 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

请让我知道这里有什么问题。

4

1 回答 1

0

您的 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# 方面,Convert.ToBase64String(hashed)您可以使用BitConverter.ToString(hashed).Replace("-", "")来获取 MD5 哈希的十六进制字符串,而不是 ?然后你可以简单地MD5(tmp)在 JavaScript 中使用。

于 2017-12-05T06:54:15.290 回答