I want to encrypt and decrypt the password and username of my login table
I already populate my login table with 5 rows

Can anyone suggest some Encryption and decryption algorithms for Password protection?
here is my current code

Option Strict On
Imports System.Data.SqlClient

Public Class Frmlogin

Private strCon As String = "Data Source=OCHO_CINCO;Initial Catalog=CGHMS;Integrated Security=True"
Dim dept_id As String

Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles BtnLogin.Click
    Dim cmd As New SqlCommand()
    Using con As New SqlConnection(strCon)
        con.Open()
        cmd.Connection = con
        cmd.CommandText = "select log_username, log_password, dept_id from login where log_username =  @username And " + "log_password = @password"
        cmd.Parameters.AddWithValue("@username", TxtUsername.Text)
        cmd.Parameters.AddWithValue("@password", Txtpassword.Text)
        Using dr As SqlDataReader = cmd.ExecuteReader()
            Dim indicator As Boolean = False
            While dr.Read()
                Dim mydept As String = dr("dept_id").ToString()

                If dr.HasRows AndAlso mydept = "1" Then
                    MessageBox.Show("Ekurhuleni")
                    FrmDashBoardMenuDept1.Show()
                    Me.Hide()
                    indicator = True
                ElseIf dr.HasRows AndAlso mydept = "2" Then
                    MessageBox.Show("WestRand")
                    FrmDashBoardMenuDept2.Show()
                    Me.Hide()
                    indicator = True
                ElseIf dr.HasRows AndAlso mydept = "3" Then
                    MessageBox.Show("Johannesburg - Head Office")
                    FrmDashBoardMenuDept3.Show()
                    Me.Hide()
                    indicator = True
                ElseIf dr.HasRows AndAlso mydept = "4" Then
                    MessageBox.Show("Gordonia Services")
                    FrmdashBoardMenuDept4.Show()
                    Me.Hide()
                    indicator = True
                ElseIf dr.HasRows AndAlso mydept = "5" Then
                    MessageBox.Show("Tshepong Stimulation Centre")
                    FrmDashBoardMenuDept5.Show()
                    Me.Hide()
                    indicator = True
                End If
            End While
            If Not indicator Then
                MessageBox.Show("Invalid User name and password")
            End If
        End Using
    End Using
End Sub

Recommended Answers

All 8 Replies

@Christopher_12 : What do you mean with Encrytion / Decryption of your password. You already entered 5 uid and pwd manually.

You can encrypt / decrypt programmatically at the time of save and retrieve pwd from database.

Secondly clear your logic about dr.HasRow(). Are you sure uid and pwd distinct for each respective dept.? As per your codes if any two or three or all dept have same uid and pwd it can open all two or three or all dept window.
If you want to open a single dept window this is not proper use of **HasRow and Read ** method of data-reader.
I just trying to modify your cades

Private strCon As String = "Data Source=OCHO_CINCO;Initial Catalog=CGHMS;Integrated Security=True"

Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles BtnLogin.Click
    Dim cmd As New SqlCommand()
    Using con As New SqlConnection(strCon)
        con.Open()
        cmd.Connection = con
        cmd.CommandText = "select log_username, log_password, dept_id from login where log_username =  @username And log_password = @password"
        cmd.Parameters.AddWithValue("@username", TxtUsername.Text)
        cmd.Parameters.AddWithValue("@password", Txtpassword.Text)
        Using dr As SqlDataReader = cmd.ExecuteReader()

            If dr.HasRows() Then

                dr.Read()
                Select Case dr("dept_id").ToString()
                    Case "1"
                        MessageBox.Show("Ekurhuleni")
                        FrmDashBoardMenuDept1.Show()
                    Case "2"
                        MessageBox.Show("WestRand")
                        FrmDashBoardMenuDept2.Show()
                    Case "3"
                        MessageBox.Show("Johannesburg - Head Office")
                        FrmDashBoardMenuDept3.Show()
                    Case "4"
                        MessageBox.Show("Gordonia Services")
                        FrmdashBoardMenuDept4.Show()
                    Case "5"
                        MessageBox.Show("Tshepong Stimulation Centre")
                        FrmDashBoardMenuDept5.Show()
                End Select

                Me.Hide()

            Else
                MessageBox.Show("Invalid User name and password")
            End If

            dr.Close()

        End Using

        cmd.Dispose()
        Con.Close()
    End Using
End Sub

Hope it can help you.

yea thank you
i'm sure about the code because it is directing me into the chosen department
but what i want is some help about how to encrypt the password in VB to database
i dont know if u understand what im trying to say
password encryption

The following uses a form with one button, and two multi-line textboxes. To test, paste some code into txtClear then click the button to encrypt. Click again to decrypt. I'm not clear on some of the details but it does work. If you google "vb.net cryptography" you can get more information. Unfortunately, most of the examples online give about the same level of detail as I give here.

