SecurityHelper.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace Common
  5. {
  6. public class SecurityHelper
  7. {
  8. //开发员
  9. public static string Me = "VollYoung.com";
  10. /// <summary>
  11. /// 给一个字符串进行MD5加密
  12. /// </summary>
  13. /// <param name="strText">待加密字符串</param>
  14. /// <returns>加密后的字符串</returns>
  15. public static string Md5Encrypt(string strText)
  16. {
  17. using (MD5 md5Hash = MD5.Create())
  18. {
  19. string hash = GetMd5Hash(md5Hash, strText);
  20. return hash;
  21. }
  22. }
  23. static string GetMd5Hash(MD5 md5Hash, string input)
  24. {
  25. // Convert the input string to a byte array and compute the hash.
  26. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
  27. // Create a new Stringbuilder to collect the bytes
  28. // and create a string.
  29. StringBuilder sBuilder = new StringBuilder();
  30. // Loop through each byte of the hashed data
  31. // and format each one as a hexadecimal string.
  32. for (int i = 0; i < data.Length; i++)
  33. {
  34. sBuilder.Append(data[i].ToString("x2"));
  35. }
  36. // Return the hexadecimal string.
  37. return sBuilder.ToString();
  38. }
  39. // Verify a hash against a string.
  40. static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
  41. {
  42. // Hash the input.
  43. string hashOfInput = GetMd5Hash(md5Hash, input);
  44. // Create a StringComparer an compare the hashes.
  45. StringComparer comparer = StringComparer.OrdinalIgnoreCase;
  46. if (0 == comparer.Compare(hashOfInput, hash))
  47. {
  48. return true;
  49. }
  50. else
  51. {
  52. return false;
  53. }
  54. }
  55. }
  56. }