Base64 Encode and Decode

Base64 Encode and Decode Online

Before understanding base64 encode and decode, we need to know about Base64. It is a binary-to-text encoding scheme that represents binary data (a sequence of 8-bit bytes) in an American Standard Code for Information Interchange (ASCII) string format.

Use of Encoding / Decoding

Base64 is used for sending email attachments, it is required because SMTP - in its original form - was designed to transport 7-bit ASCII characters only. It is useful for embedding the image files into the web (HTML) pages.
Example:
  • Simple String: Hi, I'm Amit from f1mate.com
  • Encoded String: SGksIEknbSBBbWl0IGZyb20gZjFtYXRlLmNvbQ==

Structure of Base64

The particular set of 64 characters chosen to represent the 64-digit values for the base varies between implementations. The general strategy is to choose 64 characters that are common to most encodings and that are also printable. This combination leaves the data unlikely to be modified in transit through information systems, such as email, that were traditionally not 8-bit clean. For example, MIME's Base64 implementation uses A–Z, a–z, and 0–9 for the first 62 values. Other variations share this property but differ in the symbols chosen for the last two values; an example is UTF-7.

The earliest instances of this type of encoding were created for dial-up communication between systems running the same OS, for example, uuencode for UNIX and BinHex for the TRS-80 (later adapted for the Macintosh), and could therefore make more assumptions about what characters were safe to use. For instance, uuencode uses uppercase letters, digits, and many punctuation characters, but no lowercase.
Source: https://en.wikipedia.org/wiki/Base64

Base64 algorithm:

  • Count the number of characters in a string.
  • If it's not a multiple of three, pad with a special character, i.e., "=" to make it a multiple of three.
  • Encode the string in ASCII format.
  • Now, it will convert the ASCII to binary format, 8 bits each.
  • After converting to binary format, it will divide binary data into chunks of 6 bits each.
  • The chunks of 6-bit binary data will now be converted to decimal number format.
  • Using the base64 index table, the decimals will be again converted to a string according to the table format.
  • Finally, we will get the encoded version of our input string.