Imports System.Security.Cryptography    'for encryption/decryption
Imports System.IO                       'for memory streams
Imports System.Text                     'for UTF8 support

Public Class Form1

    Private cryp As New Crypto

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        btnExecute.Text = "Encrypt"
    End Sub

    Private Sub btnExecute_Click(sender As System.Object, e As System.EventArgs) Handles btnExecute.Click

        Select Case btnExecute.Text
            Case "Encrypt"
                txtEncrypted.Text = cryp.Encrypt(txtClear.Text, "my passwword")
                txtClear.Clear()
                btnExecute.Text = "Decrypt"
            Case "Decrypt"
                txtClear.Text = cryp.Decrypt(txtEncrypted.Text, "my passwword")
                txtEncrypted.Clear()
                btnExecute.Text = "Encrypt"
        End Select

    End Sub

End Class

Public Class Crypto

    Private salt As String = "mySaltString"
    Private hash As String = "SHA1"
    Private ivec As String = "@1B2c3D4e5F6g7H8"

    Private keysize As Integer = 256
    Private numiter As Integer = 2

    Private saltBytes() As Byte = Encoding.UTF8.GetBytes(salt)
    Private ivecBytes() As Byte = Encoding.UTF8.GetBytes(ivec)

    Public Function Encrypt(ByVal clearText As String, passPhrase As String) As String

        Dim textBytes() As Byte = Encoding.UTF8.GetBytes(clearText)
        Dim password As New PasswordDeriveBytes(passPhrase, saltBytes, hash, numiter)
        Dim keyBytes() As Byte = password.GetBytes(keysize \ 8)
        Dim symmKey As New RijndaelManaged()

        symmKey.Mode = CipherMode.CBC

        Dim encryptor As ICryptoTransform = symmKey.CreateEncryptor(keyBytes, ivecBytes)

        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)

        cryptoStream.Write(textBytes, 0, textBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()

        memoryStream.Close()
        cryptoStream.Close()

        Return Convert.ToBase64String(cipherTextBytes)

    End Function

    Public Function Decrypt(ByVal cipherText As String, passPhrase As String) As String

        Dim textBytes As Byte() = Convert.FromBase64String(cipherText)

        'Create a password from the user supplied passPhrase and the salt value

        Dim password As New PasswordDeriveBytes(passPhrase, saltBytes, hash, numiter)

        'Use the password to generate pseudo-random bytes for the encryption key.
        'Note that keysize is specified in bits but must be passed as # of bytes.

        Dim keyBytes As Byte() = password.GetBytes(keysize \ 8)

        'Create Rijndael encryption object.

        Dim symmKey As New RijndaelManaged()
        symmKey.Mode = CipherMode.CBC

        'Generate decryptor from the existing key bytes and initialization vector. 
        'Key size will be defined based on the number of the key bytes.

        Dim decryptor As ICryptoTransform = symmKey.CreateDecryptor(keyBytes, ivecBytes)

        'Define memory stream which will be used to hold encrypted data.

        Dim memoryStream As New MemoryStream(textBytes)

        'Define cryptographic stream (always use Read mode for encryption).

        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)

        'At this point we don't know what the size of decrypted data although we are
        'guaranteed that the plain text will never be longer than the cypher text.

        Dim plainTextBytes As Byte() = New Byte(textBytes.Length - 1) {}

        'Decrypt, then close the streams.

        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)

        memoryStream.Close()
        cryptoStream.Close()

        'Convert decrypted data into a string and return it

        Return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

    End Function

End Class

you do NOT want to do this.
NEVER store passwords in a way that can be decrypted, it's a massive security risk.
Rather store a salted, hashed, password, and compare the password the user enters on logging in with that after salting and hashing it using the same machanism.
That way nobody, especially not an intruder, will ever be able to retrieve your passwords.
And no, don't store password hints. If someone forgets their password they're either out of luck or (more userfriendly) you will need a multi stage system for password resets.
So not sending them a new password, or even sending them a password reset link.
Require them to submit several ways to contact them, then send a link to a password regeneration page on one of those channels, and a time limited (to say an hour) password for that place on another, maybe a username to use to access that place on a third.
And only send those in case neither of the contact addresses has been changed recently (say within the last month).

Sounds like overkill? It isn't. It's not fully secure but the most secure you can get without requiring the user to create a new account when they forget their password.
And it's still only as secure as the strength of your salting and hashing mechanisms (hint, don't use MD5 or something like that for the hashing), and of course the security of your database (if someone can get in and change things they can still hijack accounts).

Good point about the password. Of course you don't want to hard code it. I just did that for the example. I should have coded the password as a user entry textbox or InputBox to make that clear.

ok i see what u trying to explain but i'm new in VB.net and i dont know how i will do that can u help me based to my code above please

I don't see the problem. Include the Crypto class (and the required Imports) then use the Encrypt/Decrypt methods to do what you want.

cpswd = crypt.Encrypt(pswd, passPhrase)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.