View Single Post
  #3 (permalink)  
Old 02-08-2008, 04:49 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Post Re: Using the Cryptography APIs in .NET

Using Visual Studio 2005, create a new Console application project using Visual Basic. Import the following namespaces:

Code:
Imports System.Text.Encoding
Imports System.Security.Cryptography
Imports System.IO

Define the following subroutine:

    Private Sub Hashing_SHA1()
        '---ask the user to enter a password---
        Console.Write("Please enter a password: ")
        Dim password As String = Console.ReadLine()

        '---hash the password---
        Dim data() As Byte = ASCII.GetBytes(password)
        Dim passwordHash() As Byte
        Dim sha As New SHA1CryptoServiceProvider()
        passwordHash = sha.ComputeHash(data)

        '---ask the user to enter the same password again---
        Console.Write("Please enter password again: ")
        password = Console.ReadLine()

        '---hash the second password and compare it with the first---
        data = System.Text.Encoding.ASCII.GetBytes(password)

        If ASCII.GetString(passwordHash) = _
           ASCII.GetString(sha.ComputeHash(data)) Then
            Console.WriteLine("Same password")
        Else
            Console.WriteLine("Incorrect password")
        End If
    End Sub
In this subroutine, you first ask the user to enter a password, after which you will hash it using the SHA1 implementation. You then ask the user to enter the same password again. To verify whether the second password matches the first, you hash the second password and then compare the two hash values. Note that for the SHA1 implementation, the hash value generated is 160 bits in length (the byte array passwordHash has 20 members [8 bits x 20 = 160 bits]). In my example, I converted the hash values into strings and performed a comparison. You could also convert them to Base64 encoding and then perform a comparison. Alternatively, you can also compare the two hash values using their byte arrays, comparing byte by byte. As soon as one byte is different, you can conclude that the two hash values are not the same.
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Reply With Quote