Base64 encoding


Series Overview

This article is part of the series. Below are links to all posts in the series:
  1. Byte Variables & Byte Arrays
  2. Byte Representations
  3. Base64 Encoding
  4. Byte Range Splitting

What's inside this article ⌄
  • Base64 encoding algorithm explained
  • Base64 conversion python java
  • Base64 padding rules
  • Base64 vs hex encoding
  • Base64 Java encrypt
  • Base64 Python encrypt

Base64 is a great thing that helps you represent your bytes as text.

Each of the six bits of your data is being represented as a character in Base64. The mapping table is named the Base64 alphabet. You can find one here or here.

Guess how many symbols are in Base64’s alphabet? You’re right, there are 64 of them!


Manual step-by-step algorithm

Let’s practice and understand a bit of a conversion by encoding a 0x7F byte to Base64 manually.

Step 1. Convert to binary (left padding to one byte):

7F (hex) = 127 (decimal) = 01111111 (binary)

Step 2. Divide 01111111 by 2 groups of 6 bits each from left to right with right padding:

011111 110000

Step 3. Convert each group to a corresponding symbol from the Base64 alphabet (using a table from the links above):

011111 = f (base64)
110000 = w (base64)

Step 4. The minimum number of symbols in a Base64 word is 4. We should use the = symbol for padding. Therefore:

0x7F (hex) = fw== (base64)

Base64 in Python & Java

This is how you can convert bytes to Base64 in Python:

byte_value = bytes([127])
base64_encoded = base64.b64encode(byte_value).decode()
print(base64_encoded) # output: fw==

And decode the Base64 string back to bytes:

base64_encoded = "fw=="
decoded_bytes = base64.b64decode(base64_encoded)
print(decoded_bytes[0]) # output: 127

Encode bytes to Base64 in Java:

String base64Encoded = Base64.getEncoder().encodeToString(new byte[]{127});
System.out.println(base64Encoded);

And decode the Base64 string back to bytes in Java:

String base64Encoded = "fw==";
byte[] decodedBytes = Base64.getDecoder().decode(base64Encoded);
System.out.println(decodedBytes[0]);

Note that there are also Base16 and Base32 encodings in place. However, there is no difference between Base16 and hexadecimal representation.

Now it’s time to roll up your sleeves and put those newfound skills to the test!

Experiment, play around, and see things working.