MD5Encrypt.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.IO;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using ZhonTai.Common.Extensions;
  5. namespace ZhonTai.Common.Helpers;
  6. /// <summary>
  7. /// MD5加密
  8. /// </summary>
  9. public class MD5Encrypt
  10. {
  11. /// <summary>
  12. /// 16位MD5加密
  13. /// </summary>
  14. /// <param name="password"></param>
  15. /// <param name="lowerCase"></param>
  16. /// <returns></returns>
  17. public static string Encrypt16(string password, bool lowerCase = false)
  18. {
  19. if (password.IsNull())
  20. return null;
  21. using var md5 = MD5.Create();
  22. return md5.ComputeHash(Encoding.UTF8.GetBytes(password)).ToHex(lowerCase);
  23. }
  24. /// <summary>
  25. /// 32位MD5加密
  26. /// </summary>
  27. /// <param name="password"></param>
  28. /// <param name="lowerCase"></param>
  29. /// <returns></returns>
  30. public static string Encrypt32(string password = "", bool lowerCase = false)
  31. {
  32. if (password.IsNull())
  33. return null;
  34. using var md5 = MD5.Create();
  35. string pwd = string.Empty;
  36. byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
  37. var format = lowerCase ? "x2" : "X2";
  38. foreach (var item in s)
  39. {
  40. pwd = string.Concat(pwd, item.ToString(format));
  41. }
  42. return pwd;
  43. }
  44. /// <summary>
  45. /// 64位MD5加密
  46. /// </summary>
  47. /// <param name="password"></param>
  48. /// <returns></returns>
  49. public static string Encrypt64(string password)
  50. {
  51. if (password.IsNull())
  52. return null;
  53. using var md5 = MD5.Create();
  54. byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
  55. return s.ToBase64();
  56. }
  57. public static string GetHash(Stream stream)
  58. {
  59. StringBuilder sb = new();
  60. using var md5 = MD5.Create();
  61. byte[] hashBytes = md5.ComputeHash(stream);
  62. foreach (byte bt in hashBytes)
  63. {
  64. sb.Append(bt.ToString("x2"));
  65. }
  66. return sb.ToString();
  67. }
  68. }