Introduction
I got interested in decoding from base64 due to an e-mail that I received that had gotten reformatted and the attached images were only visible as base64 strings.
Being an exceptionally inquisitive person, I wanted to know what the file attachments contained. I am by no means an expert programmer, but I thought it would be an adventure to try and convert the data. I found (on this very site) sample code (in C#) for converting strings to and from base64. Because the image's base64 string was too long, I adapted the code to read the string from a file and write the converted string to a file. This didn't seem to work at all as some of the characters weren't converted correctly. It converted simple strings, but nothing too advanced.
I had a further look on the net and there are many products out there that will do all this for you - but at a price. I realized that I would probably have to do this by myself. I had a quick look under the hood of Framework 2.0 and, to my pleasant surprise, the good folks at Microsoft had done all the hard work for me. All I had to do was slap some lines of code down and it worked like a dream. This is nothing fancy, but it does what it is supposed to do: encode to and decode from Base64.
Using the Code
The basic methods used in this code are System.Convert.ToBase64String
(encoding) and System.Convert.FromBase64String
(decoding).
We start off with an image which has been Base64 encoded - probably by someone out to ruin your day. I have encoded, for your pleasure, a simple image file (this file is also available in the source code and it is titled -aptly - encoded.txt).
R0lGODlhkAGQAYAAAAAAAP///yH5BAAAAAAALAAAAACQAZABAAL/
jI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is
1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8PGCg4SFhoeIiYqLjI2Oj4CBkpOUlZaXmJmam5ydnp+
QkaKjpKWmp6ipqqusra6voKGys7S1tre4ubq7vL2+v7CxwsPExcbHyMnKy8zNzs/AwdLT1NXW19jZ2tvc3d7f0NHi4+
Tl5ufo6err7O3u7+Dh8vP09fb3+Pn6+/z9/v/w8woMCBBAsaPIgwocKFDBs6fAgxosSJFCtavIgxo8aN/
xw7evwIMqTIkSRLmjyJMqXKlSxbunwJM6bMmTRr2ryJM6fOnTx7+vwJNKjQoUSLGj2KNKnSpXMAOH0KNarUqVSrWr2
KNavWrVMrcv0KNqzYsVy9kj2LNq1aqWbXun0L92rbuHTrup1rN69esHj3+v1LtS/gwYAFEz6c1zDixXAVM36c1jHky
WIlU7681TLmzVY1c/4c1TPo0aJHfy5tejPq1JdXs57s+vXj2LIX0659+Dbuwbp3/+3tey/w4IkpEk89/Djd5MobG29
++jl01dKnt65uHTb27LO3c7ft/Xvu8OJ5ky//+zx64erXF5/oHjz8+OPn0zdv/376/PrZ8//v/55EAO4n4ID+FWhgg
BElqBdzDHbV3oNkOSghVBRW6NSFGGpYIYcSevggiAyKmCCJBpo4IIoAqtgfi/q5eB+M9MkYH43u2bgejujpWB6P4vn
4HZDcCZkdkdYZOR2S0CnZHJPKOXkclMRJGRyVvlm5G5a4aVkbl7J5+RqYrImJXIQY8mXmmWWlqaZWZJr2JmlstolVn
KDZGd1/dI6FJ2d9UqfnnmH9iRmh1wUq6FeGUraodogmmtmckLIl6aQWVmpphphm2ihknXb3aKadbWrpp4yZKh+Coq4
Z6qoQtupqaKROiipitdbHVK667sprr77+Cmywwg5LbLHGHotsssqaLstss84+C2200k5LbbXWXottttpuy2233n4Lb
rjijktuueaei2666q7LbrvuvgtvvPLOS2+99t6Lb7767stvv/7+C3DAAg9McMEGH4xwwgovzHDDDj8MccQST0xxxRZ
fjHHGGm/McccefwxyyCKPTHLJJp+Mcsoqr8xyyy6/DHPMMs9Mc80234xzzjrvzHPPPv8MdNBCD11FAQA7AAAAAA==
Your inquisitive nature now wants to know what the picture contains. To do this, you use this simple code:
Public Class Form1
Sub DecodeFile(ByVal srcFile As String, ByVal destFile As String)
Dim src As String
Dim sr As New IO.StreamReader(srcFile)
src = sr.ReadToEnd
sr.Close()
Dim bt64 As Byte() = System.Convert.FromBase64String(src)
If IO.File.Exists(destFile) Then
IO.File.Delete(destFile)
End If
Dim sw As New IO.FileStream(destFile, IO.FileMode.Create)
sw.Write(bt64, 0, bt64.Length)
sw.Close()
End Sub
Sub EncodeFile(ByVal srcFile As String, ByVal destfile As String)
Dim srcBT As Byte()
Dim dest As String
Dim sr As New IO.FileStream(srcFile, IO.FileMode.Open)
ReDim srcBT(sr.Length)
sr.Read(srcBT, 0, sr.Length)
sr.Close()
dest = System.Convert.ToBase64String(srcBT)
Dim sw As New IO.StreamWriter(destfile, False)
sw.Write(dest)
sw.Close()
End Sub
Private Sub butBrowseDec_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butBrowseDec.Click
Me.SaveFileDialog1.ShowDialog()
Me.txtDecoded.Text = Me.SaveFileDialog1.FileName
End Sub
Private Sub butBrowse_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butBrowse.Click
Me.SaveFileDialog1.ShowDialog()
Me.txtEncoded.Text = Me.SaveFileDialog1.FileName
End Sub
Private Sub butEndcode_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butEndcode.Click
Try
If Me.txtDecoded.Text = Nothing Or Me.txtEncoded.Text = Nothing Then
MsgBox("Please select source and destination files!")
Exit Sub
End If
Me.EncodeFile(Me.txtDecoded.Text, Me.txtEncoded.Text)
MsgBox("Conversion complete!")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub butDecode_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butDecode.Click
Try
If Me.txtDecoded.Text = Nothing Or Me.txtEncoded.Text = Nothing Then
MsgBox("Please select source and destination files!")
Exit Sub
End If
Me.DecodeFile(Me.txtEncoded.Text, Me.txtDecoded.Text)
MsgBox("Conversion complete!")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
As you will see above, I didn't need to write anything fancy - the Framework has all the clever stuff already included. All you need to do is lay it out right. Using the code provided, you can easily encode and decode simple strings using the provided textboxes, but when it comes to files - even the encoded string I included - it simply doesn't display the result in the decoded box. So I needed to include file handling capabilities.
To make sure that your application works:
- Copy the encrypted string to a text file and save
- Run the application and select the file in the "encoded" file location text box
- Enter a filename into the "decoded" file location box and give it a ".gif" extension
Click on the decode button between the file location textboxes. If you can open the image file, you have succeeded in converting a Base64 string into an Image file.