1、在需要用到加密的地方可以使用.net中的md5相关的类生成md5给文件加密。
2、基本思路:
将文件也好,字符串也好,转成字节数组,再利用.net的md5相关类生成md5相关字符串,再将字符串转成16进制。
3、具体的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.IO;
using System.Diagnostics; namespace MD5
{
public class MD5Hash
{
public MD5Hash()
{
this.md5 = MD5.Create();
} public string CalculateFile(string filePath)
{
string reuslt = string.Empty; try
{
reuslt = Calculate(System.IO.File.ReadAllBytes(filePath));
}
catch (Exception e)
{
reuslt = string.Empty;
} return reuslt;
} public string Calculate(byte[] buffer)
{
return Format(md5.ComputeHash(buffer));
} private string Format(byte[] source)
{
StringBuilder result = new StringBuilder(string.Empty); Array.ForEach(source, (value) => result.Append(value.ToString("X2"))); return result.ToString();
} public string Calculate(string message)
{
return Calculate(message, Encoding.UTF8);
} public string Calculate(string message, Encoding encoder)
{
return Calculate(encoder.GetBytes(message));
} private MD5 md5;
}
}