API

MyCommon.cs 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Text.RegularExpressions;
  3. namespace UnivateProperties_API.Helpers
  4. {
  5. public static class MyCommon
  6. {
  7. public static bool IsValidEmail(string item)
  8. {
  9. if (!string.IsNullOrEmpty(item))
  10. {
  11. Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
  12. Match match = regex.Match(item);
  13. return match.Success;
  14. }
  15. else return false;
  16. }
  17. public static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
  18. {
  19. if (password == null) throw new ArgumentNullException("password");
  20. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  21. using (var hmac = new System.Security.Cryptography.HMACSHA512())
  22. {
  23. passwordSalt = hmac.Key;
  24. passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  25. }
  26. }
  27. public static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
  28. {
  29. if (password == null) throw new ArgumentNullException("password");
  30. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  31. if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
  32. if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
  33. using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
  34. {
  35. var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  36. for (int i = 0; i < computedHash.Length; i++)
  37. {
  38. if (computedHash[i] != storedHash[i]) return false;
  39. }
  40. }
  41. return true;
  42. }
  43. }
  44. }