计算字符串和文件的MD5值

1、计算字符串的MD5值

public string GetMD5WithString(string sDataIn)
{
    string str = "";
    byte[] data = Encoding.GetEncoding("utf-8").GetBytes(str);
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] bytes = md5.ComputeHash(data);
    for (int i = 0; i < bytes.Length; i++)
    {
        str += bytes[i].ToString("x2");
    }
    return str;
}

2、计算文件的MD5值

public string GetMD5WithFilePath(string filePath)
{
    FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] hash_byte = md5.ComputeHash(file);
    string str = System.BitConverter.ToString(hash_byte);
    str = str.Replace("-", "");
    return str;
}

原文地址:http://www.cnblogs.com/RTdo/p/4483767.html

你可能感兴趣的:(C#)