Welcome to AddressOf.com Sign in | Join | Help

Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

A friend of mine needed a way to store some values in a configuration file that is somewhat sensitive (coming from a web service using WSE2 with encryption).  I thought about using DP-API, however, he needed the ability to use the same config file for all users.  The first thing that came to mind was to use TripleDES in a similar manner as when I worked on RadioShack e-Commerce site.  Basically, I used a third party component that would encrypt and decrypt the strings (password, credit card, etc.) and then use a crude homemade Base64 type function to convert the string so that special characters (specifically, the ASCII 0 - NULL) wouldn't interfere with the OLEDB functions.

I knew that the encryption/decryption and Base64 functionality is part of the BCL... so I did some googling for a sample.  I came across a pretty simple example that was written in C#.  Alas, my friend needed the code in VB.NET (well, of course he did ;-) ).  Here is an even more simplified version of the code I found.

Private Function TripleDESEncode(ByVal value As String, ByVal key As String) As String

  Dim des As New Security.Cryptography.TripleDESCryptoServiceProvider

  des.IV = New Byte(7) {}

  Dim pdb As New Security.Cryptography.PasswordDeriveBytes(key, New Byte(-1) {})

  des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, New Byte(7) {})

  Dim ms As New IO.MemoryStream((value.Length * 2) - 1)

  Dim encStream As New Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), Security.Cryptography.CryptoStreamMode.Write)

  Dim plainBytes As Byte() = Text.Encoding.UTF8.GetBytes(value)

  encStream.Write(plainBytes, 0, plainBytes.Length)

  encStream.FlushFinalBlock()

  Dim encryptedBytes(CInt(ms.Length - 1)) As Byte

  ms.Position = 0

  ms.Read(encryptedBytes, 0, CInt(ms.Length))

  encStream.Close()

  Return Convert.ToBase64String(encryptedBytes)

End Function

 

Public Function TripleDESDecode(ByVal value As String, ByVal key As String) As String

  Dim des As New Security.Cryptography.TripleDESCryptoServiceProvider

  des.IV = New Byte(7) {}

  Dim pdb As New Security.Cryptography.PasswordDeriveBytes(key, New Byte(-1) {})

  des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, New Byte(7) {})

  Dim encryptedBytes As Byte() = Convert.FromBase64String(value)

  Dim ms As New IO.MemoryStream(value.Length)

  Dim decStream As New Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), Security.Cryptography.CryptoStreamMode.Write)

  decStream.Write(encryptedBytes, 0, encryptedBytes.Length)

  decStream.FlushFinalBlock()

  Dim plainBytes(CInt(ms.Length - 1)) As Byte

  ms.Position = 0

  ms.Read(plainBytes, 0, CInt(ms.Length))

  decStream.Close()

  Return Text.Encoding.UTF8.GetString(plainBytes)

End Function

Basically, I just wanted two simple functions that would take a string and a private key value and encrypt it using TripleDES and Base64 Encode it.  When I wanted to decode the value, just pass it to another function that would reverse the process using the same private key.  This code is completely self-contained, just drop into a existing form, class or module and use.  Here's an example of the functions being used from a console application:

<STAThread()> _

Sub Main()

 

  Dim key As String = "a1B@c3D$"

 

  Dim original As String = "This is a test, blah, blah, blah."

  Console.WriteLine("Original" & vbCrLf & "-----------------")

  Console.WriteLine(original & vbCrLf)

  Dim encrypted As String = TripleDESEncode(original, key)

  Console.WriteLine("Encrypted" & vbCrLf & "-----------------")

  Console.WriteLine(encrypted & vbCrLf)

  Dim decrypted As String = TripleDESDecode(encrypted, key)

  Console.WriteLine("Decrypted" & vbCrLf & "-----------------")

  Console.WriteLine(decrypted & vbCrLf)

 

  Console.ReadLine()

 

End Sub

When using this, be sure to use a key that conforms to same sort of rules you would want for passwords.  Also, if you intend to use this sort of functionality within your code, where the key is stored within the project, but sure to use one of the many obfuscaters that are available that can encrypt the strings within the executable.  If you use an obfuscater that does not have that functionality, then use some other mechanism to obfuscate this key value.

Published Tuesday, October 19, 2004 6:57 PM by CorySmith
Filed under:

Comments

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Friday, November 5, 2004 7:11 AM by Leejay
Hi there impressive code, however I am having an issue. I am passing a encoded string to a page and attempting to decode it.
This is how I am fetching the string : Request.QueryString("string")

I am getting this error "Invalid length for a Base-64 char array." when I try decode the string?

Please could you offer some advice on how to go about this?

It works when I use say a text box for the value but doesnt when I use the Request.QueryString("string")

So I assume that it has something to do with the string and the Request object?

Thank you in advance for any help you can offer

# Cifrado y Descifrado de Texto con .NET

Thursday, November 25, 2004 8:29 PM by Nazul's Weblog

# Cifrado y Descifrado de Texto con .NET

Thursday, November 25, 2004 8:31 PM by Nazul's Weblog
M

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Friday, December 3, 2004 6:38 AM by srinath

hi

just change ie reverse the parameter passage and try.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Friday, December 3, 2004 6:38 AM by srinath

hi

just change ie reverse the parameter passage and try. password and then username

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, December 30, 2004 3:37 PM by sunilta
I've run into the same problem, "Invalid length for a Base-64 char array." when I try decode the string. I'm not sure what you mean by reversing the parameter passage...password then username?

