Click here to Skip to main content
15,936,517 members
Articles / Web Development / HTML

Hashing Passwords using ASP.NET's Crypto Class

Rate me:
Please Sign up or sign in to vote.
4.60/5 (30 votes)
20 Nov 2014CPOL8 min read 134.5K   3K   45   20
This article provides an overview of the hashing process of passwords in ASP.NET's Crypto class.


This article would provide the concept of cryptography and the namespaces and classes introduced in ASP.NET for easy coding to get the encryptions done in no time, yeah with shorter code as well.


Cryptography and protecting the data has always been the main point of interest for all computer programmers and enthusiasts. This enables them to secure their servers and to prevent any unauthorized data access. Usually, hackers attempt to gain access to a user's account data by logging into his account using his password. That is why it has always been a good approach to first encrypt the password and other sensitive information of a user's account and then store into the databases since SQL injection like methods can easily reveal the data stored in the database and hacker might be able to consume the information stored there.


Cryptography is a method used to protect the sensitive information and data from other parties that might use that data for any illegal activity.

Cryptography in ASP.NET

ASP.NET is a server-side programming language and provides a bunch of new namespaces for the programmers built on the .NET framework that makes it easy for the programmers to focus on the UI and UX of the web site and not the core features and processes that run the web site.

ASP.NET team has provided a new class as Crypto present inside the System.Web.Helpers namespace of Web Pages framework.

Hashing and Crypto Technique

It is worth noting and explaining what is hashing and how it is used to save the passwords.

Hashing is a process in which a password (from human understand form) is converted into a non-understandable form of string. That string is not directly, nor indirectly understandable by the humans. Hashing is used to change the password in any sense so that any one with rights to see the data in the database can never get the password to use the user's account for any purpose.

Salting is another technique used to make the hashing process faster. Salt is just a bunch of more characters that you add to the input before the hashing process takes place. This would create a much more strong hashing result and the string returned would be even stronger than before. But salting requires you to save the salt that was used while hashing the password since it cannot be regenerated.

It is also worth noting that once hashed, the string cannot be converted back to the original string that was passed at the time of hashing.

Salting the Hello World

Salting is just an extra layer, that will be added to the password, as image shows that the salted password is not like the password that was sent. An extra character(s) is added to it. It plays its role for storing the same password's hash as a different hash value for different users. For example, in the following image, two same users use the same password "bob" but their salt; that was generated at their registration time, is different so the same password for them is saved differently. 

Salting is used to minimize any errors or hacking issues that were caused by the attempt of an hacker to try out every possible permutation, combination of the characters in the English alphabets. 

Removing ambiguity

Using the Crypto Class

The Crypto classes contain the simplified versions of the Cryptography that was available though .NET programming and the methods are simple enough for any web developer to easily make the passwords secure in his/her web application.

The class is a static class, which means you cannot create an instance of this class.

Using the Methods

Crypto class exposes the following methods for working purposes in ASP.NET hashing process.

  1. string GenerateSalt()

    This method generates a new Salt to be added to the input string before the hashing process would start. This string needs to be saved because recreating of an exact match is almost impossible.

  2. string Hash()

    This function hashes the input string using either the default (SHA-256) algorithm or user can pass an algorithm for the ASP.NET to use to hash the password into.

  3. string HashPassword()

    This function returns an RFC 2898 hash value of the input string passed by the user.

  4. string SHA1()

    Returns the SHA1 hashed value for the input string provided.

  5. string SHA256()

    Same as the above, but the algorithm used is SHA-256.

  6. bool VerifyHashedPassword()

    This method can be used by developers while authenticating the users. Because this method would check for the password sent by the user. Salt for the user would be saved in the database, and that salt would be added to the Password string provided by the user and then hashing would proceed resulting into the hashed value, if both values (the hashed value in database) and the value from user match then it returns true.

Using them in website

You can directly use these functions in your Web Pages application since Web Pages application already contains the System.Web.Helpers namespace in it; Crypto is available in .cshtml files.

