none
Validating a password from a VB form

    Question

  •  

    I having problem validating password from a VB.net form and will appreciate all help. I am using a hash and salt password. The sign up information is saving on the table properly. I save the salt on the table as Slt.  When I run the form I get this error message “Slt not declared, it could be inaccessible due to its protection level”

    I  Am pasting the procedure codes thanks for your time

     Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
            Dim plainPassword As String = txtPlainPassword.Text
            Dim hashedpasswrd As String = ""
            Dim Salted As String
            Dim hash As String
            'hashedpasswrd = (Hash512(txtPlainPassword.Text, CreateRandomSalt))
            Dim conn As OleDbConnection
            conn = New OleDbConnection(connString)
            conn.Open()
            Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Users WHERE [UserName] =@UserName AND Slt =@Salt", conn)
            hashedpasswrd = (Hash512(Slt + plainPassword))
            cmd.Parameters.AddWithValue("@UserName", txtUserName.Text)
            cmd.Parameters.AddWithValue("@Pswrd", hashedpasswrd)
            Dim dr As OleDbDataReader = cmd.ExecuteReader
            ' The following variable hold true if user is found atherwise it holds false
            Dim userFound As Boolean = False
            Dim FirstName As String = " "
            Dim LastName As String = " "
            Dim Title As String = " "
            ' If found
            While dr.Read
                userFound = True
                Title = dr("Title").ToString
                FirstName = dr("FirstName").ToString
                LastName = dr("SurName").ToString
    
            End While
    
            'checking the result
    
            If userFound = True Then
                count = 0
                frmMain.Show()
                frmMain.lblWelcome.Text = "Welcome" & " " & Title & " " & FirstName & " " & LastName
                Me.Hide()
            Else
                count += 1
    
                MsgBox("Sorry, username or password not valid", MsgBoxStyle.OkOnly, "Invalid Login")
    
                If count = 3 Then
                    MsgBox("Login failed contact the administrator")
                End If
            End If
            conn.Close()
    
        End Sub
        Private Sub frmLogin_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub


    • Edited by alobi Tuesday, January 2, 2018 8:32 AM
    Tuesday, January 2, 2018 8:30 AM

