Files
kridoo 6e91a0c7f0 111
2025-09-15 17:32:08 +08:00

71 lines
1.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class EncryptMD5
{
/// <summary>
/// 获取字符串MD5值
/// </summary>
/// <param name="sText"></param>
/// <param name="encoding">编码方式 utf8</param>
/// <param name="uppercase">true 大写false 小写</param>
/// <returns></returns>
public static string Encrypt(string sText, Encoding encoding, bool uppercase = false)
{
byte[] buffer = encoding.GetBytes(sText);
string s = Encrypt(buffer);
if (!uppercase)
s = s.ToLower();
return s;
}
/// <summary>
/// 获取字符串MD5值
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static string Encrypt(byte[] buffer)
{
//使用MD5这个抽象类的Creat()方法创建一个虚拟的MD5类的对象。
using (MD5 md5 = MD5.Create())
{
//使用MD5实例的ComputerHash()方法处理字节数组。
byte[] bufferNew = md5.ComputeHash(buffer);
string s = BitConverter.ToString(bufferNew, 0, bufferNew.Length);
return s.Replace("-", "");
}
}
/// <summary>
/// 获取流MD5值
/// </summary>
/// <param name="inputStream"></param>
/// <returns></returns>
public static string Encrypt(Stream inputStream)
{
using (MD5 mi = MD5.Create())
{
//开始加密
byte[] bufferNew = mi.ComputeHash(inputStream);
string s = BitConverter.ToString(bufferNew, 0, bufferNew.Length);
return s.Replace("-", "");
}
}
/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string EncryptFile(string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
return Encrypt(fs);
}
}
}