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.
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.
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