dcsimg
Results 1 to 23 of 23

Thread: [VB.NET 2005] A Strong Encryption Class for Dummies

  1. #1

    Thread Starter
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    [VB.NET 2005] A Strong Encryption Class for Dummies

    A Strong Encryption Class for Dummies

    Figured I'd post this here. This is a nice little class for making it extremely simple to do complex, strong encryption.

    I typically use this class in programs for encrypting and hashing passwords, so they can be stored safely in a plain text file or database. Encrypting user access permissions, etc.

    The heart of it is four public functions, all of which I found at one time or another online and refined them to true VB.NET code since none of them quite were.

    The first two simply encrypt and decrypt strings. You just provide the "key".
    The third turns a string into a hash. Very useful for passwords.
    The last compares a string against a hash. Perfect for login screens.

    Code is below. Cheers! Rate if you find it useful!
    (Sorry, character limit on posts prevent me from posting it in color.)

    Code:
    Imports System.Security.Cryptography
    Imports System.IO
    Imports System.Text
    
    Public Class clsCrypto
        'Byte vector required for Rijndael.  This is randomly generated and recommended you change it on a per-application basis.
        'It is 16 bytes.
        Private bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62}
    
        'Character to pad keys with to make them at least intMinKeySize.
        Private Const chrKeyFill As Char = "X"c
    
        'String to display on error for functions that return strings. {0} is Exception.Message.
        Private Const strTextErrorString As String = "#ERROR - {0}"
    
        'Min size in bytes of randomly generated salt.
        Private Const intMinSalt As Integer = 4
    
        'Max size in bytes of randomly generated salt.
        Private Const intMaxSalt As Integer = 8
    
        'Size in bytes of Hash result.  MD5 returns a 128 bit hash.
        Private Const intHashSize As Integer = 16
    
        'Size in bytes of the key length.  Rijndael takes either a 128, 192, or 256 bit key.  
        'If it is under this, pad with chrKeyFill. If it is over this, truncate to the length.
        Private Const intKeySize As Integer = 32
    
        'Encrypt a String with Rijndael symmetric encryption.
        Public Function EncryptString128Bit(ByVal strPlainText As String, ByVal strKey As String) As String
            Try
                Dim bytPlainText() As Byte
                Dim bytKey() As Byte
                Dim bytEncoded() As Byte
                Dim objMemoryStream As New MemoryStream
                Dim objRijndaelManaged As New RijndaelManaged
    
                strPlainText = strPlainText.Replace(vbNullChar, String.Empty)
    
                bytPlainText = Encoding.UTF8.GetBytes(strPlainText)
                bytKey = ConvertKeyToBytes(strKey)
    
                Dim objCryptoStream As New CryptoStream(objMemoryStream, _
                    objRijndaelManaged.CreateEncryptor(bytKey, bytIV), _
                    CryptoStreamMode.Write)
    
                objCryptoStream.Write(bytPlainText, 0, bytPlainText.Length)
                objCryptoStream.FlushFinalBlock()
    
                bytEncoded = objMemoryStream.ToArray
                objMemoryStream.Close()
                objCryptoStream.Close()
    
                Return Convert.ToBase64String(bytEncoded)
            Catch ex As Exception
                Return String.Format(strTextErrorString, ex.Message)
            End Try
        End Function
    
        'Decrypt a String with Rijndael symmetric encryption.
        Public Function DecryptString128Bit(ByVal strCryptText As String, ByVal strKey As String) As String
            Try
                Dim bytCryptText() As Byte
                Dim bytKey() As Byte
    
                Dim objRijndaelManaged As New RijndaelManaged
    
                bytCryptText = Convert.FromBase64String(strCryptText)
                bytKey = ConvertKeyToBytes(strKey)
    
                Dim bytTemp(bytCryptText.Length) As Byte
                Dim objMemoryStream As New MemoryStream(bytCryptText)
    
                Dim objCryptoStream As New CryptoStream(objMemoryStream, _
                    objRijndaelManaged.CreateDecryptor(bytKey, bytIV), _
                    CryptoStreamMode.Read)
    
                objCryptoStream.Read(bytTemp, 0, bytTemp.Length)
    
                objMemoryStream.Close()
                objCryptoStream.Close()
    
                Return Encoding.UTF8.GetString(bytTemp).Replace(vbNullChar, String.Empty)
    
            Catch ex As Exception
                Return String.Format(strTextErrorString, ex.Message)
            End Try
    
        End Function
    
        'Compute an MD5 hash code from a string and append any salt-bytes used/generated to the end.
        Public Function ComputeMD5Hash(ByVal strPlainText As String, Optional ByVal bytSalt() As Byte = Nothing) As String
            Try
                Dim bytPlainText As Byte() = Encoding.UTF8.GetBytes(strPlainText)
                Dim hash As HashAlgorithm = New MD5CryptoServiceProvider()
    
                If bytSalt Is Nothing Then
                    Dim rand As New Random
                    Dim intSaltSize As Integer = rand.Next(intMinSalt, intMaxSalt)
    
                    bytSalt = New Byte(intSaltSize - 1) {}
    
                    Dim rng As New RNGCryptoServiceProvider
                    rng.GetNonZeroBytes(bytSalt)
                End If
    
                Dim bytPlainTextWithSalt() As Byte = New Byte(bytPlainText.Length + bytSalt.Length - 1) {}
    
                bytPlainTextWithSalt = ConcatBytes(bytPlainText, bytSalt)
    
                Dim bytHash As Byte() = hash.ComputeHash(bytPlainTextWithSalt)
                Dim bytHashWithSalt() As Byte = New Byte(bytHash.Length + bytSalt.Length - 1) {}
    
                bytHashWithSalt = ConcatBytes(bytHash, bytSalt)
    
                Return Convert.ToBase64String(bytHashWithSalt)
            Catch ex As Exception
                Return String.Format(strTextErrorString, ex.Message)
            End Try
        End Function
    
        'Verify a string against a hash generated with the ComputeMD5Hash function above.
        Public Function VerifyHash(ByVal strPlainText As String, ByVal strHashValue As String) As Boolean
            Try
                Dim bytWithSalt As Byte() = Convert.FromBase64String(strHashValue)
    
                If bytWithSalt.Length < intHashSize Then Return False
    
                Dim bytSalt() As Byte = New Byte(bytWithSalt.Length - intHashSize - 1) {}
    
                Array.Copy(bytWithSalt, intHashSize, bytSalt, 0, bytWithSalt.Length - intHashSize)
    
                Dim strExpectedHashString As String = ComputeMD5Hash(strPlainText, bytSalt)
    
                Return strHashValue.Equals(strExpectedHashString)
            Catch ex As Exception
                Return Nothing
            End Try
        End Function
    
        'Simple function to concatenate two byte arrays. 
        Private Function ConcatBytes(ByVal bytA() As Byte, ByVal bytB() As Byte) As Byte()
            Try
                Dim bytX() As Byte = New Byte(((bytA.Length + bytB.Length)) - 1) {}
    
                Array.Copy(bytA, bytX, bytA.Length)
                Array.Copy(bytB, 0, bytX, bytA.Length, bytB.Length)
    
                Return bytX
            Catch ex As Exception
                Return Nothing
            End Try
    
        End Function
    
        'A function to convert a string into a 32 byte key. 
        Private Function ConvertKeyToBytes(ByVal strKey As String) As Byte()
            Try
                Dim intLength As Integer = strKey.Length
    
                If intLength < intKeySize Then
                    strKey &= Strings.StrDup(intKeySize - intLength, chrKeyFill)
                Else
                    strKey = strKey.Substring(0, intKeySize)
                End If
    
                Return Encoding.UTF8.GetBytes(strKey)
            Catch ex As Exception
                Return Nothing
            End Try
        End Function
    
    End Class
    Last edited by Jenner; Dec 12th, 2008 at 09:47 AM.

  2. #2
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Very useful CodeBank entry as there are not many examples of encryption that are useful.

    Anyway, for secure data storage and usage in a Windows application, I'd take a look at proper usage of the SecureString and the Managed DPAPI.

    Remember, strings in .Net are immutable so each time you call one of your functions, that string is duplicated into memory so this won't protect the data from someone looking at the memory or worse, looking at the paging file if the data touched the disk (then the strings could be there for quite a while). A SecureString, when properly used, can prevent or slow this kind of issue.

    Also, using an MD5 hash of a string isn't a bad idea, but remember a .Net application can easily be decompiled into MSIL or even back into the language it was written in with little to no effort so people will be able to see your salt being added to a hash generating algorithm (I would go with sha over md5 as it's harder to break).

    System.Security.SecureString
    Managed DPAPI Overview Part 1
    Managed DPAPI Overview Part 2
    KrisSiegel.com - My Personal Website with my blog and portfolio
    Don't Forget to Rate Posts!

    Free Icons: FamFamFam, VBCorner, VBAccelerator
    Useful Links: System.Security.SecureString Managed DPAPI Overview Part 1 Managed DPAPI Overview Part 2 MSDN, MSDN2, Comparing the Timer Classes

  3. #3

    Thread Starter
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Good points, I actually do have another batch of code that's a complete login/security system that has a version of this Class that uses SecureStrings and SHA256. It's quite a bit more comprehensive though and I didn't want to post that monstrosity under a "Crypto for Dummies" code example.

  4. #4
    Addicted Member Lectere's Avatar
    Join Date
    Mar 2007
    Location
    The Netherlands
    Posts
    224

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Very nice, thanks!
    Last edited by Lectere; Apr 8th, 2008 at 04:44 PM.

  5. #5
    Hyperactive Member kuldevbhasin's Avatar
    Join Date
    Mar 2008
    Location
    Mumbai, India
    Posts
    473

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    thankx a ton jenner....u r a genius.....u have helped me a lot....
    i have used ur code for the password...and would also be using the code to store the volume serial no. in a file for the security of my project.
    thankx a lot....u r a great help for me...

  6. #6
    Hyperactive Member
    Join Date
    Mar 2007
    Location
    Hong Kong
    Posts
    384

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    That is very useful for every programmer! Can you give me some example using the code?
    I dun know how to de-encrypt the string that I using the encryption method.

  7. #7
    Hyperactive Member
    Join Date
    Aug 2005
    Posts
    261

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Will like to know how can i get the encrypted/decrypted data into a textbox?

    Thanks!

  8. #8
    Hyperactive Member
    Join Date
    Aug 2005
    Posts
    261

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Never mind! Just found it. Easier than expected.

    Thanks for the code Jenner!!!!

  9. #9
    Lively Member
    Join Date
    Aug 2005
    Posts
    82

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    This is very awesome and works great. Thanks Jenner.

  10. #10
    Lively Member
    Join Date
    Jun 2007
    Location
    Canada
    Posts
    86

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Hi, I need help with encryption. I am Making a program to encrypt(using a key) a string(being a textbox) and then put the encryption to textbox2.

    I then want to make a separate program to decrypt it using the same key(symetrical encryption) putthing the encrypted text(cyber text) into textbox1 and then getting the decrypted text in the textbox2

    Im not familiar with the classes i could use in >net. Could you spare some advice? and how would i implement this into buttons?

  11. #11

    Thread Starter
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Just copy/paste this into a new class.

    Then, whenever you want to use it's abilities, instance a new one and call the functions:

    Code:
    Dim crypto As New clsCrypto
    MyCypherText = crypto.EncryptString128Bit(MyPlainText, MyKey)
    If this is looking strange to you, then you really should get a beginner's book to VB.NET programming.
    My CodeBank Submissions: TETRIS using VB.NET2010 and XNA4.0, Strong Encryption Class, Hardware ID Information Class, Generic .NET Data Provider Class, Lambda Function Example, Lat/Long to UTM Conversion Class, Audio Class using BASS.DLL

    Remember to RATE the people who helped you and mark your forum RESOLVED when you're done!

    "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe. "
    - Albert Einstein

  12. #12
    Lively Member
    Join Date
    Jun 2007
    Location
    Canada
    Posts
    86

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Thanks. Do you know any good beginners books?

  13. #13
    Junior Member
    Join Date
    Apr 2009
    Posts
    30

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    I read a lot of thread and they recommended to use the username and password as the salt.
    The module from this thread accepts byte as the argument for salt.
    So my question is how do I convert the string into byte to insert for the salt for the ComputeMD5Hash function?

  14. #14

    Thread Starter
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    The answer is right in the code:

    Encoding.UTF8.GetBytes(strMyString)

    This will convert a string into UTF8 bytes. From there, you can use those bytes however you want, such as in the MD5 routines.
    My CodeBank Submissions: TETRIS using VB.NET2010 and XNA4.0, Strong Encryption Class, Hardware ID Information Class, Generic .NET Data Provider Class, Lambda Function Example, Lat/Long to UTM Conversion Class, Audio Class using BASS.DLL

    Remember to RATE the people who helped you and mark your forum RESOLVED when you're done!

    "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe. "
    - Albert Einstein

  15. #15
    Fanatic Member
    Join Date
    Oct 2008
    Location
    Dominican Republic
    Posts
    733

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    I'm at loss here... I see that you are using 128bit encryption, is there any way to make it 256bit encryption? Or is it 256bit by default? If they key length is 32 bytes then the encryption would be at 256 bits?
    Last edited by tassa; Aug 6th, 2009 at 11:50 AM.
    "In our profession, precision and perfection are not a dispensable luxury, but a simple necessity."
    Niklaus E. Wirth


    Rate any post that helped you, it's a good way of saying thanks
    Please specify your Visual Studio Version!

    Why rating is useful

    My Code Bank Submissions: How to determine Windows Version| Working With Mouse Events | Blocking Input Using API | Get host's IP | Minimize to system tray "animated" | Colored ListBox (custom fonts, colors, highlight) Updated -New Class! | [VS 2008] Strong encryption and hashing class - Updated! 31/August/2009 | Create a shortcut using IWshRuntimeLibrary

  16. #16

    Thread Starter
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Yes, the Rijndael algorithm can take either a 128, 192 or 256 bit key. In this example, I am actually using a 256 bit key. The names of the functions are a bit misleading. I believe when I originally wrote them, the application I was using only used 128 bit keys.
    My CodeBank Submissions: TETRIS using VB.NET2010 and XNA4.0, Strong Encryption Class, Hardware ID Information Class, Generic .NET Data Provider Class, Lambda Function Example, Lat/Long to UTM Conversion Class, Audio Class using BASS.DLL

    Remember to RATE the people who helped you and mark your forum RESOLVED when you're done!

    "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe. "
    - Albert Einstein

  17. #17
    Fanatic Member
    Join Date
    Oct 2008
    Location
    Dominican Republic
    Posts
    733

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    128 bit key would be an array of 8 numbers? Right? I understand that every "spot" in the byte array equals 2 bytes, so 8*2=16 => 128 bit. And so on until 256?

    EDIT:

    Never mind, I got my answer .
    Last edited by tassa; Aug 10th, 2009 at 06:41 PM.
    "In our profession, precision and perfection are not a dispensable luxury, but a simple necessity."
    Niklaus E. Wirth


    Rate any post that helped you, it's a good way of saying thanks
    Please specify your Visual Studio Version!

    Why rating is useful

    My Code Bank Submissions: How to determine Windows Version| Working With Mouse Events | Blocking Input Using API | Get host's IP | Minimize to system tray "animated" | Colored ListBox (custom fonts, colors, highlight) Updated -New Class! | [VS 2008] Strong encryption and hashing class - Updated! 31/August/2009 | Create a shortcut using IWshRuntimeLibrary

  18. #18
    New Member
    Join Date
    Jul 2008
    Posts
    3

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    How do you use the VerifyHash Function?

    I have tried putting it as:

    VerifyHash(PlainTextPass.text,EncryptedSaltedPass) but everytime I try to run it comes as false, I think I am doing it wrong.

    Many thanks for any help.

    Andy

  19. #19

    Thread Starter
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Last I tried it, it worked, but that was a while ago. I'll re-download exactly what I got posted and make sure it works possibly tomorrow.
    My CodeBank Submissions: TETRIS using VB.NET2010 and XNA4.0, Strong Encryption Class, Hardware ID Information Class, Generic .NET Data Provider Class, Lambda Function Example, Lat/Long to UTM Conversion Class, Audio Class using BASS.DLL

    Remember to RATE the people who helped you and mark your forum RESOLVED when you're done!

    "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe. "
    - Albert Einstein

  20. #20
    New Member
    Join Date
    May 2011
    Posts
    1

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    Quite a good class. Tried, Tested and it's Working like charm

  21. #21
    New Member
    Join Date
    Jul 2012
    Posts
    2

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    I know it has been a long time since the post and the OP has posted but can you tell me if there are any differences in VB.NET Express Edition 2008? I'll try the module out later

  22. #22

    Thread Starter
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    No difference. It'll work with 2008 and 2010 just fine.
    My CodeBank Submissions: TETRIS using VB.NET2010 and XNA4.0, Strong Encryption Class, Hardware ID Information Class, Generic .NET Data Provider Class, Lambda Function Example, Lat/Long to UTM Conversion Class, Audio Class using BASS.DLL

    Remember to RATE the people who helped you and mark your forum RESOLVED when you're done!

    "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe. "
    - Albert Einstein

  23. #23
    New Member
    Join Date
    Jul 2012
    Posts
    2

    Re: [VB.NET 2005] A Strong Encryption Class for Dummies

    thanks! I can try it out until I build my new computer, but it'll definitely help with my project! Again, thanks for the awesome post!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width