Thanks so much

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Wednesday, January 5, 2005 4:30 AM by peer
Hi, have had the same problem with Request.QueryString("string"); and then trying to base64 decode it. The Request.QueryString object decodes '+' sings as ' '. See http://tiberi.us/view_article.aspx?article_id=20 for more info

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, January 6, 2005 6:14 AM by vijay
its really fentastic method to encrypt and decrypt...
thank a lot
regards,
Vijay

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Wednesday, January 12, 2005 12:25 AM by simonw
All those people having problems with Base64 encoding - it's because you're probably using the string in a URL. URLs get URLEncoded and as a result some the characters in your hashes are going to be substituted. For some reason URL decoding also breaks the process (the plus sign seems to be at fault).

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Tuesday, February 1, 2005 6:20 PM by Cc
Hi I am new to all of the security field. I just want to understand the concept that you presented to here.

you are doing encode ->encrypt -> ----->decrypt ->decoding? right?

the encrypt/decrypt and encode/decode are separate library to use?

Thanks a lot.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Wednesday, April 6, 2005 10:17 PM by phillipl
Now I don't have to include all this interop dlls etc etc to just encrypt a string....This is awesome and easy.. Thanks!

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Tuesday, May 10, 2005 8:13 AM by Maxee
I don't know if my answer will help anyone or not since the question has been asked bout half year ago...

As i know the function FromBase64String only accept 32 bytes or 4 alphanumeric string, cannot be more or less

Dim encryptedBytes As Byte() = Convert.FromBase64String(value)

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Wednesday, May 25, 2005 10:15 AM by TheAdvisor
Before u send the encrypted string(cipher) as a QueryString u must use the Server.UrlEncode("cipher") function, otherwise the values wont be preserved when u request the QueryString.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Friday, July 15, 2005 1:52 PM by Adriano
I am having the a similar problem as above.
I can encrypt a string and decrypt it using the code above. but when it comes to query strings I can encrypt it but when I decrypt, I don't get the same value back.
I try to use the Server.UrlEncode to encode the query string before I send it but the result still the same.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Wednesday, July 20, 2005 4:27 PM by Venkat
Thanks for posting the code, it was very useful

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, July 28, 2005 2:22 PM by Bob
This is great - saved me several hours of research!

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, July 28, 2005 9:09 PM by robert
anyone know of encrypting so you end up with ascii values and the same length string?

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Monday, October 10, 2005 8:41 AM by AL
EXCELLENT

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, November 3, 2005 12:52 AM by Dane
I'm getting a "Length of the data to decrypt is invalid." error. I'm not using a query string or anything like that. I'm just using simple text... I've tried several different examples and keep getting the same error! Any suggestions?

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, November 3, 2005 12:56 AM by Dane
Quick update... it seems that if I change the length of the key or text to encrypt/decrypt I get a different error. "Invalid length for a Base-64 char array." I could really use some help. Thanks everyone!

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Friday, November 4, 2005 12:17 PM by Dane
For those of you having problems with the DES ecryption, you might want to try using the RC2CryptoServiceProvider. It worked perfectly the first time for me.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Monday, December 19, 2005 4:17 PM by Ron
I would really like to use this code but am geting the Length of the data to decrypt is invalid error. I am using a very simple key "yoyo" just for testing and the password is a 4 character password. Can anyone help me on this? Thanks

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Tuesday, April 4, 2006 7:56 AM by Brij
Server.URLEncode, just worked fine at once,

Thanx a lot

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Tuesday, September 19, 2006 2:15 PM by chri
Very nice piece of code. I tried a lot and came to almost the same solution, except that decryption did not work. For some reason, after cryptoStream.write(myMemoryStream,...), the memoryStream seemed to be empty. I also tried memoryStream.close() and memoryStream.getBuffer(), but that did not work, either. Also, I used DESCryptoServiceProvider instead. BTW, I also encountered the "Length of the data to decrypt is invalid." error whick I solved by padding the data to a multiply of the key length. Though, your solution seems to work without padding, too. Thanx a lot.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, November 30, 2006 8:03 AM by needJavahelp

I need this extremely simply code in Java. And I don't know the first thing about Java. Does anyone have a Java class for this, or know of an easy way to convert this VB.net code to Java?

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Wednesday, August 29, 2007 1:57 AM by AndersR
First off you derive bytes from key not value (aka password). Secondly you should remember to salt password using RNGCryptoServiceProvider when creating PasswordDeriveBytes: PasswordDeriveBytes pdb = new PasswordDeriveBytes( value, new RNGCryptoServiceProvider().GetBytes(new byte[7])); Also you should clear the byte arrays and cryptoserviceprovider to avoid leaving any trace in memory: try { // your code } finally { ClearBytes(plainBytes); // method that iterates byte array and set values to 0 des.Clear(); }

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Thursday, October 11, 2007 3:15 AM by Abhiram
This Code is Workning fine for a small piece of text and failing for even a little bit lengthy text

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Wednesday, October 31, 2007 7:06 AM by Randall Moore
To fix the problem in passing an encrypted value in the querystring just replace any space with a + after you retrieve the querysting. Myvar=Request.Querysting("x") Myvar = Myvar.Replace(" ", "+") Then decrypt Myvar.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Tuesday, November 20, 2007 8:01 AM by Mike Z
I beleive the problems with decoding using base64 is that a DESede string may contain character codes not supported by Base64 encoding.

# re: Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

Tuesday, December 11, 2007 5:02 AM by Widmeyer Lisboa
Apparently, the Request.QueryString object interprets the '+' sign as a space! So, with a quick Replace function we resolve this problem.
Anonymous comments are disabled