public static string GetSaltedPassword(string password, string salt, SaltMethod saltMethod = SaltMethod.DoubleSalt) { if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("password"); } if (string.IsNullOrWhiteSpace(salt)) { throw new ArgumentNullException("salt"); } switch (saltMethod) { case SaltMethod.PreSalt: return(salt + password); case SaltMethod.PostSalt: return(password + salt); case SaltMethod.SplitSalt: int saltSize = salt.Length; int halfSaltSize = saltSize / 2; string preSalt = salt.Substring(0, halfSaltSize); string postSalt = salt.Substring(halfSaltSize); return(preSalt + password + postSalt); case SaltMethod.SparseSalt: string result = ""; char[] passwordChars = password.ToCharArray(); char[] saltChars = salt.ToCharArray(); int maxLoop = Math.Min(passwordChars.Length, saltChars.Length); for (int i = 0; i < maxLoop; i++) { result += passwordChars[i] + saltChars[i]; } if (passwordChars.Length > maxLoop) { result += password.Substring(maxLoop); } else if (saltChars.Length > maxLoop) { result += salt.Substring(maxLoop); } return(result); default: //DoubleSalt return(salt + password + salt); } }
public static string ComputeHash(string password, string salt, SaltMethod saltMethod = SaltMethod.DoubleSalt, HashSize hashSize = HashSize.S160) { if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("password"); } if (string.IsNullOrWhiteSpace(salt)) { throw new ArgumentNullException("salt"); } string saltedPassword = GetSaltedPassword(password, salt, saltMethod); byte[] bytesOfString = RandomStringGenerator.GetBytesFromString(saltedPassword); byte[] hash = ComputeHash(bytesOfString, hashSize); return(RandomStringGenerator.ToEncodedString(hash)); }
public static bool VerifyPassword(string password, string salt, string storedHash, SaltMethod saltMethod = SaltMethod.DoubleSalt, HashSize hashSize = HashSize.S160) { if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("password"); } if (string.IsNullOrWhiteSpace(salt)) { throw new ArgumentNullException("salt"); } string verifyHash = ComputeHash(password, salt, saltMethod, hashSize); return(verifyHash == storedHash); }