【问题标题】:Convert an byte array to MD5 Hash in react native在本机反应中将字节数组转换为 MD5 哈希
【发布时间】:2022-08-11 21:25:54
【问题描述】:

我有一个 C# 系统,它接收密码,并且使用此函数将此密码加密为 MD5 哈希。我已经阅读了很多帖子和建议,但我无法像在 C# 中那样创建 MD5 字节数组。

  public static string GetMD5HashData(string data)
    {
        //create new instance of md5
        MD5 md5 = MD5.Create();

        //convert the input text to array of bytes
        byte[] hashData = md5.ComputeHash(Encoding.Default.GetBytes(data));

        //create new instance of StringBuilder to save hashed data
        StringBuilder returnValue = new StringBuilder();

        //loop for each byte and add it to StringBuilder
        for (int i = 0; i < hashData.Length; i++)
        {
            returnValue.Append(hashData[i].ToString());
        }

        // return hexadecimal string
        return returnValue.ToString();

    }

这个函数的返回就是这个字符串207154234292557519022585191701391052252168.我需要在 React Native 中生成相同的字符串。 这部分Encoding.Default.GetBytes(数据)在里面C#我在 React native 中复制的函数,所以 C# 和 React 本机都从输入字符串返回相同的字节数组.

输入字符串:\'system123\' 字节数组:\'[115, 121, 115, 116, 101, 109, 49, 50, 51]\'

用于生成字节数组的 React 本机函数。

convertStringToByteArray = (str) =>{
var bufferedVal = Buffer.from(str, \'utf8\').toString(\'hex\');
String.prototype.encodeHex = function () {
var bytes = [];
for (var i = 0; i < this.length; ++i) {
 bytes.push(this.charCodeAt(i));
}

return bytes;
};

var byteArray = str.encodeHex();
return byteArray;
};

我尝试了一些库,如 crypto-js 用于 react-native 创建 MD5 哈希,但无法生成与 C# 相同的值 \'207154234292557519022585191701391052252168\'。有人可以帮我吗?

    标签: c# react-native encryption md5


    【解决方案1】:

    问题在于,与 js 代码相比,您在 C# 代码中使用了不同的编码。 尝试在您的代码中使用Encoding.UTF8 而不是Encoding.Default

    public static string GetMD5HashData(string data)
    {
        //create new instance of md5
        MD5 md5 = MD5.Create();
    
        //convert the input text to array of bytes
        byte[] hashData = md5.ComputeHash(Encoding.UTF8.GetBytes(data));
    
        //create new instance of StringBuilder to save hashed data
        StringBuilder returnValue = new StringBuilder();
    
        //loop for each byte and add it to StringBuilder
        for (int i = 0; i < hashData.Length; i++)
        {
            returnValue.Append(hashData[i].ToString());
        }
    
        // return hexadecimal string
        return returnValue.ToString();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      相关资源
      最近更新 更多