濮阳12345API

SaltAndHashHelper.cs 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace CallCenter.Utility
  8. {
  9. public class SaltAndHashHelper
  10. {
  11. /// <summary>
  12. /// 对用户输入的密码进行加密
  13. /// </summary>
  14. /// <param name="passWord">输入的明文密码</param>
  15. /// <param name="salt">加密过程中产生的盐值</param>
  16. /// <returns>加密后的密码值</returns>
  17. public static string GetHashSha256AndSalt(string passWord, out string salt)
  18. {
  19. //首先生成随机加密盐
  20. RandomNumberGenerator saltNumber = new RNGCryptoServiceProvider();
  21. byte[] s = new byte[256];
  22. saltNumber.GetBytes(s);
  23. salt = Convert.ToBase64String(s); //将盐值转化为字符串
  24. return GetHashSha256(passWord, salt);//针对盐值和密码一起应用hash加密函数,得到明文密码
  25. }
  26. /// <summary>
  27. /// 对用户输入的密码采用指定的盐值进行加密
  28. /// </summary>
  29. /// <param name="passWord">输入的明文密码</param>
  30. /// <param name="salt">指定的盐值</param>
  31. /// <returns>加密后的密码值</returns>
  32. public static string GetHashSha256(string passWord, string salt)
  33. {
  34. byte[] bytes = Encoding.Unicode.GetBytes(salt + passWord); //将盐值和密码进行组合
  35. SHA256Managed hashstring = new SHA256Managed();
  36. byte[] hash = hashstring.ComputeHash(bytes);//针对组合后的数据应用hash函数
  37. string hashString = string.Empty;
  38. foreach (byte x in hash)
  39. {
  40. hashString += String.Format("{0:x2}", x);
  41. }
  42. return hashString; //得到加密后的密文字符串
  43. }
  44. }
  45. }