Geeks With Blogs
.Nettuce Code Salad
I endeavoured to follow the CrackStation rules: Salted Password Hashing - Doing it Right
    public class SaltedHash
    {
        public string Hash { getprivate set; }
        public string Salt { getprivate set; }
 
        public SaltedHash(string password)
        {
            var saltBytes = new byte[32];
            using (var provider = new RNGCryptoServiceProvider())
                provider.GetNonZeroBytes(saltBytes);
            Salt = Convert.ToBase64String(saltBytes);
            Hash = ComputeHash(Salt, password);
        }
 
        static string ComputeHash(string salt, string password)
        {
            var saltBytes = Convert.FromBase64String(salt);
            using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltBytes, 1000))
                return Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256));
        }
 
        public static bool Verify(string salt, string hash, string password)
        {
            return hash == ComputeHash(salt, password);
        }
    }
Posted on Thursday, June 14, 2012 8:22 PM | Back to top


Comments on this post: Salt and hash a password in .NET

# re: Salt and hash a password in .NET
Requesting Gravatar...
Thanks for sharing this...been looking for this kind ofcode for so long! :)
Left by Sushi Digital on Jun 19, 2012 8:16 PM

# re: Salt and hash a password in .NET
Requesting Gravatar...
I cant wait for the day that I can write code like that.
Left by TTop on Jun 20, 2012 3:59 AM

# re: Salt and hash a password in .NET
Requesting Gravatar...
You should probably be calling Dispose on the RNGCryptoServiceProvider instance you're creating. A using block would be simplest.
Left by Joel on Jun 20, 2012 4:59 PM

# re: Salt and hash a password in .NET
Requesting Gravatar...
Also the SHA256 instance needs to be disposed as well.
Left by Joel on Jun 20, 2012 5:20 PM

# re: Salt and hash a password in .NET
Requesting Gravatar...
Thanks Joel!
Left by Jon on Jun 20, 2012 6:10 PM

# re: Salt and hash a password in .NET
Requesting Gravatar...
I'd also recommend using a SecureString type for the password input parameters where used in the method signatures as it protects the plain-text password value whilst in-memory.
Left by BobT on Jul 03, 2012 8:45 PM

# re: Salt and hash a password in .NET
Requesting Gravatar...
Here is an API for use in .NET which will securely perform Hashing and Key Stretching and similar to your implimentation will create Crypto Random Salt.

The difference is my API combines iterations of Hashing and AES encryption + Byte Swapping for key stretching.
Left by hdizzle on Oct 04, 2012 1:32 AM

# re: Salt and hash a password in .NET
Requesting Gravatar...
I need a password decrypting code for SHA1 hashing.
Left by Adewale on Apr 15, 2014 1:43 PM

Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net