一、在須要用到加密的地方可使用.net中的md5相關的類生成md5給文件加密。數組
二、基本思路:ui
將文件也好,字符串也好,轉成字節數組,再利用.net的md5相關類生成md5相關字符串,再將字符串轉成16進制。this
三、具體的例子:加密
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Runtime.InteropServices; 6 using System.Security.Cryptography; 7 using System.IO; 8 using System.Diagnostics; 9 10 namespace MD5 11 { 12 public class MD5Hash 13 { 14 public MD5Hash() 15 { 16 this.md5 = MD5.Create(); 17 } 18 19 public string CalculateFile(string filePath) 20 { 21 string reuslt = string.Empty; 22 23 try 24 { 25 reuslt = Calculate(System.IO.File.ReadAllBytes(filePath)); 26 } 27 catch (Exception e) 28 { 29 reuslt = string.Empty; 30 } 31 32 return reuslt; 33 } 34 35 public string Calculate(byte[] buffer) 36 { 37 return Format(md5.ComputeHash(buffer)); 38 } 39 40 private string Format(byte[] source) 41 { 42 StringBuilder result = new StringBuilder(string.Empty); 43 44 Array.ForEach(source, (value) => result.Append(value.ToString("X2"))); 45 46 return result.ToString(); 47 } 48 49 public string Calculate(string message) 50 { 51 return Calculate(message, Encoding.UTF8); 52 } 53 54 public string Calculate(string message, Encoding encoder) 55 { 56 return Calculate(encoder.GetBytes(message)); 57 } 58 59 private MD5 md5; 60 } 61 }