Base64 Encode / Decode

What is Base64

Base64 is a generic term for a number of similar encoding schemes that encode binary data by treating it numerically and translating it into a base 64 representation. The Base64 term originates from a specific MIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML.

Base64 encoding is a technique used for converting binary data into blocks of printable ASCII characters. The Base64 encoding algorithm uses a special conversion table to assign one of the 64 ASCII characters to every 6 bits of the bytestream. That is to say, a binary stream is divided into blocks of six bits and each block is mapped to an ASCII character. The ASCII character with the value of 64 (character =) is used to signify the end of the binary stream.

When and why would you use Base64 encoding?

  • 7 Bit ASCII characters are safe for transmission over the network and between different systems
  • SMPT protocol for emails supports only 7 Bit ASCII Characters. Base64 is the commonly used technique to send binary files as attachments in emails.
  • Base64 encode saves around 33% of space more than regular strings

Code Examples

Perlencode_base64($string);decode_base64($string);Requires use MIME::Base64;
JavaBase64.encodeBase64(string);Base64.decodeBase64(string);Requires import org.apache.commons.codec.binary.Base64;
JavaScriptbtoa(string);atob(string);<= IE9 is unsupported
RubyBase64.encode64('string')Base64.decode64(enc)Requires require "base64"

External Links

More information about Base64 (Wikipedia)