This post examines how a user password can be securely stored. There are many blog posts elsewhere online that detail the importance behind securing passwords securely; this post will simply focus on the code which can accomplish the task. The extracts below are from a simple console application that demonstrates the method used to securely save and verify a user password.
In the Main method, firstly the user is prompted to enter their password which is immediately passed into the HashNewPassword method which itself salts and hashes the password and assigns it to the variable hashedPassword.
In the HashNewPassword method, the salt variable is declared as an array of bytes. Using the RNGCryptoServiceProvider from System.Security.Cryptography, a good standard salt is created. The salt, with the entered password, is then passed into the HashPassword method.
In the HashPassword method, the hash variable is declared as an array of bytes. To set the value of this variable, the password and salt are passed into Rfc2898DeriveBytes, along with the number of iterations to create the hash, in this case 1000. A greater number of iterations means a more securely hashed password, but it will take longer to run. Finally, we need to convert the arrays of bytes for the salt and the hash into a string which we can return. In a real application, this would make it easier to save to a database. The variable hashBytes is declared and the salt is added to the first 16 elements of the array and the hash is assigned to the last 16 elements of the array. Then hashBytes is converted to a string and returned.
The VerifyEnteredPassword method is used after the user enters their password for a second time. Both the re-entered password and the saved hashed password are entered as arguments. Firstly, the savedPasswordHash is converted into a string. Next, a 16 element array of bytes is declared for the salt, as before. The salt is copied from savedPasswordHashBytes and assigned to the local salt property. Finally, the passwordEntered is sent into the HashPassword method with the salt and is checked to ensure it is equal to savedPasswordHash.
Comments
Post a Comment