-
Feb 6th, 2008, 04:55 PM
#1
[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.
-
Feb 6th, 2008, 05:46 PM
#2
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
-
Feb 6th, 2008, 06:31 PM
#3
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.
-
Apr 7th, 2008, 07:43 AM
#4
Addicted Member
Re: [VB.NET 2005] A Strong Encryption Class for Dummies
Last edited by Lectere; Apr 8th, 2008 at 04:44 PM.
-
Apr 9th, 2008, 12:06 PM
#5
Hyperactive Member
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...
-
May 3rd, 2008, 12:55 AM
#6
Hyperactive Member
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.
-
May 31st, 2008, 04:18 PM
#7
Hyperactive Member
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!
-
May 31st, 2008, 06:15 PM
#8
Hyperactive Member
Re: [VB.NET 2005] A Strong Encryption Class for Dummies
Never mind! Just found it. Easier than expected.
Thanks for the code Jenner!!!!
-
Oct 15th, 2008, 03:57 PM
#9
Lively Member
Re: [VB.NET 2005] A Strong Encryption Class for Dummies
This is very awesome and works great. Thanks Jenner.
-
Feb 14th, 2009, 11:38 AM
#10
Lively Member
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?
-
Feb 16th, 2009, 01:58 PM
#11
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.
-
Feb 16th, 2009, 06:00 PM
#12
Lively Member
Re: [VB.NET 2005] A Strong Encryption Class for Dummies
Thanks. Do you know any good beginners books?
-
Jun 6th, 2009, 11:11 AM
#13
Junior Member
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?
-
Jun 15th, 2009, 08:28 AM
#14
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.
-
Aug 6th, 2009, 11:40 AM
#15
Fanatic Member
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.
-
Aug 7th, 2009, 07:37 AM
#16
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.
-
Aug 7th, 2009, 08:29 AM
#17
Fanatic Member
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.
-
Oct 1st, 2009, 03:21 PM
#18
New Member
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
-
Oct 1st, 2009, 03:44 PM
#19
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.
-
May 28th, 2011, 05:24 AM
#20
New Member
Re: [VB.NET 2005] A Strong Encryption Class for Dummies
Quite a good class. Tried, Tested and it's Working like charm
-
Jul 2nd, 2012, 01:07 PM
#21
New Member
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
-
Jul 2nd, 2012, 01:37 PM
#22
Re: [VB.NET 2005] A Strong Encryption Class for Dummies
No difference. It'll work with 2008 and 2010 just fine.
-
Jul 2nd, 2012, 03:07 PM
#23
New Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|