You can use the ASP.NET sample website I have attached to the tip to test the class, or you can read the tip to understand this concept. The HTML markup of the website can be changed to this:

<form method="post">
    <p>Write the string as a password that would be encrypted using 
   <span style="color: #0094ff; 
   font-family: Consolas;">Crypto</span> class of ASP.NET Web Pages.</p>
    <input type="password" name="password" autofocus />
    <input type="submit" value="Submit" />

    <p>Password: @password</p>
    <p>MD5 Hashed result: @hashed</p>
    <p>SHA256 result: @sha256</p>
    <p>SHA1 result: @sha1</p>
    <p>Salt: @salt</p>
    <p>HashedPassword: @hashedPassword</p>
    <p>Verify: @verify.ToString()</p>

Note: Above HTML uses Razor scripting to enter the variable data from server into the HTML markup.

The server side code now would be as follows:

// Create the variables...
// Remember: This password is just being shown to show the actual text being passed, 
// In real applications you shouldn't show the password to the User.
var password = "";
var hashed = "";
var sha256 = "";
var sha1 = "";

var salt = "";

var hashedPassword = "";
var verify = false;
// If the request is a POST request, then
if (IsPost)
   // Get the password
   password = Request.Form["password"];
   // Run the functions on the code, 
   hashed = Crypto.Hash(password, "MD5");
   sha256 = Crypto.SHA256(password);
   sha1 = Crypto.SHA1(password);

   salt = Crypto.GenerateSalt();

   hashedPassword = Crypto.HashPassword(password);

   // First parameter is the previously hashed string using a Salt
   verify = Crypto.VerifyHashedPassword("{hash_password_here}", password);
How to use the salt

Accidently I forgot to show how to use the salt in password hashing, thank you to Waqas for his comment so that I can mention this part also. Actually a salt is just a random string that is appended (or prepended) to the password string. The usage and need of salt is just to overcome the problem of rainbow attacks and dictionary attacks. A salt is a random string that dictionary attack or rainbow table may not have. 

In the code, it would be something like, 

hashedPassword = Crypto.HashPassword(salt + password); // prepending the salt

A personal tip: Always generate a new salt for every user and their every password. Using the same salt would make it easier for attacker to determine what is the string being appended or prepended. Making it a real random would overcome this problem. Even if attackers gets the salt of one account he can never get the rest of passwords because of random salts. 

Although using their email's first few character may seem to do the trick. But that is no strong neither is it safe

Crypto.Hash method

Crypto.Hash() method can accept two parameters, one parameter is the string that you would pass for hashing purpose and the second one is the algorithm to use. In this article, I am passing MD5 algorithm; default is SHA-256. I have passed MD5 because no other code of Crypto would hash the password using MD5 algorithm. It is an unsecure algorithm and can be easily be cracked and converted back to a human-readable correct password; initial password that was used.

You should always use the SHA-256 algorithm or SHA-1 instead of MD5.

Crypto.HashPassword method

This method is the main and recommended method of hashing the passwords in your ASP.NET applications. You pass the password as a parameter and the function hashes it. According to the MSDN documentation for this method, the remarks on this are:


The password hash is generated with the RFC 2898 algorithm using a 128-bit salt, a 256-bit subkey, and 1000 iterations. The format of the generated hash bytestream is {0x00, salt, subkey}, which is base-64 encoded before it is returned.

This makes the password hash strong and the Crypto.VerifyHashedPassword() can easily verify the password to be accurate or false.

Running the application; for testing

Run the web page, enter the password as "CodeProject" you will find the following web page.

First run