Answers

  • basically how do I pass the salt value from users table, concatenate it with password entered from txtpassword.txt and hash it? How is my code but I am getting an error message: "Argument is not specified for  parameter salt of Public function Hash512(password as string, salt as string) as string"? thank
    While dr.Read
                userFound = True
                
                salt = dr("Salt").ToString
            End While
            hashedpasswrd = (Hash512(Salted + plainPassword))

    Hi

    Here is some code as a stand alone Project which tries to incorporate your code to create/save/load a local DataBase (actually a Dictionasry here) of Users. It uses your Salt/Hash code and displays Failed or Successful login (from User Name and User Password TextBoxes on the Form.

    This might help you to sort out what I think you are trying to do. If you want, run this as a separate project to try it out.

    There is an initial 'setup' of trial Users (3 of them) which would normally be loaded from the DataBase. In this example, the Save/Load of databaseis commented out. If you want to test those, then uncomment only the SaveDataBase line and run the code once (just to save the set up users. Then comment out the set up users code and uncomment the DataBase.Clear and ReadDataBase lines and rerun.

    ' Form1 with TextBox1, TextBox2,
    ' Label1 and Button1
    Option Strict On
    Option Explicit On
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Security.Cryptography
    Imports System.Text
    Public Class Form1
      Dim DataBase As New Dictionary(Of String, User)
      <Serializable> Class User
    	Property Name As String
    	Property PW As String
    	Property Salt As String
    	Property hash As String
      End Class
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    	' add some random data to database for tests
    	Dim user1, user2, user3 As New User
    	user1.Name = "Les"
    	user1.PW = "freddy"
    	user1.Salt = CreateRandomSalt()
    	user1.hash = Hash512(user1.PW, user1.Salt)
    	DataBase.Add(user1.Name, user1)
    
    	user2.Name = "Mary"
    	user2.PW = "qwerty"
    	user2.Salt = CreateRandomSalt()
    	user2.hash = Hash512(user2.PW, user2.Salt)
    	DataBase.Add(user2.Name, user2)
    
    	user3.Name = "Elizabeth"
    	user3.PW = "123456"
    	user3.Salt = CreateRandomSalt()
    	user3.hash = Hash512(user3.PW, user3.Salt)
    	DataBase.Add(user3.Name, user3)
    
    	' uncomment to save DataBase
    	'	SaveDataBase()
    
    	' un comment to read DataBase
    	'DataBase.Clear()
    	'ReadDataBase()
    
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    	Select Case VerifyUser(TextBox1.Text, TextBox2.Text)
    	  Case True
    		Label1.Text = "Successful login"
    	  Case Else
    		Label1.Text = "Failed login"
    	End Select
      End Sub
      Function VerifyUser(name As String, password As String) As Boolean
    	' uncomment messageboxes to see which failed
    
    	' verify user name
    	If Not DataBase.Keys.Contains(name) Then
    	  '	  MessageBox.Show("User Name not found")
    	  Return False
    	Else
    	  ' verify user hash
    	  If Not Hash512(password, DataBase(name).Salt) = DataBase(name).hash Then
    		'	MessageBox.Show("Password incorrect")
    		Return False
    	  End If
    	End If
    	Return True
      End Function
      Public Function Hash512(password As String, salt As String) As String
    	Dim convertedToBytes As Byte() = Encoding.UTF8.GetBytes(password & salt)
    	Dim hashType As HashAlgorithm = New SHA512Managed()
    	Dim hashBytes As Byte() = hashType.ComputeHash(convertedToBytes)
    	Dim hashedResult As String = Convert.ToBase64String(hashBytes)
    	Return hashedResult
      End Function
      Public Function CreateRandomSalt() As String
    	Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=][}{<>"
    	Dim salt As String = ""
    	Dim rnd As New Random
    	Dim sb As New StringBuilder
    	For i As Integer = 1 To 100
    	  Dim x As Integer = rnd.Next(0, mix.Length)
    	  salt &= (mix.Substring(x, 1))
    	Next
    	Return salt
      End Function
    
      Dim DBpath As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\DB.xml"
      Public Sub SaveDataBase()
    	Dim path As String = DBpath
    	Dim fs As IO.FileStream = New IO.FileStream(DBpath, IO.FileMode.OpenOrCreate)
    	Dim bf As New BinaryFormatter()
    	bf.Serialize(fs, DataBase)
    	fs.Close()
      End Sub
      Public Sub ReadDataBase()
    	Dim path As String = DBpath
    	If FileIO.FileSystem.FileExists(DBpath) Then
    	  Dim fsRead As New IO.FileStream(DBpath, IO.FileMode.Open)
    	  Dim bf As New BinaryFormatter()
    	  DataBase = CType(bf.Deserialize(fsRead), Dictionary(Of String, User))
    	  fsRead.Close()
    	End If
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by alobi Monday, January 8, 2018 8:34 AM
    • Unmarked as answer by alobi Monday, January 8, 2018 9:57 AM
    • Marked as answer by alobi Monday, January 8, 2018 10:24 AM
    Thursday, January 4, 2018 6:17 PM

All replies

  • Hi alobi,

    According to your description, I guess that you store password that was hashed with salt in the Access database, the salt is random or unchanged

     hashedpasswrd = (Hash512(Slt + plainPassword))

    The Hash512 method will hash password, but I don't see Slt's value, and you don't declare it. You said that save the salt on the table as Slt, as far as I'm concerned,  you could need to pass salt(string) and password in Hash512, the Hash512 like this:

    Public Function Hash512(password As String, salt As String) As String
            Dim convertedToBytes As Byte() = Encoding.UTF8.GetBytes(password & salt)
            Dim hashType As HashAlgorithm = New SHA512Managed()
            Dim hashBytes As Byte() = hashType.ComputeHash(convertedToBytes)
            Dim hashedResult As String = Convert.ToBase64String(hashBytes)
            Return hashedResult
        End Function
    
        Public Function CreateRandomSalt() As String
            'the following is the string that will hold the salt charachters
            Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=][}{<>"
            Dim salt As String = ""
            Dim rnd As New Random
            Dim sb As New StringBuilder
            For i As Integer = 1 To 100 'Length of the salt
                Dim x As Integer = rnd.Next(0, mix.Length - 1)
                salt &= (mix.Substring(x, 1))
            Next
            Return salt
        End Function

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, January 3, 2018 6:29 AM
    Moderator
  • My problem is on validating the password, example if MR. Abc whose password has been salted, hashed and saved on a table wants to login.  I know that what I need to do is add the saved salt to the plain password and hash it and then compare it with the hashed password on the table. My problem is that I am not able to put the code together to do that as evidenced in my code above. Thanks for your time. Alex

    
    Wednesday, January 3, 2018 1:33 PM
  • Alobi, 

    I don't know if this is a school assignment. Otherwise you should surely ask yourself if you still want this in 2018. If you have customers they surely don't. There are few persons who don't use a password when they login to Windows anymore. Therefore most programs simply use the "environment.user" for the user and don't bully customers anymore by constantly asking for a password. How would you self do it if programs as Word, VS, ...... are every time asking for a password.


    Success Cor


    Wednesday, January 3, 2018 2:46 PM
  • Hi alobi,

    According to your description, I guess that you store password that was hashed with salt in the Access database, the salt is random or unchanged

     hashedpasswrd = (Hash512(Slt + plainPassword))

    The Hash512 method will hash password, but I don't see Slt's value, and you don't declare it. You said that save the salt on the table as Slt, as far as I'm concerned,  you could need to pass salt(string) and password in Hash512, the Hash512 like this:

    Public Function Hash512(password As String, salt As String) As String
            Dim convertedToBytes As Byte() = Encoding.UTF8.GetBytes(password & salt)
            Dim hashType As HashAlgorithm = New SHA512Managed()
            Dim hashBytes As Byte() = hashType.ComputeHash(convertedToBytes)
            Dim hashedResult As String = Convert.ToBase64String(hashBytes)
            Return hashedResult
        End Function
    
        Public Function CreateRandomSalt() As String
            'the following is the string that will hold the salt charachters
            Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=][}{<>"
            Dim salt As String = ""
            Dim rnd As New Random
            Dim sb As New StringBuilder
            For i As Integer = 1 To 100 'Length of the salt
                Dim x As Integer = rnd.Next(0, mix.Length - 1)
                salt &= (mix.Substring(x, 1))
            Next
            Return salt
        End Function

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Hi Cherry

    Your code, using a collection of random characters from the string 'mix' will never use the last character as your code used 'mix.length-1'. If the last character is needed to be included, consider using 'mix.length' instead.


    Regards Les, Livingston, Scotland

    Wednesday, January 3, 2018 4:39 PM
  • Ok, how does "environment.user" work? I have never used it before and I am open to using it

    alobi


    • Edited by alobi Wednesday, January 3, 2018 5:24 PM
    Wednesday, January 3, 2018 5:22 PM
  • Ok, how does "environment.user" work? I have never used it before and I am open to using it

    alobi


    Is this one person local only then?

    If so, you don't need any database; just encrypt the user name and password (you might use XML with encrypted attributes) and write to the the user's ApplicationData directory.

    I'll set something up for you if you let me know that's what you want to do. With this, hashing is used at all.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Wednesday, January 3, 2018 5:37 PM
  • It is not one person only, should have ability to sign as many people needed up.  Thank

    Wednesday, January 3, 2018 8:31 PM
  • It is not one person only, should have ability to sign as many people needed up.  Thank

    Then everyone would have to have an updated database all at the same time.

    How do you propose to solve that part?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Wednesday, January 3, 2018 8:34 PM
  • The following may be an option. The demo class is for testing, if we change userPassword from MyPassword to anything else then it would return false. And I'm sure there may be better ways to build this but that is all dependent on how you are protecting the system from.

    Imports System.Security.Cryptography
    
    Public Class demo
        Public Sub New()
            Dim p = New Passwording()
            '
            ' User enters this password which gets saved to database
            '
            Dim databasePassword = p.EncryptPassword("MyPassword")
    
            '
            ' User enters this password say into a TextBox
            '
            Dim userPassword = "MyPassword"
    
            '
            ' Determine if the database password matches the entered password
            '
            If p.ValidatePassword(databasePassword, userPassword) Then
                Console.WriteLine("Enter")
            Else
                Console.WriteLine("Exit")
            End If
    
        End Sub
    End Class
    Public Class Passwording
        Public Function EncryptPassword(ByVal pUserPassword As String) As String
            Dim salt(15) As Byte
    
            CType(New RNGCryptoServiceProvider(), RNGCryptoServiceProvider).GetBytes(salt)
    
            Dim pbkdf2 = New Rfc2898DeriveBytes(pUserPassword, salt, 10000)
            Dim hash() As Byte = pbkdf2.GetBytes(20)
    
            Dim hashBytes(35) As Byte
    
            Array.Copy(salt, 0, hashBytes, 0, 16)
            Array.Copy(hash, 0, hashBytes, 16, 20)
    
            Return Convert.ToBase64String(hashBytes)
    
        End Function
        Public Function ValidatePassword(ByVal pFromDatabasePassword As String, ByVal pUserPassword As String) As Boolean
            Dim savedPasswordHash As String = pFromDatabasePassword
            Dim hashBytes() As Byte = Convert.FromBase64String(savedPasswordHash)
            Dim salt(15) As Byte
    
            Array.Copy(hashBytes, 0, salt, 0, 16)
            Dim pbkdf2 = New Rfc2898DeriveBytes(pUserPassword, salt, 10000)
            Dim hash() As Byte = pbkdf2.GetBytes(20)
    
            For i As Integer = 0 To 19
                If hashBytes(i + 16) <> hash(i) Then
                    Return False
                End If
            Next
    
            Return True
    
        End Function
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, January 4, 2018 2:24 AM
    Moderator
  • Actually  the issue centers around this code, let me try and explain my problem better. "slt is a value from a table, (1)how do get the value declared and  incorporate it in code as  shown hashedpasswrd = (Hash512(Salt + plainPassword))  

    (2)The process for validating a  plain password  is to add  salt from the table + plainpassword from the form  and hash it, then compare it with the hashed password on the table.  please let me know if should provide more information, I really do no want get too far way from this to avoid getting more confused. also on the code under that Salt Ia getting hashedpasswrd = (Hash512(Salt + plainPassword)) a wiggly line that saysn "salt is not declared it maybe inaccessible due to its protection" 



    Thursday, January 4, 2018 9:17 AM
  • Actually  the issue centers around this code, let me try and explain my problem better. "slt is a value from a table, (1)how do get the value declared and  incorporate it in code as  shown hashedpasswrd = (Hash512(Salt + plainPassword))  

    (2)The process for validating a  plain password  is to add  salt from the table + plainpassword from the form  and hash it, then compare it with the hashed password on the table.  please let me know if should provide more information, I really do no want get too far way from this to avoid getting more confused. also on the code under that Salt Ia getting hashedpasswrd = (Hash512(Salt + plainPassword)) a wiggly line that saysn "salt is not declared it maybe inaccessible due to its protection" 



    Who are you talking too, it's not clear.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, January 4, 2018 10:18 AM
    Moderator

  • Who are you talking too, it's not clear.


    Karen,

    To whom is in my perception not so important in a forum. But its not clear "about what".


    Success Cor



    Thursday, January 4, 2018 11:51 AM
  • basically how do I pass the salt value from users table, concatenate it with password entered from txtpassword.txt and hash it? How is my code but I am getting an error message: "Argument is not specified for  parameter salt of Public function Hash512(password as string, salt as string) as string"? thank
    While dr.Read
                userFound = True
                
                salt = dr("Salt").ToString
            End While
            hashedpasswrd = (Hash512(Salted + plainPassword))

    Thursday, January 4, 2018 4:05 PM
  • basically how do I pass the salt value from users table, concatenate it with password entered from txtpassword.txt and hash it? How is my code but I am getting an error message: "Argument is not specified for  parameter salt of Public function Hash512(password as string, salt as string) as string"? thank
    While dr.Read
                userFound = True
                
                salt = dr("Salt").ToString
            End While
            hashedpasswrd = (Hash512(Salted + plainPassword))

    Forget all of that for now: As a test, put the password in directly. No encryting or hashing, just put the password in.

    Can you validate it now?

    If you can't then you're looking in the wrong direction; the problem is in how you're storing or how you're reading the data from your source.

    If you can then we can talk about how to proceed but right now, you don't know where the problem is.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, January 4, 2018 4:09 PM
  • basically how do I pass the salt value from users table, concatenate it with password entered from txtpassword.txt and hash it? How is my code but I am getting an error message: "Argument is not specified for  parameter salt of Public function Hash512(password as string, salt as string) as string"? thank
    While dr.Read
                userFound = True
                
                salt = dr("Salt").ToString
            End While
            hashedpasswrd = (Hash512(Salted + plainPassword))

    Hi

    Here is some code as a stand alone Project which tries to incorporate your code to create/save/load a local DataBase (actually a Dictionasry here) of Users. It uses your Salt/Hash code and displays Failed or Successful login (from User Name and User Password TextBoxes on the Form.

    This might help you to sort out what I think you are trying to do. If you want, run this as a separate project to try it out.

    There is an initial 'setup' of trial Users (3 of them) which would normally be loaded from the DataBase. In this example, the Save/Load of databaseis commented out. If you want to test those, then uncomment only the SaveDataBase line and run the code once (just to save the set up users. Then comment out the set up users code and uncomment the DataBase.Clear and ReadDataBase lines and rerun.

    ' Form1 with TextBox1, TextBox2,
    ' Label1 and Button1
    Option Strict On
    Option Explicit On
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Security.Cryptography
    Imports System.Text
    Public Class Form1
      Dim DataBase As New Dictionary(Of String, User)
      <Serializable> Class User
    	Property Name As String
    	Property PW As String
    	Property Salt As String
    	Property hash As String
      End Class
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    	' add some random data to database for tests
    	Dim user1, user2, user3 As New User
    	user1.Name = "Les"
    	user1.PW = "freddy"
    	user1.Salt = CreateRandomSalt()
    	user1.hash = Hash512(user1.PW, user1.Salt)
    	DataBase.Add(user1.Name, user1)
    
    	user2.Name = "Mary"
    	user2.PW = "qwerty"
    	user2.Salt = CreateRandomSalt()
    	user2.hash = Hash512(user2.PW, user2.Salt)
    	DataBase.Add(user2.Name, user2)
    
    	user3.Name = "Elizabeth"
    	user3.PW = "123456"
    	user3.Salt = CreateRandomSalt()
    	user3.hash = Hash512(user3.PW, user3.Salt)
    	DataBase.Add(user3.Name, user3)
    
    	' uncomment to save DataBase
    	'	SaveDataBase()
    
    	' un comment to read DataBase
    	'DataBase.Clear()
    	'ReadDataBase()
    
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    	Select Case VerifyUser(TextBox1.Text, TextBox2.Text)
    	  Case True
    		Label1.Text = "Successful login"
    	  Case Else
    		Label1.Text = "Failed login"
    	End Select
      End Sub
      Function VerifyUser(name As String, password As String) As Boolean
    	' uncomment messageboxes to see which failed
    
    	' verify user name
    	If Not DataBase.Keys.Contains(name) Then
    	  '	  MessageBox.Show("User Name not found")
    	  Return False
    	Else
    	  ' verify user hash
    	  If Not Hash512(password, DataBase(name).Salt) = DataBase(name).hash Then
    		'	MessageBox.Show("Password incorrect")
    		Return False
    	  End If
    	End If
    	Return True
      End Function
      Public Function Hash512(password As String, salt As String) As String
    	Dim convertedToBytes As Byte() = Encoding.UTF8.GetBytes(password & salt)
    	Dim hashType As HashAlgorithm = New SHA512Managed()
    	Dim hashBytes As Byte() = hashType.ComputeHash(convertedToBytes)
    	Dim hashedResult As String = Convert.ToBase64String(hashBytes)
    	Return hashedResult
      End Function
      Public Function CreateRandomSalt() As String
    	Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=][}{<>"
    	Dim salt As String = ""
    	Dim rnd As New Random
    	Dim sb As New StringBuilder
    	For i As Integer = 1 To 100
    	  Dim x As Integer = rnd.Next(0, mix.Length)
    	  salt &= (mix.Substring(x, 1))
    	Next
    	Return salt
      End Function
    
      Dim DBpath As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\DB.xml"
      Public Sub SaveDataBase()
    	Dim path As String = DBpath
    	Dim fs As IO.FileStream = New IO.FileStream(DBpath, IO.FileMode.OpenOrCreate)
    	Dim bf As New BinaryFormatter()
    	bf.Serialize(fs, DataBase)
    	fs.Close()
      End Sub
      Public Sub ReadDataBase()
    	Dim path As String = DBpath
    	If FileIO.FileSystem.FileExists(DBpath) Then
    	  Dim fsRead As New IO.FileStream(DBpath, IO.FileMode.Open)
    	  Dim bf As New BinaryFormatter()
    	  DataBase = CType(bf.Deserialize(fsRead), Dictionary(Of String, User))
    	  fsRead.Close()
    	End If
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by alobi Monday, January 8, 2018 8:34 AM
    • Unmarked as answer by alobi Monday, January 8, 2018 9:57 AM
    • Marked as answer by alobi Monday, January 8, 2018 10:24 AM
    Thursday, January 4, 2018 6:17 PM
  • Hi Les, I like this code and have entered it in a form to test it is. I am showing a couple of error messages which I am not sure how to correct. On Private sub form1 Load on this line "Dim user1, user2, user3 As New User" under the User I get wiggle line the says "type user is not defined" (2) DataBase is not declared it maybe inaccessible due to its protection"
    Saturday, January 6, 2018 2:10 PM
  • Hi

    Hmmmm....

    Can you confirm that these lines are present just above the Form Load event handler.

    Public Class Form1
      Dim DataBase As New Dictionary(Of String, User)
      <Serializable> Class User
    	Property Name As String
    	Property PW As String
    	Property Salt As String
    	Property hash As String
      End Class
      Private Sub Form1_Load(send


    Regards Les, Livingston, Scotland

    • Marked as answer by alobi Monday, January 8, 2018 8:28 AM
    • Unmarked as answer by alobi Monday, January 8, 2018 8:34 AM
    • Marked as answer by alobi Monday, January 8, 2018 9:59 AM
    • Unmarked as answer by alobi Monday, January 8, 2018 10:12 AM
    Saturday, January 6, 2018 2:17 PM
  • The code works fine but how do I incorporate my user table.  If you can take a little to explain that part Access DB, it will be appreciated.
    ' Form1 with TextBox1, TextBox2,
    ' Label1 and Button1
    Option Strict On
    Option Explicit On
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Security.Cryptography
    Imports System.Text
    Public Class Form1
      Dim DataBase As New Dictionary(Of String, User)
      <Serializable> Class User
    	Property Name As String
    	Property PW As String
    	Property Salt As String
    	Property hash As String
      End Class
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    	' add some random data to database for tests
    	Dim user1, user2, user3 As New User
    	user1.Name = "Les"
    	user1.PW = "freddy"
    	user1.Salt = CreateRandomSalt()
    	user1.hash = Hash512(user1.PW, user1.Salt)
    	DataBase.Add(user1.Name, user1)
    
    	user2.Name = "Mary"
    	user2.PW = "qwerty"
    	user2.Salt = CreateRandomSalt()
    	user2.hash = Hash512(user2.PW, user2.Salt)
    	DataBase.Add(user2.Name, user2)
    
    	user3.Name = "Elizabeth"
    	user3.PW = "123456"
    	user3.Salt = CreateRandomSalt()
    	user3.hash = Hash512(user3.PW, user3.Salt)
    	DataBase.Add(user3.Name, user3)
    
    	' uncomment to save DataBase
    	'	SaveDataBase()
    
    	' un comment to read DataBase
    	'DataBase.Clear()
    	'ReadDataBase()
    
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    	Select Case VerifyUser(TextBox1.Text, TextBox2.Text)
    	  Case True
    		Label1.Text = "Successful login"
    	  Case Else
    		Label1.Text = "Failed login"
    	End Select
      End Sub
      Function VerifyUser(name As String, password As String) As Boolean
    	' uncomment messageboxes to see which failed
    
    	' verify user name
    	If Not DataBase.Keys.Contains(name) Then
    	  '	  MessageBox.Show("User Name not found")
    	  Return False
    	Else
    	  ' verify user hash
    	  If Not Hash512(password, DataBase(name).Salt) = DataBase(name).hash Then
    		'	MessageBox.Show("Password incorrect")
    		Return False
    	  End If
    	End If
    	Return True
      End Function
      Public Function Hash512(password As String, salt As String) As String
    	Dim convertedToBytes As Byte() = Encoding.UTF8.GetBytes(password & salt)
    	Dim hashType As HashAlgorithm = New SHA512Managed()
    	Dim hashBytes As Byte() = hashType.ComputeHash(convertedToBytes)
    	Dim hashedResult As String = Convert.ToBase64String(hashBytes)
    	Return hashedResult
      End Function
      Public Function CreateRandomSalt() As String
    	Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=][}{<>"
    	Dim salt As String = ""
    	Dim rnd As New Random
    	Dim sb As New StringBuilder
    	For i As Integer = 1 To 100
    	  Dim x As Integer = rnd.Next(0, mix.Length)
    	  salt &= (mix.Substring(x, 1))
    	Next
    	Return salt
      End Function
    
      Dim DBpath As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\DB.xml"
      Public Sub SaveDataBase()
    	Dim path As String = DBpath
    	Dim fs As IO.FileStream = New IO.FileStream(DBpath, IO.FileMode.OpenOrCreate)
    	Dim bf As New BinaryFormatter()
    	bf.Serialize(fs, DataBase)
    	fs.Close()
      End Sub
      Public Sub ReadDataBase()
    	Dim path As String = DBpath
    	If FileIO.FileSystem.FileExists(DBpath) Then
    	  Dim fsRead As New IO.FileStream(DBpath, IO.FileMode.Open)
    	  Dim bf As New BinaryFormatter()
    	  DataBase = CType(bf.Deserialize(fsRead), Dictionary(Of String, User))
    	  fsRead.Close()
    	End If
      End Sub
    End Class

    How do I incorporate my db table?
    Monday, January 8, 2018 10:12 AM