Recipe 16.5. Handling Passwords Securely


Problem

You want to test an entered password against a value stored somewhere, but you don't want anyone to be able to look through the system or through your program to discover what that password is.

Solution

Sample code folder: Chapter 16\SecurePassword

Store the hash of the password in the system registry, and test any user-entered password by comparing its hash against the registry entry.

Discussion

The following demonstration code includes a method that lets you record a username and password (hashed) in the system registry, and another method that compares a newly entered username and password with the previously stored value. This code requires the GetHash() function defined in Recipe 16.1:

 Public Sub StoreUserAndPassword(ByVal userName As String, _       ByVal passwordText As String)    ' ----- Save the encrypted password in the registry.    Dim hashPassword As String = GetHash(passwordText)    My.Computer.Registry.SetValue _       ("HKEY_CURRENT_USER\Software\  PasswordsTest", _       userName, hashPassword) End Sub Public Function CheckPassword(ByVal userName As String, _       ByVal passwordText As String) As Boolean    ' ----- See if the username and password passed to    '       this function match entries in the registry.    Dim hashPassword As String = GetHash(passwordText)    ' ----- Retrieve any stored value.    Dim hashPassRead As String = _       Convert.ToString(My.Computer.Registry.GetValue( _         "HKEY_CURRENT_USER\Software\PasswordsTest", _       userName, Nothing))    ' ----- Compare the passwords.    If (hashPassRead = Nothing) Then       ' ----- Invalid username.       Return False    ElseIf (hashPassRead = hashPassword) Then       ' ----- Good username and password.       Return True    Else       ' ----- Good username, bad password.       Return False    End If End Function 




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net