Base64 Simplified
Bradly J. Barton
brad@HandAble.com


Base64 encoding contains uppercase, lowercase, numbers, '+', '/' and '='. .

To decode Base64:

Take the encoded stuff in groups of 4 characters and turn each character into a code 0 to 63 thus:

A-Z map to 0 to 25
a-z map to 26 to 51
0-9 map to 52 to 61
+ maps to 62
/ maps to 63

There will be four numbers, all less than 64 which can be represented by a 6 digit binary number (aaaaaa, bbbbbb, cccccc, dddddd respectively). Arrange the 6 digit binary numbers into three bytes as such:

aaaaaabb bbbbcccc ccdddddd

Equals signs (one or two) are used at the end of the encoded block to indicate that the text was not an integer multiple of three bytes long.

Example:

QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Take the first four characters (QWxh) and convert them using the map above:

Q = 16 decimal = binary 010000
W = 22 decimal = binary 010110
x = 49 decimal = binary 110001
h = 33 decimal = binary 100001

Now arrange them:

01000001 01101100 01100001
65 108 97
Ala

Repeat this process for each group of 4, ending with ZQ==

Z = 25 decimal = binary 011001
Q = 16 decimal = binary 010000
skip the equal signs

Arrange them

01100101 00000000 00000000
101 0 0
e (null) (null)

Decoding the entire string will yield: "Aladdin:open sesame"

Updated 9/12/2002: Of course, this same method is extended to deal with binary data as well as text. When this was first put together, it was meant as a primer on how to deal with Basic Authentication (which encodes passwords in Base64 for transmission). Nick Lindridge pointed this out to me and even sent along the changes to the source code to make it work with binary data. Those changes have been made in the source files that can be downloaded below.

Here is a zip file containing this page, source code, and a Win32 executable for translating base 64 encoding strings back and forth.


Back to ...Signifying Nothing