Encryption and Decryption Functions In Vb.net

Updated sandeepparekh9 2 Tallied Votes 10K Views Share

Simple Encryption and Decryption Function using rijndael algorithm.

Imports this:

Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Text

Source : [snipped]

Begginnerdev commented: Good post. +4
Public Function Encrypt(ByVal plainText As String) As String
 
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
 
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
 
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
 
        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
 
 
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
 
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()
 
        symmetricKey.Mode = CipherMode.CBC
 
        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
 
        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
 
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function

Public Function Decrypt(ByVal cipherText As String) As String
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
 
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        ' Convert strings defining encryption key characteristics into byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
 
        ' Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
 
        ' First, we must create a password, from which the key will be 
        ' derived. This password will be generated from the specified 
        ' passphrase and salt value. The password will be created using
        ' the specified hash algorithm. Password creation can be done in
        ' several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
 
        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
 
        ' Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()
 
        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.
        symmetricKey.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 = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
 
        ' Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New MemoryStream(cipherTextBytes)
 
        ' Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
 
        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
 
        ' Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
 
        ' Close both streams.
        memoryStream.Close()
        cryptoStream.Close()
 
        ' Convert decrypted data into a string. 
        ' Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
 
        ' Return decrypted string.   
        Return plainText
    End Function


Example :

Dim strEncryptedText  As String
strEncryptedText  =  Encrypt("yourEncryptionText")
 
Dim strDecrptedText As String
strDecrptedText = Decrypt(strEncryptedText)
NETProgrammer -3 Light Poster

Rijndael algorithm is quite good and has already been shared here. Thanks though.

mitchfizz05 0 Newbie Poster

I have no idea how it works... But cool!
I might use this rather than just saving passwords to a text file.
But would other programs with this code be able to decode the data?
Thanks.

codeorder 197 Nearly a Posting Virtuoso

But would other programs with this code be able to decode the data?

I'm not quite certain since cryptography is a new field for me, though I do believe that this: Dim saltValue As String = "mySaltValue" is what makes your .app unique. Changing the value to anything, should only allow your app to decode it and none other.

prancode 0 Newbie Poster

Hi sandeepparekh9,
I tried your code in my program, but I'm unable to encrypt the password, could you help me out, im new to encryption, it's my first time.

Imports System.Data.SqlClient
Imports System.Data
Imports System.Windows.Forms
Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Text



Public Class LoginForm1

    Dim DT As New DataTable
    Dim QUERYSTRING As String
    Dim I As Integer = 0
    Dim constring As New SqlConnection(My.Settings.PERDBConnectionString)
    Public count As Integer


    Private Sub Login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Login.Click



        Try

            If constring.State = ConnectionState.Open Then
                constring.Close()
            End If
            constring.Open()

            Dim MainMenu As New MDIParent1
            Dim result As String
            Dim CMD As New SqlCommand
            CMD.Connection = constring


            CMD.CommandText = "Exec validatelogin '" & txtuserid.Text & "','" & txtpwd.Text & "'"
            Dim ad As New SqlDataAdapter(CMD)
            Dim dt As New DataTable

            result = CMD.ExecuteScalar
            ad.Fill(dt)
            MsgBox(result, MsgBoxStyle.Exclamation)


            If result = "True" And CheckBox1.CheckState = 0 Then

                MainMenu.Show()
                Me.Dispose(False)

            Else
                MsgBox("Username or Password appears to be wrong")

            End If


            constring.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.ApplicationModal)
        End Try


    End Sub


    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

        Dim result As String
        Dim CMD As New SqlCommand
        CMD.Connection = constring

        Try
            If constring.State = ConnectionState.Open Then
                constring.Close()
            End If
            constring.Open()

            If CheckBox1.CheckState = 1 Then
                CMD.CommandText = "Exec validatelogin '" & txtuserid.Text & "','" & txtpwd.Text & "'"
                Dim ad As New SqlDataAdapter(CMD)
                Dim dt As New DataTable

                result = CMD.ExecuteScalar
                ad.Fill(dt)

                If result = "True" Then
                    Height = 655
                    Width = 466

                Else
                    MsgBox("Username or Password appears to be wrong")
                End If

            ElseIf CheckBox1.CheckState = 0 Then
                Height = 289
                Width = 462

            End If

            constring.Close()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.ApplicationModal)
        End Try


    End Sub


    Private Sub btnSave_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Try

            Dim sqlparameter(2) As Object
            sqlparameter(0) = txtuserid.Text
            sqlparameter(1) = txtoldpwd.Text
            sqlparameter(2) = txtnewpwd.Text


            While CheckBox1.CheckState = 1
                If constring.State = ConnectionState.Open Then
                    constring.Close()
                End If

                constring.Open()
                Dim CMD As New SqlCommand
                CMD.Connection = constring
                Dim commandstring As String = " '"
                Dim msg As String
                Dim ad As New SqlDataAdapter
                Dim dt As New DataTable
                Dim strEncryptedText As String


                    For Each Str As String In sqlparameter
                        commandstring &= Str & "','"
                    Next

                    If String.IsNullOrEmpty(txtuserid.Text) OrElse String.IsNullOrEmpty(txtpwd.Text) OrElse String.IsNullOrEmpty(txtoldpwd.Text) OrElse String.IsNullOrEmpty(txtnewpwd.Text) Then

                        MsgBox("All fields need to be filled")
                        Exit Sub

                End If


                commandstring = Mid(commandstring, 1, (Len(commandstring) - 2))
                CMD.CommandText = "Exec updatelog " & commandstring
                msg = CMD.ExecuteScalar()
                    'ad.Fill(dt)
                strEncryptedText = Encrypt("txtpwd.Text")

                    If txtoldpwd.Text = txtpwd.Text Then
                        MsgBox("password changed")
                        Exit Sub
                    Else
                        MsgBox("password is mismatched")
                        Exit Sub
                    End If
                    constring.Close()

            End While

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.ApplicationModal)


        End Try


    End Sub


    Public Function Encrypt(ByVal plainText As String) As String

        Dim passPhrase As String = "Password"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()
        symmetricKey.Mode = CipherMode.CBC
        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function


    Public Function Decrypt(ByVal cipherText As String) As String

        Dim passPhrase As String = "Password"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()

        symmetricKey.Mode = CipherMode.CBC

        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
        Dim memoryStream As New MemoryStream(cipherTextBytes)
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
        memoryStream.Close()
        cryptoStream.Close()

        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

        Return plainText
    End Function



End Class
bogidewd 0 Newbie Poster

strEncryptedText = Encrypt("txtpwd.Text")

prancode, on line 153 of the above code, I presume you are trying to encrypt the contents of the txtpwd text box. To do so, you need to remove the quotes... it should be like this;

strEncryptedText = Encrypt(txtpwd.Text)

grantpsd 0 Newbie Poster

I had to make a couple of changes, but for the most part entered it as you had it. It seems to encrypt fine but stops at the decryptedByteCount declaration. The error says "Length of the data to decrypt is invalid".

I was just encrypting it to a text box and then trying to decrypt that text box to another.

One change I had to make was that the compiler would not compile "PasswordDeriveBytes" instead it said that it was obsolete and that "Rfc2898DeriveBytes" had replaced it.

The new one only accepts 3 parameters and not the hashAlgorithm.

I would appreciate it if anyone could tell me how to make this work. I am using Visual Studio 2012.

Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Text


Module Encrypt2

    Public passPhrase As String = "yourPassPhrase"
    Public saltValue As String = "mySaltValue"
    Dim hashAlgorithm As String = "SHA1"

    Public Function Encrypt(ByVal plainText As String) As String
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256

        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)

        Dim password As New Rfc2898DeriveBytes(passPhrase, saltValueBytes, passwordIterations)

        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()

        symmetricKey.Mode = CipherMode.CBC

        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

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

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()

        Dim cipherTextBytes() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Clear()

        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)

        Return cipherText

    End Function

    Public Function Decrypt(ByVal cipherText As String) As String

        Dim hashAlgorithm As String = "SHA1"

        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256

        ' Convert strings defining encryption key characteristics into Byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding

        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        ' Convert the Ciphertext into a Byte array
        Dim cipherTextBytes As Byte() = Encoding.UTF8.GetBytes(cipherText)

        ' First we must create a password, from which the key will be 
        ' derived. This password will be generated from the specified
        ' passphrase and salt value. The password will be crated using 
        ' the specified hash algorithm. Password creation can be done in 
        ' several iterations

        Dim password As New Rfc2898DeriveBytes(passPhrase, saltValueBytes, passwordIterations)

        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits)

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

        ' Create uninitialized Rijndael encryption object

        Dim symmetricKey As New RijndaelManaged()

        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.

        symmetricKey.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 = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)

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

        Dim memoryStream As New MemoryStream(cipherTextBytes)

        ' Define cryptographic stream (always user Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)


        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}

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

        ' Close both streams
        memoryStream.Close()
        cryptoStream.Close()

        ' Convert decrypted data into a string
        ' Let us assume that the original plaintext string was UTF8-Encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

        ' Return the decrypted string
        Return plainText


    End Function

End Module

'*******************************************************************

Imports System.Security.Cryptography
Public Class Form1




    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If txt3.TextLength > 0 And txt4.TextLength > 0 Then
            txt1.Text = Decrypt(txt3.Text)
            txt2.Text = Decrypt(txt4.Text)

        End If


    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click



        If txt1.Text.Length > 0 And txt2.Text.Length > 0 Then
            txt3.Text = Encrypt(txt1.Text)
            txt4.Text = Encrypt(txt2.Text)
        End If

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class
grantpsd 0 Newbie Poster

I meant that I am using Visual Studio 2010. And the program is stopping at line 112.

JJ_Code 0 Newbie Poster

Hi sandeepparekh9,
I try to use your Encrypt and Decrypt functions and I found if 2 functions stay on the same application it's work but I want to Encrypt at the one web application and Decrypt at the another one web application it decrypt not like the original word that I encrypt .. below is the source and the word that I want to encrypt is "SV00760" and now the resault after decrypt is "»dǃ:/}/" ..

Garry@TriSys 0 Newbie Poster

Sandeep
Many thanks for taking the time to post this code.
I have tested this on multiple languages and found that it works with all of the supported international languages in Windows 7.
Well done, and keep up the good work.

Kind Regards, Garry@TriSys

rprateek 0 Newbie Poster

I get "invalid length for a base-64 char array" in below line when i try to use it in Asp.net
' Convert the Ciphertext into a Byte array

 Dim cipherTextBytes As Byte() = Encoding.UTF8.GetBytes(cipherText)
Ahmed.C 0 Junior Poster in Training

Hey. This is really cool!!! But there is one thing I need to ask you. How do I decrypt a certain file. e.g. my program creates a file which stores a password. Once the file is saved it will add the encryption. So if the file is opend outside e.g. using notepad wordpad it will show the encryption key rather than the password and if the file is opened from my program it should show the password.

How can this be done. I'd love to use your encryption method in that form.

Thank You!

Reverend Jim 4,968 Hi, I'm Jim, one of DaniWeb's moderators. Moderator Featured Poster

What you do is encrypt the text before you write it to the file. Then after you read it back in you decrypt it

app -> encrypt -> file

file -> decrypt -> app
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.