How to Generate SHA1 Cryptography in C# and VB.Net

Generate SHA1 Cryptography

This part has been copied directly from Wikipedia

SHA-1 is a cryptographic hash function designed by the United States National Security Agency and published by the United States NIST as a U.S. Federal Information Processing Standard. SHA stands for “Secure Hash Algorithm”.

Why you need SHA1?

If you want to make your sensitive information secure, one of the best way, is that make them encrypt. There are different ways which you can use them to make your information encrypt but in most of cases the encrypted information can be decrypted easily , So these methods cannot be good choice for encrypting data same as Base64, But SHA1 is a one way street , it means after encrypt nobody can decrypt it .

If there is no way to decrypt SHA1, how we can use it?

It is common question about SHA1! Somebody still looking for a way to decrypt the SHA1 but I suggest them to stop searching because they cannot find anything.

Now I will explain you how SHA1 can work for you. For example you make a SAH1 from the password that you want to save on the database, when user wants to login to the system you have to make another SHA1 form the string that user has entered, then compare it with SHA1 that you have been saved before on the database if they are same user is eligible to login to the system.

To make a SAH1 you need to pass 3 steps:

Make byte stream from the string that you want to encrypt.
Make SHA1 form the byte.
Make string from the SHA1 that you have produced.
I have mention these three steps in the code below:

[VB.Net]

Private Sub EncryptData()
Dim strToHash As String = "Please Encrypt me !"
Dim Result As String = ""
Dim OSha1 As New _
System.Security.Cryptography.SHA1CryptoServiceProvider

'Step 1
Dim bytesToHash() As Byte _
= System.Text.Encoding.ASCII.GetBytes(strToHash)

'Step 2
bytesToHash = OSha1.ComputeHash(bytesToHash)

'Step 3
For Each item As Byte In bytesToHash
Result += item.ToString("x2")
Next
End Sub

[C#]

private void EncryptData()
{
string strToHash = "Please Encrypt me !";
string Result = "";
System.Security.Cryptography.SHA1CryptoServiceProvider OSha1 = _
new System.Security.Cryptography.SHA1CryptoServiceProvider();

//Step 1
byte[] bytesToHash = _
System.Text.Encoding.ASCII.GetBytes(strToHash);

//Step 2
bytesToHash =_
OSha1.ComputeHash(bytesToHash);

//Step 3
foreach (byte item in bytesToHash) {
Result += item.ToString("x2");
}
}

Discover more from CODE t!ps

Subscribe to get the latest posts sent to your email.

Scroll to Top

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading