Click here to Skip to main content
15,881,204 members
Articles / Programming Languages / Visual Basic

Base64 Decoder and Encoder

Rate me:
Please Sign up or sign in to vote.
3.03/5 (18 votes)
28 Feb 2010CPOL2 min read 193.9K   6.1K   47   12
Sample code for encoding and decoding Base64 data
Screenshot - screenshot.gif

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:

VB.NET
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:

  1. Copy the encrypted string to a text file and save
  2. Run the application and select the file in the "encoded" file location text box
  3. 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
South Africa South Africa
Born. School. 2 Law degrees and i dumped them for a job as a develper because technology is my passion.

Comments and Discussions

 
QuestionOther Example for testing Pin
Member 108718544-Feb-17 3:01
Member 108718544-Feb-17 3:01 
GeneralMy vote of 4 Pin
Tanmoy_Mazumder11-Mar-13 0:49
Tanmoy_Mazumder11-Mar-13 0:49 
QuestionGood but one small mistake Pin
maurolo25-Apr-12 22:42
maurolo25-Apr-12 22:42 
GeneralMy vote of 5 Pin
bebopperz17-Feb-11 12:21
bebopperz17-Feb-11 12:21 
Questionthanks and need more help Pin
skyfriendly3-Aug-10 2:33
skyfriendly3-Aug-10 2:33 
GeneralMy vote of 1 Pin
GurliGebis28-Feb-10 2:38
GurliGebis28-Feb-10 2:38 
GeneralRe: My vote of 1 Pin
bebopperz17-Feb-11 12:20
bebopperz17-Feb-11 12:20 
GeneralThank you ! Pin
quake33325-Feb-10 2:18
quake33325-Feb-10 2:18 
Questionso much extra code for nothing? Pin
ii_noname_ii10-Feb-09 1:39
ii_noname_ii10-Feb-09 1:39 
AnswerRe: so much extra code for nothing? Pin
ii_noname_ii10-Feb-09 1:52
ii_noname_ii10-Feb-09 1:52 
QuestionAny size limit for the file needed to be encoded? Pin
platelet15-Jan-09 10:13
platelet15-Jan-09 10:13 
GeneralI will tell you why the framework to not have your function... Pin
Jcmorin20-Apr-07 5:49
Jcmorin20-Apr-07 5:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.