2012-03-21

ASP.Net Default Password Hash (+Salt)

Today I played around with custom user controls so I wondered if I could create my own login control, that would allow me to check credentials against the built-in ASP.net security mechanisms. The included Table structure is easy enough to understand, but it took me a while to find out how to apply salt and hashing algorithms to the entered user password to get the same hash that the ASP.net security mechanisms generate. Just to not forget it or to whoever might need it:


        public static string EncodePassword(string pass, string saltBase64)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(pass);
            byte[] src = Convert.FromBase64String(saltBase64);
 
            byte[] dst = new byte[src.Length + bytes.Length];
            System.Buffer.BlockCopy(src, 0, dst, 0, src.Length);
            System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
            HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
 
            byte[] inArray = algorithm.ComputeHash(dst);
            return Convert.ToBase64String(inArray);
        }


And if you have to create a new Salt, just use:


        public string CreateSalt(int saltLength)
        {
            //Create and populate random byte array
            byte[] randomArray = new byte[length];
            string randomString;
 
            //Create random salt and convert to string
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomArray);
            randomString = Convert.ToBase64String(randomArray);
            return randomString;
        }


Resources: forums.asp.netPeter Stathakos Blog

No comments:

Post a Comment