Decoding reverses the encoding process: it reads Base64 characters in groups of 4, maps each character back to its 6-bit numeric value (0–63), packs them into a 24-bit integer, and extracts the original 8-bit bytes.
Step-by-Step Decoding Process
- Sanitize Input: Strip whitespace, newlines (
\r\n), and optional data URI prefixes likedata:*/*;base64,. - Validate Character Set: Verify that every character belongs to the Base64 alphabet (A–Z, a–z, 0–9,
+,/, or URL-safe equivalents-,_). Reject or flag unexpected characters. - Process in 4-Character Blocks:
- Convert character 1 → 6 bits
- Convert character 2 → 6 bits
- Convert character 3 → 6 bits (or detect
=padding) - Convert character 4 → 6 bits (or detect
=padding)
- Extract Bytes:
triple = (val1 << 18) | (val2 << 12) | (val3 << 6) | val4 byte1 = (triple >> 16) & 0xFF byte2 = (triple >> 8) & 0xFF byte3 = triple & 0xFF - Handle Trailing Padding:
- If the block ends with
==, output onlybyte1. - If the block ends with
=, outputbyte1andbyte2. - If unpadded, output all 3 bytes.
- If the block ends with
Error Handling in Modern Decoders
Robust decoders must handle edge cases gracefully:
- Mismatched Padding: Some systems omit trailing
=padding (e.g. JWTs). Standard-compliant decoders can infer the missing padding fromlength % 4. - Non-zero Padding Bits: If the unused bits in the final byte are not zero, RFC 4648 specifies that strict decoders should report a validation warning or error to prevent data smuggling.