Introduction
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.
Background
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
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 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.
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.
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.
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.
string HashPassword()
This function returns an RFC 2898 hash value of the input string
passed by the user.
string SHA1()
Returns the SHA1 hashed value for the input string
provided.
string SHA256()
Same as the above, but the algorithm used is SHA-256.
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" />
</form>
<div>
<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>
</div>
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:
var password = "";
var hashed = "";
var sha256 = "";
var sha1 = "";
var salt = "";
var hashedPassword = "";
var verify = false;
if (IsPost)
{
password = Request.Form["password"];
hashed = Crypto.Hash(password, "MD5");
sha256 = Crypto.SHA256(password);
sha1 = Crypto.SHA1(password);
salt = Crypto.GenerateSalt();
hashedPassword = Crypto.HashPassword(password);
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);
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:
Quote:
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.
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.
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.
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.
History
- First version of the post