C# 获取文本、文件的MD5值

280次阅读
没有评论

共计 1154 个字符,预计需要花费 3 分钟才能阅读完成。

废话不多说,直接看代码,代码如下

/// <summary>
/// MD5加密(16位)
/// </summary>
/// <param name="ConvertString"></param>
/// <returns></returns>
public static string Encrypt16(string ConvertString)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

    string CipherText = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(ConvertString)), 4, 8);
    CipherText = CipherText.Replace("-", "");
    return CipherText;
}

/// <summary>
/// MD5加密(32位)
/// </summary>
/// <param name="stringToEncrypt"></param>
/// <returns></returns>
public static string Encrypt32(string stringToEncrypt)
{
    string CipherText = "";

    MD5 md5 = MD5.Create();

    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(stringToEncrypt));

    for (int i = 0; i < s.Length; i++)
    {
        CipherText += s[i].ToString("X2");
    }

    return CipherText;
}

/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetMD5HashFromFile(string fileName)
{
    try
    {
        FileStream file = new FileStream(fileName, FileMode.Open);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] retVal = md5.ComputeHash(file);
        file.Close();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < retVal.Length; i++)
        {
            sb.Append(retVal[i].ToString("x2"));
        }
        return sb.ToString();
    }
    catch (Exception)
    {
        return null;
    }
}

正文完
 0
flames
版权声明:本站原创文章,由 flames 于2021-01-18发表,共计1154字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)