编程语言
首页 > 编程语言> > C# 和 Python 的 hash_md5加密方法

C# 和 Python 的 hash_md5加密方法

作者:互联网

C#版本1:

        public static string GenerateMD5Hash(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] byteArray = Encoding.UTF8.GetBytes(str);
            byteArray = md5.ComputeHash(byteArray);

            string hashedValue = "";
            foreach (byte b in byteArray)
            {
                hashedValue += b.ToString("x2");
            }
            return hashedValue;
        }

C#版本2:

        public static string GenerateMD5Hash(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] byteArray = Encoding.UTF8.GetBytes(str);
            byteArray = md5.ComputeHash(byteArray);
            StringBuilder mdStrBuff = new StringBuilder();
            for (int i = 0; i < byteArray.Length; i++)
            {
                if ((0xFF & byteArray[i]).ToString("x").Length == 1)
                {
                    mdStrBuff.Append("0");
                }
                mdStrBuff.Append((0xFF & byteArray[i]).ToString("x"));
            }
            string r = mdStrBuff.ToString();
            return r;
        }

Python版本:

def hash_md5(s):
    res = s 
    h = hashlib.md5()
    h.update(res.encode(encoding='utf-8'))
    return h.hexdigest()

(这三种方式最终加密完成的结果都相同的)

转自此处,请点击

标签:byteArray,hash,string,mdStrBuff,C#,Python,MD5CryptoServiceProvider,ToString,md5
来源: https://www.cnblogs.com/19930521zhang/p/15039878.html