Advertisement
Willcode4cash

PBKDF2Hash

Mar 11th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. public class PBKDF2Hash
  2. {
  3.     public const int SaltByteSize = 24;
  4.     public const int HashByteSize = 20; // to match the size of the PBKDF2-HMAC-SHA-1 hash
  5.     public const int PBKDF2Iterations = 1000;
  6.     public const int IterationIndex = 0;
  7.     public const int SaltIndex = 1;
  8.     public const int PBKDF2Index = 2;
  9.  
  10.     public static string HashPassword(string password)
  11.     {
  12.         var cryptoProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();
  13.         byte[] salt = new byte[SaltByteSize];
  14.         cryptoProvider.GetBytes(salt);
  15.         var hash = GetPBKDF2Bytes(password, salt, PBKDF2Iterations, HashByteSize);
  16.         return $"{PBKDF2Iterations}:{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
  17.     }
  18.  
  19.     public static bool ValidatePassword(string password, string correctHash)
  20.     {
  21.         char[] delimiter = { ':' };
  22.         var split = correctHash.Split(delimiter);
  23.         var iterations = Int32.Parse(split[IterationIndex]);
  24.         var salt = Convert.FromBase64String(split[SaltIndex]);
  25.         var hash = Convert.FromBase64String(split[PBKDF2Index]);
  26.         var testHash = GetPBKDF2Bytes(password, salt, iterations, hash.Length);
  27.         return SlowEquals(hash, testHash);
  28.     }
  29.  
  30.     private static bool SlowEquals(byte[] a, byte[] b)
  31.     {
  32.         var diff = (uint)a.Length ^ (uint)b.Length;
  33.         for (int i = 0; i < a.Length && i < b.Length; i++) diff |= (uint)(a[i] ^ b[i]);
  34.         return diff == 0;
  35.     }
  36.  
  37.     private static byte[] GetPBKDF2Bytes(string password, byte[] salt, int iterations, int outputBytes)
  38.     {
  39.         var PBKDF2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt);
  40.         PBKDF2.IterationCount = iterations;
  41.         return PBKDF2.GetBytes(outputBytes);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement