Page 1 of 1

Encryption How to use MD5 encryption in VB.NET Rate Topic: -----

#1 Bort  Icon User is offline

  • Ill-informed Mongoloid
  • member icon

Reputation: 414
  • View blog
  • Posts: 3,024
  • Joined: 18-September 06

Post icon  Posted 09 October 2008 - 04:19 AM

This tutorial was originally thought up thanks to RodgerB who suggested I added some form of encryption to the code in my 'Trial Period' tutorial here.

I have only looked at encryption for a few days now, but MD5 encryption seems pretty simple, so I decided to put together some notes on it and put it here in case anyone else needed it.

Basically MD5 encryption works one way, so you can encrypt a piece of data, but not decrypt it. Sound kinda pointless? Actually, no, it's quite handy for username/password databases where you will need to save the encrypted data, then check it against what someone has input into, for example, a TextBox. So if you join a website that you need to log into, for example a brilliant programming site called /dream.in.code (visit it here: www.dreamincode.net), you would create your username and password, which is then encrypted and saved in a database. then, when you visit the site, you type in your username/password, these get encrypted, and the encrypted data is checked against the encrypted data saved in the database. If it matches, you are logged in, if it does not, chances are it will complain at you about it.

So how do we go about encrypting information? Well, first of all, you will need to import a few namespaces. Put this code above the Public Class Form1 line.

Imports System.Security.Cryptography
Imports System.Text



System.Security.Cryptography imports all of the information VB need to run the MD5 encryption, and System.Text provides UTF8 support.

Ok, our next step is the declarations. Put this code in the 'Submit' button of your form.

		Dim strText As String = TextBox1.Text
		Dim bytHashedData As Byte()
		Dim encoder As New utf8encoding()
		Dim md5Hasher As New MD5CryptoServiceProvider



These variables are:

strText = The text string you wish to encrypt (eg. password)
bytHashedData = The same text string after encryption. This is no longer in string format, but rather it is a byte array.
encoder = This is a name for the UTF8Encoding method. This is what converts the string into byte format.
md5Hasher = This is the method which actually encrypts the byte array (from encoder) into a different byte array.

This is the line of code you will need to encrypt the information.

		bytHashedData = md5Hasher.ComputeHash(encoder.GetBytes(strText))



The data stored as the variable bytHashedData is what would be saved in the database as your 'password'.

As I mentioned near the beginning, MD5 is one-way encryption, so you cannot decrypt the data once it is converted. This means that if you later go to log into /dic, for example, you would type your password in, and by the time it comes back to your PC to log you in or ask for a correct password, the word you typed into the box has been encrypted itself (using exactly the same code as shown above), then compared to what you saved in the database as your original password. Obviously, if it returns a match, you are logged in, if it does not, you are not logged in.

I do not have code for this bit, but it is exactly like checking a database for any information. The main thing you have to remember when implementing this, is that the data stored in the database is saved in Byte format, not String.

one last thing to mention. MD5 does have one glaring weakness, unless the user goes for obscure passwords. Someone wanting access to your account can use a dictionary search on your username (basically they work their way through a dictionary testing words to see if they can find your password). Not a problem for people with weird passwords, but could cause problems for people with normal words. This is where a little trick called salting comes in. The way salting works is you add some additional information to the password before encrypting it. This could be a user ID, or even the username. Like this:

		bytHashedData = md5Hasher.ComputeHash(encoder.GetBytes(strText & txtUserName.Text))



This is a simple, yet effective way to avoid dictionary attacks

If you have any questions or comments about this tutorial, please post here and I will get back to you with an answer.

Happy coding,
Bort

This post has been edited by Bort: 09 October 2008 - 08:15 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Encryption

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1641
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Posted 09 October 2008 - 07:16 AM

Nice tutorial, you might want to add some information and samples on using RSACryptoServiceProvider as well. It's another form of encryption offered in the .Net Framework.

With this provider you can accomplish things like RSA-SHA1256 Signature verification, like

Public Function VeryfiRASSha256Signature(ByVal dataToSign As Byte()) As Boolean
	Using rsa As New RSACryptoServiceProvider()
		Dim sig As Byte() = rsa.SignData(dataToSign, "SHA256")

		If rsa.VerifyData(dataToSign, "SHA256", sig) Then
			Return True
		Else
			Return False
		End If
	End Using
End Function


Was This Post Helpful? 0
  • +
  • -

#3 Bort  Icon User is offline

  • Ill-informed Mongoloid
  • member icon

Reputation: 414
  • View blog
  • Posts: 3,024
  • Joined: 18-September 06

Posted 09 October 2008 - 08:01 AM

You're probably right PsychoCoder, but I have just figured out MD5 which is a lot simpler. I may well add more information to this tutorial as and when I figure out more encryption methods.

Thanks for the snippet though, it will give me somewhere to start :)

Bort
Was This Post Helpful? 0
  • +
  • -

#4 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1641
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Posted 09 October 2008 - 08:12 AM

No problem kind sir, I just try to help out as much as I can :)
Was This Post Helpful? 0
  • +
  • -

#5 Bort  Icon User is offline

  • Ill-informed Mongoloid
  • member icon

Reputation: 414
  • View blog
  • Posts: 3,024
  • Joined: 18-September 06

Posted 15 October 2008 - 08:15 AM

I spent some time trying to get this to work with my other tutorials (registry changes and trial period), but it didn't work properly. I needed to be able to decrypt the data as well as encrypt it, so I looked into RSA encryption as kind of suggested by PsychoCoder. Once the tutorial for it ispublished, I will link it here.

Bort
Was This Post Helpful? 0
  • +
  • -

#6 Bort  Icon User is offline

  • Ill-informed Mongoloid
  • member icon

Reputation: 414
  • View blog
  • Posts: 3,024
  • Joined: 18-September 06

Posted 30 March 2010 - 02:23 AM

Hmm, can't edit my last post there, so here is the link to the RSA Encryption tutorial :)

Link
Was This Post Helpful? 0
  • +
  • -

#7 cry1978  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 12-January 06

Posted 11 July 2011 - 11:12 PM

I have found a tutorial that does a two way for the md5

encrypt and decrypt it?

Public Class Form1

    ' Brandonio21

    'Postby xolara  Fri Apr 01, 2011 12:19 pm
    'I have posted a code here on bpforums

    'It encrypts the text you input with a password of your choice

    '1 Form
    '2 Textboxes 1 of them is multilined and the other is for password
    '2 buttons Encrypt and Decrypt
    'http://bpforums.info/viewtopic.php?f=9&t=262&sid=8f376c756486c398d6f86342797211a0



    Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
    Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(password.Text))
            DES.Mode = Security.Cryptography.CipherMode.ECB
            Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor
            Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(password.Text)
            password.Text = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch ex As Exception
            MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(password.Text))
            DES.Mode = Security.Cryptography.CipherMode.ECB
            Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateDecryptor
            Dim Buffer As Byte() = Convert.FromBase64String(password.Text)
            password.Text = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch ex As Exception
            MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    
End Class



Was This Post Helpful? 0
  • +
  • -

#8 cry1978  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 12-January 06

Posted 11 July 2011 - 11:29 PM

In the code above I would like to say I have tried to get the multi textbox to decrypt, but it will encrypt it?

so I left that part out that I did for this code to try to make both encrypt.

so I guess this encrypt method is supposed to encrypt input fields, I am new to how to do this, but what if I used this in my visual basic software for my $db_name $username $password
do I keep this encrypted code within my software? and what about the decrypt method do I keep that in there too? lol for it all to work?

or maybe just include the encrypted part, but not the decrypt part, when you need to decrypt it just put back the decrypt part?

how does this work for when a user types in there password online? when a user types in there password how does it encrypt that? looks like there is a command to auto encrypt when a user clicks the submit button?


I'm just trying to understand how this works for websites online, and how it can work for when I want to use this for a software in visual basic 2008
Was This Post Helpful? 0
  • +
  • -

#9 The_Shadow_Coder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 29-June 11

Posted 03 August 2011 - 08:30 PM

ummm i am having problems with the code

its says "Error 1 Value of type '1-dimensional array of Byte' cannot be converted to 'Byte'."

[code]
Imports System.Security.Cryptography
Imports System.Text

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

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strText As String = TextBox1.Text
Dim bytHashedData As Byte
Dim encoder As New UTF8Encoding
Dim md5hasher As New MD5CryptoServiceProvider

bytHashedData = md5hasher.ComputeHash(encoder.GetBytes(strText))
End Sub
End Class
[code]

the error occures at md5hasher.ComputeHash(encoder.GetBytes(strText))
Was This Post Helpful? 0
  • +
  • -

#10 prancode  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-May 12

Posted 14 May 2012 - 10:09 PM

View PostBort, on 09 October 2008 - 04:19 AM, said:

This tutorial was originally thought up thanks to RodgerB who suggested I added some form of encryption to the code in my 'Trial Period' tutorial here.

I have only looked at encryption for a few days now, but MD5 encryption seems pretty simple, so I decided to put together some notes on it and put it here in case anyone else needed it.

Basically MD5 encryption works one way, so you can encrypt a piece of data, but not decrypt it. Sound kinda pointless? Actually, no, it's quite handy for username/password databases where you will need to save the encrypted data, then check it against what someone has input into, for example, a TextBox. So if you join a website that you need to log into, for example a brilliant programming site called /dream.in.code (visit it here: www.dreamincode.net), you would create your username and password, which is then encrypted and saved in a database. then, when you visit the site, you type in your username/password, these get encrypted, and the encrypted data is checked against the encrypted data saved in the database. If it matches, you are logged in, if it does not, chances are it will complain at you about it.

So how do we go about encrypting information? Well, first of all, you will need to import a few namespaces. Put this code above the Public Class Form1 line.

Imports System.Security.Cryptography
Imports System.Text



System.Security.Cryptography imports all of the information VB need to run the MD5 encryption, and System.Text provides UTF8 support.

Ok, our next step is the declarations. Put this code in the 'Submit' button of your form.

		Dim strText As String = TextBox1.Text
		Dim bytHashedData As Byte()
		Dim encoder As New utf8encoding()
		Dim md5Hasher As New MD5CryptoServiceProvider



These variables are:

strText = The text string you wish to encrypt (eg. password)
bytHashedData = The same text string after encryption. This is no longer in string format, but rather it is a byte array.
encoder = This is a name for the UTF8Encoding method. This is what converts the string into byte format.
md5Hasher = This is the method which actually encrypts the byte array (from encoder) into a different byte array.

This is the line of code you will need to encrypt the information.

		bytHashedData = md5Hasher.ComputeHash(encoder.GetBytes(strText))



The data stored as the variable bytHashedData is what would be saved in the database as your 'password'.

As I mentioned near the beginning, MD5 is one-way encryption, so you cannot decrypt the data once it is converted. This means that if you later go to log into /dic, for example, you would type your password in, and by the time it comes back to your PC to log you in or ask for a correct password, the word you typed into the box has been encrypted itself (using exactly the same code as shown above), then compared to what you saved in the database as your original password. Obviously, if it returns a match, you are logged in, if it does not, you are not logged in.

I do not have code for this bit, but it is exactly like checking a database for any information. The main thing you have to remember when implementing this, is that the data stored in the database is saved in Byte format, not String.

one last thing to mention. MD5 does have one glaring weakness, unless the user goes for obscure passwords. Someone wanting access to your account can use a dictionary search on your username (basically they work their way through a dictionary testing words to see if they can find your password). Not a problem for people with weird passwords, but could cause problems for people with normal words. This is where a little trick called salting comes in. The way salting works is you add some additional information to the password before encrypting it. This could be a user ID, or even the username. Like this:

		bytHashedData = md5Hasher.ComputeHash(encoder.GetBytes(strText & txtUserName.Text))



This is a simple, yet effective way to avoid dictionary attacks

If you have any questions or comments about this tutorial, please post here and I will get back to you with an answer.

Happy coding,
Bort


'This is the part of my code where i need to encrypt the data, but then, my passwrd is not getting encrypted,
'could you please help me. I am new to encryption.
'Thanks in advance.


 Dim strText As String = txtpwd.Text
        Dim bytHashedData As Byte()
        Dim encoder As New UTF8Encoding()
        Dim md5Hasher As New MD5CryptoServiceProvider



        Try

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

            If String.IsNullOrEmpty(txtUser_id.Text) OrElse String.IsNullOrEmpty(txtEmp_name.Text) OrElse String.IsNullOrEmpty(txtpwd.Text) OrElse String.IsNullOrEmpty(txtComboBox2.Text) OrElse String.IsNullOrEmpty(txtComboBox3.Text) OrElse String.IsNullOrEmpty(txtDate_created.Text) Then

                MsgBox("All fields need to be filled, enter correct password")
                Exit Sub

            End If
            ' Dim MyText As String
            bytHashedData = md5Hasher.ComputeHash(encoder.GetBytes(strText & txtUser_id.Text))

            commandstring = Mid(commandstring, 1, (Len(commandstring) - 2))
            'MyText = txtpwd.Text
            'MyText = txtpwd.Text
            'MyText = Crypt(MyText)
            'MessageBox.Show(MyText)
           
            bytHashedData = md5Hasher.ComputeHash(encoder.GetBytes(strText))

            CMD.CommandText = "exec sp_faculty_club_Login" & commandstring
            
            msg = CMD.ExecuteScalar()
           
            MsgBox(msg, MsgBoxStyle.Exclamation)

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

    End Sub

This post has been edited by modi123_1: 15 May 2012 - 05:34 AM
Reason for edit:: please use code tags

Was This Post Helpful? 0
  • +
  • -

#11 coder_2010  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 21-August 12

Posted 21 August 2012 - 08:54 AM

Hi, I've just learned a few encryption techniques, even some from this forum! Thanks to all.
I also wanted to add an encryption method you can use for vb.net. It is the AES encryption method:

imports system.security.cryptography
public class AES_Encryptor
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
        Dim AES As New RijndaelManaged
        Dim Hash_AES As New MD5CryptoServiceProvider
        Dim encrypted As String = ""
        Try
            Dim hash(31) As Byte
            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
            Array.Copy(temp, 0, hash, 0, 16)
            Array.Copy(temp, 0, hash, 15, 16)
            AES.Key = hash
            AES.Mode = CipherMode.ECB
            Dim DESEncryptor As ICryptoTransform = AES.CreateEncryptor
            Dim buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(input)
            encrypted = Convert.ToBase64String(DESEncryptor.TransformFinalBlock(buffer, 0, buffer.Length))

        Catch ex As Exception

        End Try
        Return encrypted
    End Function

    Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
        Dim AES As New RijndaelManaged
        Dim Hash_AES As New MD5CryptoServiceProvider
        Dim decrypted As String = ""
        Try
            Dim hash(31) As Byte
            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
            Array.Copy(temp, 0, hash, 0, 16)
            Array.Copy(temp, 0, hash, 15, 16)
            AES.Key = hash
            AES.Mode = CipherMode.ECB
            Dim DESDecryptor As ICryptoTransform = AES.CreateDecryptor
            Dim buffer As Byte() = Convert.FromBase64String(input)
            decrypted = ASCIIEncoding.ASCII.GetString(DESDecryptor.TransformFinalBlock(buffer, 0, buffer.Length))

        Catch ex As Exception

        End Try
        Return decrypted
    End Function
end class


Was This Post Helpful? 0
  • +
  • -

#12 coder_2010  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 21-August 12

Posted 21 August 2012 - 09:03 AM

BTW, with the AES encryption, you do not need to store the password! If you can remember the password, just bring up an inputbox or something to type the password and use that password like:

Also, in the code section for the AES, change public class to Module and end class to end module.
You won't have to raise the object: IE no "AES_Encryptor. ..." just "AES_Encrypt".

public class form1
    public sub Button1_Click(byval sender as object, byval e as system.eventargs) handles Button1.Click
   dim passwd as string = inputbox("Please enter your password: ")
   dim etext as string = AES_Encrypt(your string here, passwd)
end class



And do the same for the decryption!
Was This Post Helpful? 0
  • +
  • -

#13 MarkM90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-December 12

Posted 19 December 2012 - 10:16 AM

Hi,

I am new to the world of visual basic and found this thread very helpful, I can now successfully save encrypted passwords to the database! However I'm having a little trouble trying to compare the password entered when the user logs into the system. The database field I am trying to compare it to is a varbinary field. I have tried using the following but I'm not sure how to call the byte variable in my select statement:

CommandText = "SELECT * FROM [table] WHERE field1 = '" & TextBox.Text & "' AND field2='"& bytHashedData &"';"

Am I on the right lines? I don't really know the correct syntax, but trying "'& bytHashedData &'" I get an '& operator not defined for type '1-dimensional array of byte". I have also tried @bytHashedData with no luck.

Thanks in advance.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1