Click here to Skip to main content
Click here to Skip to main content

Base64 Decoder and Encoder

, 28 Feb 2010
Rate this:
Please Sign up or sign in to vote.
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:

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)

About the Author

Eugene van der Walt
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

 
QuestionGood but one small mistake Pinmembermaurolo25-Apr-12 22:42 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 28 Feb 2010
Article Copyright 2007 by Eugene van der Walt
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid