Welcome :Guest

Congratulations!!!

Top 5 Contributors of the Month
Mayuri
Sandeep Singh
stevemarkayden
kumarfurima
Preethi

 Home >> Articles >> Security >> Post New Resource

# Cryptography : A Basic Introduction of Hashing and HashAlgo class for beginners Ã¢â‚¬â€œ Part 1

Posted By:Ravi Ranjan Kumar       Posted Date: October 24, 2012    Points: 200    Category: Security    URL: http://www.dotnetspark.com

This article enable you to understand the basic concept of Hashing and its related class.

### Hashing

Hash is a kind of process, signature, function which is responsible for translating information into a cryptic value. The concept of hash and encryption is almost same. In practical view Hash is an algorithm that takes an arbitrary block of data and returns a fixed-size bit string. Hashing is also known for its unidirectional process because it is not require dehashing or decrypting to get back data. In hashing the data which is needed to be encoded is often called the Ã¢â‚¬Å“message,Ã¢â‚¬Â and the outcome of hash value after processing is sometimes called the message digest or simply digests.
While hashing message, an algorithm is utilize which work is to map input values to a series of known output values. so given then same series of input values, a hash algorithm always produces the same output values. Hashing is an industry supported standard similar to encryption.

While creating and designing hash functions, we generally came across with ways:

• First one is we have nothing idea and info about the distribution of the incoming keys.
In such situation, hash function proved its importance because its evenly distributes the key range across the hash table.
• Second one is we have little bit idea and info about the distribution of the incoming keys.
In such situation, we should use a distribution-dependent hash function that can avoids assigning clusters of related key values to the same hash table slot.

#### Practical working of Hashing

As we know Hashing takes any amount of values(Plain Text and Binary) and then creates a constant-length hash representing a checksum for the data so in sense hashing something is a way of turning something (usually a key or a password) into a (usually fixed length string of characters.

LetÃ¢â‚¬â„¢s take an example which explains the working process of hashing.
We all daily log on our system either windows/linux/Mac/etc we have to authenticate our self in case if password is set for login. So what we think our password is kept private and secure so no one can trace or stole it. Lots of question in mind like

How we get authenticated by entering password ?
To know the solution of above question we should know the working process of hashing. While creating user account the password which is given by user is not stored by System. Actually a hash value of password is stored. Its all gone through consistent Hashing algorithm to hash plain text to hashed value. So whenever a user enters a password for authentication purpose, this password is not transported or stored. A hash of the password is transported for authentication instead of transporting the password in clear text. System Hashes the password entered by user by using the same hashing algorithm that was used while creating password when user create account.
It is clear System compares the entered hash value while login to the hash value stored while creating account. If the hashes matched the user is authenticated otherwise not authenticated.

Should we want to hash everything?
No doubt, itÃ¢â‚¬â„¢s a common assumption to use Hash to secure everything because of its powerful algorithm and way of hashing dataÃ¢â‚¬â„¢s to fixed constant length.
Why not we can but to make hashing more secure, we should always use salt values. We must also store salt value and keep it confidential and secure. So in such case whenever a hashed value needs to be verified, the input value is combined with the salt value and hashed to generate an output value. So then output hashed value is compared to stored hash value. In sense we can hash a our plain text as long as salt is correctly.
dont hash code

### Is both hashing and Encryption are Same ?

##### Note Ã¢â‚¬â€œ I used Google to get this cartoon pic.

Its usually a common reaction or can be a question for beginner who just put their step in Cryptography. Whatever knowledge of hashing is vital for developers to gain a complete understanding of security and cryptography and being beginner we should have almost basic idea about what hash called and how is different from Encryption.
As we read about Encryption in previous article series-Cryptography : Symmetric Encryption by Symmetric Algorithm ClassesÃ¢â‚¬â€œPart 1 is that Encryption is a scheme where an intelligible text is made unintelligible using a secure key. The security of the encrypted (Cipher) text resides in the key length and decryption process is a difficult without proper knowledge of the key. In sense while encryption a plain text using a secret algorithm, and sent to a second party who can decrypt the plain text back because they also has access to this secret algorithm.
where as, hashing is refer as one-way functions that compress arbitrary length strings into fixed short strings. Hash Functions can be designed using block ciphers using a secret key as a parameter along with the message that has to be hashed. The important thing and focus point about a hash value is that it is nearly impossible for any one to derive the original input value without knowing the data used to create the hash value. so we can see Hash working is not like encryption because Encrypting is a proper two-way function. ItÃ¢â‚¬â„¢s reversible, you can decrypt the mangled string to get original string if you have the key which is not possible in Hash

### Hash Algorithm Classes

The .Net Framework provides some great classes to implement Hashing. The HashAlgorithm class providesbase functionality for all hashing classes in the .Net Framework. The HashAlgorithm class is an abstract(MustInherit) class that is extended by the SHA1, MD, KeyedHashAlgorithm, RIPEMD160, SHA 256,SHA 384and SHA 512 classes where as each of the class is sued to hash data

### Hashing by using MD5 class

The MD5 class is an abstract(means must inherit) class which responsible to provides hashing functionality by using MD5 hashing algorithm.

What is MD5 class
The MD5 hashing algorithm is one of the two most commonly used hashing algorithms. There are known flaws in the algorithm and its known as its great features and its popularity.
in .Net Framework, the MD5 hashing algorithm class uses a 128-bit hash key and is extended by the MD5CryptoServiceProvder class which is also known as CSP class.

What is MD5CryptoServiceProvder(CSP) class
The MDCryptoServiceProvieder class extends the MD5 class. The MDCryptoServiceProvieder class that provides cryptographic service by wrapping unmanaged object that are external to the CLR(Common Language Runtime)

Implementation of MDCryptoServiceProvieder class

Here given code show you how to use MD5CryptoServiceProvider for hashing your data. GetMD5Hash is a function which need values as parameter. In function MD5provider is an instance of MD5CryptoServiceProvider. after creating instance Convert the input string to a byte array and compute the hash, at last managing Loop through each byte of the hashed data and format each one as a hexadecimal string

Note : To access MD5CryptoServiceProvider class you must need to mention System.Security.Cryptography Namespace

 `1` `using` `System.Security.Cryptography;`

Now create a function

 `01` `public` `static` `string` `GetMD5Hash(``string` `plaintext)`
 `02` `        ``{`
 `03` `            ``MD5CryptoServiceProvider MD5provider = ``new` `MD5CryptoServiceProvider();`
 `04` `            ``byte``[] hasedvalue = MD5provider.ComputeHash(Encoding.Default.GetBytes(plaintext));`
 `05` `            ``StringBuilder str = ``new` `StringBuilder();`
 `06` `            ``for` `(``int` `counter = 0; counter < hasedvalue.Length; counter++)`
 `07` `            ``{`
 `08` `                ``str.Append(hasedvalue[counter].ToString(``"x2"``));`
 `09` `            ``}`
 `10` `            ``return` `str.ToString();`
 `11` `        ``}`

How to use Function
you can simply use function by just passing value which need to be hashed as given sample of code.

 `1` `static` `void` `Main(``string``[] args)`
 `2` `       ``{`
 `3` `Console.WriteLine(``"Enter Value for Hashed"``);`
 `4` `           ``string` `yourvalue = Console.ReadLine();`
 `5`
 `6` `           ``string` `strhashed = GetMD5Hash(yourvalue);`
 `7` `           ``Console.WriteLine(``"Hashed Value : "` `+ strhashed);`
 `8` `      ``}`

What Output comes

How to Verify Hash

To Verify a hash against a string we can use StringComparer class which responsible to represents a string comparison operation that uses specific case and culture-based or ordinal comparison rules.

 `01` `static` `bool` `VerifyMD5hash(``string` `PlainText, ``string` `prevhashedvalue)`
 `02` `        ``{`
 `03`
 `04` `            ``string` `hashedvalue2 = GetMD5Hash(PlainText);`
 `05`
 `06` `            ``// Create a StringComparer an compare the hashes.`
 `07` `            ``StringComparer strcomparer = StringComparer.OrdinalIgnoreCase;`
 `08`
 `09` `            ``if` `(strcomparer.Compare(hashedvalue2, prevhashedvalue).Equals(0))`
 `10` `            ``{`
 `11` `                ``return` `true``;`
 `12` `            ``}`
 `13` `            ``else`
 `14` `            ``{`
 `15` `                ``return` `false``;`
 `16` `            ``}`
 `17` `        ``}`

we can use given codes to learn how to use both function to check hashed function is same or not.

 `01` `static` `void` `Main(``string``[] args)`
 `02` `        ``{`
 `03` `            ``Console.WriteLine(``"Enter Value for Hashed"``);`
 `04` `            ``string` `yourvalue = Console.ReadLine();`
 `05`
 `06` `            ``string` `strhashed = GetMD5Hash(yourvalue);`
 `07` `            ``Console.WriteLine(``"Hashed Value : "` `+ strhashed);`
 `08`
 `09` `            ``Console.WriteLine(``"\nDo you want to verify your hash ? if yes press Y"``);`
 `10` `            ``char` `ch = Convert.ToChar(Console.ReadLine());`
 `11` `            ``if` `(ch == ``'Y'` `|| ch == ``'y'``)`
 `12` `            ``{`
 `13` `                ``Console.WriteLine(``"Enter value again "``);`
 `14` `                ``string` `yourvalue2 = Console.ReadLine();`
 `15`
 `16` `                ``bool` `res = VerifyMD5hash(yourvalue2, strhashed);`
 `17` `                ``Console.WriteLine(``"--------------------"``);`
 `18` `                ``if` `(res)`
 `19` `                ``{`
 `20`
 `21` `                    ``Console.WriteLine(``"Hash is Matched"``);`
 `22`
 `23` `                ``}`
 `24` `                ``else`
 `25` `                ``{`
 `26` `                    ``Console.WriteLine(``"Hash is not Matching "``);`
 `27` `                ``}`
 `28` `                ``Console.WriteLine(``"--------------------"``);`
 `29` `            ``}`
 `30` `            ``else` `{ Environment.Exit(1); }`
 `31` `         ``}`

What output comes

### Coming Next

In the next article, I will hopefully come back with more basic details and implementation of SHA1 and other Hash Algo classes for beginners. Till then Happy CodingÃ¢â‚¬Â¦

Responses

No response found. Be the first to respond this post

Post Comment