C# MD5加密文本、文件

/// <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;
	}
}
posted @ 2020-01-15 11:24  鸿焱  阅读(2901)  评论(0编辑  收藏  举报