.net中MD5使用方法
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace MD5练习
{
public static class MD5String
{
/// <summary>
/// 字符串转换
/// </summary>
/// <param name="str">要转换的字符串</param>
/// <returns></returns>
public static string GetMD5String(string str)
{
MD5 md5 = MD5.Create();
byte[] b = Encoding.UTF8.GetBytes(str);
byte[] md5b = md5.ComputeHash(b);
md5.Clear();
StringBuilder sb = new StringBuilder();
foreach (var item in md5b)
{
sb.Append(item.ToString("x2"));
}
return sb.ToString();
}
/// <summary>
/// 文件转成MD5
/// </summary>
/// <param name="path">完整路径</param>
/// <returns></returns>
public static string GetMD5FileString(string path)
{
StringBuilder sb = new StringBuilder();
using (FileStream fs = File.OpenRead(path))
{
MD5 md5 = MD5.Create();
byte[] b = md5.ComputeHash(fs);
md5.Clear();
foreach (var item in b)
{
sb.Append(item.ToString("x2"));
}
}
return sb.ToString();
}
}
}
作者 xhccom的专栏
补充:综合编程 , 安全编程 ,