PasswordHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Security.Cryptography;
  3. namespace Quadarax.Foundation.Core.Business.Security
  4. {
  5. public static class PasswordHelper
  6. {
  7. public static string HashPassword(string password)
  8. {
  9. byte[] salt;
  10. byte[] buffer2;
  11. if (password == null)
  12. {
  13. throw new ArgumentNullException("password");
  14. }
  15. using (var bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8, HashAlgorithmName.SHA256))
  16. {
  17. salt = bytes.Salt;
  18. buffer2 = bytes.GetBytes(0x20);
  19. }
  20. byte[] dst = new byte[0x31];
  21. Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
  22. Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
  23. return Convert.ToBase64String(dst);
  24. }
  25. public static bool VerifyHashedPassword(string hashedPassword, string password)
  26. {
  27. byte[] buffer4;
  28. if (hashedPassword == null)
  29. {
  30. return false;
  31. }
  32. if (password == null)
  33. {
  34. throw new ArgumentNullException("password");
  35. }
  36. byte[] src = Convert.FromBase64String(hashedPassword);
  37. if ((src.Length != 0x31) || (src[0] != 0))
  38. {
  39. return false;
  40. }
  41. byte[] dst = new byte[0x10];
  42. Buffer.BlockCopy(src, 1, dst, 0, 0x10);
  43. byte[] buffer3 = new byte[0x20];
  44. Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
  45. using (var bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8, HashAlgorithmName.SHA256))
  46. {
  47. buffer4 = bytes.GetBytes(0x20);
  48. }
  49. return ByteArraysEqual(buffer3, buffer4);
  50. }
  51. private static bool ByteArraysEqual(byte[] b1, byte[] b2)
  52. {
  53. if (b1 == b2) return true;
  54. if (b1 == null || b2 == null) return false;
  55. if (b1.Length != b2.Length) return false;
  56. for (int i = 0; i < b1.Length; i++)
  57. {
  58. if (b1[i] != b2[i]) return false;
  59. }
  60. return true;
  61. }
  62. }
  63. }