MD5Helper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace AuthorizationSign
  7. {
  8. public class MD5Helper
  9. {
  10. /// <summary>
  11. /// 计算字节数组的 MD5 值
  12. /// </summary>
  13. /// <param name="buffer"></param>
  14. /// <returns></returns>
  15. public static string CalcMD5(byte[] buffer)
  16. {
  17. using (MD5 md5 = MD5.Create())
  18. {
  19. byte[] md5Bytes = md5.ComputeHash(buffer);
  20. return BytesToString(md5Bytes);
  21. }
  22. }
  23. /// <summary>
  24. /// 将得到的 MD5 字节数组转成 字符串
  25. /// </summary>
  26. /// <param name="md5Bytes"></param>
  27. /// <returns></returns>
  28. private static string BytesToString(byte[] md5Bytes)
  29. {
  30. StringBuilder sb = new StringBuilder();
  31. for (int i = 0; i < md5Bytes.Length; i++)
  32. {
  33. sb.Append(md5Bytes[i].ToString("X2"));
  34. }
  35. return sb.ToString();
  36. }
  37. /// <summary>
  38. /// 计算字符串的 MD5 值
  39. /// </summary>
  40. /// <param name="str"></param>
  41. /// <returns></returns>
  42. public static string CalcMD5(string str)
  43. {
  44. byte[] buffer = Encoding.UTF8.GetBytes(str);
  45. return CalcMD5(buffer);
  46. }
  47. /// <summary>
  48. /// 计算流的 MD5 值
  49. /// </summary>
  50. /// <param name="stream"></param>
  51. /// <returns></returns>
  52. public static string CalcMD5(Stream stream)
  53. {
  54. using (MD5 md5 = MD5.Create())
  55. {
  56. byte[] buffer = md5.ComputeHash(stream);
  57. return BytesToString(buffer);
  58. }
  59. }
  60. }
  61. }