Notice that there is a "False" infront of Verify, that is because we're not passing the correct Hash code for the CodeProject password to check against. Let's paste the hashed password from the result to the source code in the Visual Studio (or whatever IDE you're using). Copy the text in front of HashedPassword and paste it in the function that would return the VerifyHashedPassword, as:

verify = Crypto.VerifyHashedPassword("{here}", password);

Once done, re-submit the password, "CodeProject"; same password this time again.

Password matched

You will see that this time it didn't complain. Although if you see that the hashed password string is different. This enables us to check for the password, even saving the same password differently.

Yes, there is a security for letter-cases; small case or capital case. You can try writing the password in small letters as "codeproject" and see that this time, it doesn't verify the password.

Doesn't match

This is helpful in saving the passwords and again checking them for authenticating the users. ASP.NET team has really paid a lot of attention in making this whole process very simple and easy for new developers to focus on the UX of the web application and just write a single line code to generate and save the hashed passwords for better security.

Points of Interest

MD5 based algorithm can be easily cracked, whereas SHA-1 or SHA-256 based algorithm are stronger and cannot be cracked easily. ASP.NET has cool set of namespaces and classes that can be used while programming in a web application and it enables a programmer to focus on only the UX and not the back-end coding to create a salt and other stuff.

Adding a salt makes the hashed password even more stronger to be cracked.

Once hashed, it is impossible to convert back.


  • First version of the post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

Questionverify using salt Pin
Member 34447344-Jul-17 11:46
Member 34447344-Jul-17 11:46 
QuestionMisleading article Pin
nmg1961-Feb-16 2:20
nmg1961-Feb-16 2:20 
GeneralMy vote of 4 Pin
VICK4-Aug-15 23:54
professional VICK4-Aug-15 23:54 
AnswerRe: My vote of 4 Pin
Afzaal Ahmad Zeeshan5-Aug-15 5:27
professionalAfzaal Ahmad Zeeshan5-Aug-15 5:27 
GeneralRe: My vote of 4 Pin
VICK5-Aug-15 23:25
professional VICK5-Aug-15 23:25 
QuestionDB schema Pin
Wali Ahmed28-Jan-15 23:08
Wali Ahmed28-Jan-15 23:08 
AnswerRe: DB schema Pin
Afzaal Ahmad Zeeshan29-Jan-15 3:48
professionalAfzaal Ahmad Zeeshan29-Jan-15 3:48 
QuestionPassword Recovery Pin
S M Hasan22-Nov-14 18:02
S M Hasan22-Nov-14 18:02 
AnswerRe: Password Recovery Pin
Afzaal Ahmad Zeeshan22-Nov-14 21:08
professionalAfzaal Ahmad Zeeshan22-Nov-14 21:08 
GeneralRe: Password Recovery Pin
S M Hasan23-Nov-14 23:04
S M Hasan23-Nov-14 23:04 
AnswerRe: Password Recovery Pin
Afzaal Ahmad Zeeshan24-Nov-14 9:44
professionalAfzaal Ahmad Zeeshan24-Nov-14 9:44 
QuestionCode in Image? Pin
Nelek21-Nov-14 3:37
protectorNelek21-Nov-14 3:37 
AnswerRe: Code in Image? Pin
Afzaal Ahmad Zeeshan21-Nov-14 4:19
professionalAfzaal Ahmad Zeeshan21-Nov-14 4:19 
SuggestionSalting Pin
DaveAuld21-Nov-14 1:11
professionalDaveAuld21-Nov-14 1:11 
AnswerRe: Salting Pin
Afzaal Ahmad Zeeshan21-Nov-14 1:35
professionalAfzaal Ahmad Zeeshan21-Nov-14 1:35 
GeneralRe: Salting Pin
Krzemo22-Nov-14 1:18
Krzemo22-Nov-14 1:18 
But what is a point in generating additional salt and storing it in database...

U (almost for sure) have data like user name and last password change time. Isn't it better to use them as a salt?

AnswerRe: Salting Pin
Afzaal Ahmad Zeeshan22-Nov-14 1:28
professionalAfzaal Ahmad Zeeshan22-Nov-14 1:28 
GeneralRe: Salting Pin
Krzemo22-Nov-14 2:00
Krzemo22-Nov-14 2:00 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun20-Nov-14 16:37
Humayun Kabir Mamun20-Nov-14 16:37 
AnswerRe: My vote of 5 Pin
Afzaal Ahmad Zeeshan20-Nov-14 18:57
professionalAfzaal Ahmad Zeeshan20-Nov-14 18:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.