Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series Module 3 - Modern Symmetric Cryptography

Java Program for Base64 Encoding and Decoding Explained

Reviewed & accurate
AI Summary

Introduction

Base64 is the workhorse of binary-safe text transport. It lets you take any sequence of bytes and represent it using only 64 printable ASCII characters: A through Z, a through z, 0 through 9, plus, and slash, with the equals sign as padding. The format was first specified for PEM (Privacy-Enhanced Mail) in RFC 1421 in 1993 and refined in RFC 2045 for MIME in 1996. In this base64 encoding java tutorial we will use java.util.Base64, the standard Java class that has been part of the JDK since Java 8.

Base64 is not encryption. It provides confidentiality against nobody; an attacker can decode base64 as easily as you can. But Base64 is essential plumbing for cryptography because almost every cryptographic output, whether a ciphertext, a hash, a key, or a signature, is a sequence of binary bytes that must travel through text-only channels such as JSON, XML, HTTP headers, or email. Without a base64 layer, modern cryptography could not be transported.

What is Base64?

Base64 is a binary-to-text encoding. It takes groups of three bytes (24 bits) and re-chunks them into four groups of six bits. Each six-bit value indexes into a 64-character alphabet to produce one printable character. Thus three input bytes become four output bytes, an expansion of exactly one third.

When the input length is not a multiple of three, padding is needed. The encoder pads the final three-byte group with zero bits and adds one or two equals signs at the end so the decoder knows how many real bytes were in the last group. For example, the two-byte input "Hi" becomes the four-character output "SGk=".

Java's java.util.Base64 class exposes three encoders. The basic encoder uses the standard alphabet and adds line breaks every 76 characters (RFC 2045). The URL-safe encoder replaces plus with minus and slash with underscore, because plus and slash have special meaning in URLs and could break query strings. The MIME encoder follows the MIME format with newlines and is suitable for email headers.

How Base64 Works Step by Step

Let us encode the 3-byte string "Man" step by step to see exactly how the algorithm works.

Step 1: Take the ASCII bytes of "Man": M is 77, a is 97, n is 110. In binary, that is 01001101 01100001 01101110.

Step 2: Concatenate the 24 bits into one stream: 010011010110000101101110.

Step 3: Split into four 6-bit groups: 010011 010110 000101 101110. In decimal these are 19, 22, 5, 46.

Step 4: Index into the Base64 alphabet: position 19 is T, position 22 is W, position 5 is F, position 46 is u. So "Man" encodes as "TWFu".

Step 5: For inputs that are not a multiple of 3 bytes, pad. For example, "Ma" (two bytes) becomes "TWE=", and "M" (one byte) becomes "TQ==".

Java Program for Base64 Encoding and Decoding Explained

import java.util.Base64;

public class Base64Demo {
    public static void main(String[] args) {
        String original = "Cryptography tutorial from imcseian";

        // 1. Basic Base64 encoder/decoder
        String basicEncoded = Base64.getEncoder().encodeToString(original.getBytes());
        System.out.println("Basic encoded  : " + basicEncoded);
        String basicDecoded = new String(Base64.getDecoder().decode(basicEncoded));
        System.out.println("Basic decoded  : " + basicDecoded);

        // 2. URL-safe encoder (uses - and _ instead of + and /)
        String urlEncoded = Base64.getUrlEncoder().encodeToString(original.getBytes());
        System.out.println("URL encoded    : " + urlEncoded);

        // 3. MIME encoder (line breaks every 76 chars, suitable for email)
        String mimeEncoded = Base64.getMimeEncoder().encodeToString(original.getBytes());
        System.out.println("MIME encoded   : " + mimeEncoded);

        // 4. Common crypto use-case: encode raw bytes for safe transport
        byte[] rawBytes = new byte[]{(byte)0x9F, (byte)0xAB, 0x12, 0x55, (byte)0xE4};
        String safeForJson = Base64.getEncoder().encodeToString(rawBytes);
        System.out.println("Raw hex bytes  : 9F AB 12 55 E4");
        System.out.println("As base64      : " + safeForJson);

        // 5. Decode a known base64 string back to bytes
        String sample = "SGVsbG8sIFdvcmxkIQ==";
        byte[] decoded = Base64.getDecoder().decode(sample);
        System.out.println("Decoded sample  : " + new String(decoded));
    }
}

Code Explanation Line by Line

Base64.getEncoder() returns a singleton Encoder instance that uses the standard RFC 4648 alphabet. The method encodeToString is a convenience that wraps the byte array conversion and string construction in one call. The matching Base64.getDecoder() returns a Decoder that accepts either padded or unpadded input, although the basic decoder requires correct padding for unambiguous decoding.

Base64.getUrlEncoder() returns an encoder that uses the URL-safe alphabet. Plus signs in URLs encode as spaces, and slashes delimit path segments, so substituting them with minus and underscore makes the encoded string safe to embed in a URL query parameter without further encoding. URL-safe encoders omit the line breaks that the MIME encoder adds.

Base64.getMimeEncoder() returns an encoder that adds CRLF line breaks every 76 characters of output, as required by RFC 2045. This is what email systems expect for binary attachments. If you paste a MIME-encoded blob into a raw HTTP header without the line breaks, some servers will reject it.

The fourth block in main demonstrates the most common cryptography use case: turning raw binary bytes into a string that can safely travel through JSON or XML. Raw byte values like 0x9F are not printable, so if you tried to put them into a JSON string you would get either a parse error or a corrupted transport. Base64 fixes this by guaranteeing every output byte is a printable ASCII character.

The fifth block decodes a known base64 string. The string "SGVsbG8sIFdvcmxkIQ==" decodes to the bytes of "Hello, World!" which proves that the algorithm works in both directions.

Sample Input and Output

Basic encoded  : Q3J5cHRvZ3JhcGh5IHR1dG9yaWFsIGZyb20gaW1jc2VpYW4=
Basic decoded  : Cryptography tutorial from imcseian
URL encoded    : Q3J5cHRvZ3JhcGh5IHR1dG9yaWFsIGZyb20gaW1jc2VpYW4=
MIME encoded   : Q3J5cHRvZ3JhcGh5IHR1dG9yaWFsIGZyb20gaW1jc2VpYW4=
Raw hex bytes  : 9F AB 12 55 E4
As base64      : n6sSVeQ=
Decoded sample  : Hello, World!

The exact output may vary slightly because the MIME encoder sometimes breaks lines depending on length. The crucial observation is that all three encoders produce strings that decode back to the same original bytes.

Common Mistakes to Avoid

First, never use Base64 as a form of encryption. Base64 is encoding, not encryption. Anyone can decode it. If you need confidentiality, run the data through AES-GCM first and then base64-encode the ciphertext for transport.

Second, never mix URL-safe and standard alphabets. If you encode with getUrlEncoder() but try to decode with the standard getDecoder(), the minus and underscore characters will cause IllegalArgumentException. Use the matching getUrlDecoder() for URL-safe output.

Third, never assume Base64 output is a fixed length. The output length is ceil(inputLength / 3) * 4. If your code reads a fixed-size buffer, allocate for the rounded-up length plus padding.

Fourth, never paste base64 into HTML without escaping. Base64 strings can contain equals signs, plus signs, and slashes, all of which have special meaning in HTML attributes or URLs. Use the URL-safe encoder or URL-encode the result.

Real-World Applications

Base64 is everywhere. JSON Web Tokens (JWTs) base64-encode the header, payload, and signature sections. SAML assertions are base64-encoded XML. PEM-formatted certificates and private keys are base64-encoded DER with a header and footer. Data URLs embed images as base64 directly in HTML img tags. The HTTP Basic Authentication header is the base64 encoding of "username:password".

In cryptography specifically, base64 is the standard format for transferring symmetric keys, ciphertexts, hashes, HMACs, and signatures between systems that expect text. Almost every REST API that signs requests (such as AWS Signature Version 4) uses base64 at some point in its signing pipeline.

Conclusion

Base64 is also widely used in cryptographic challenge-response protocols. The HTTP Basic Authentication header is simply the base64 encoding of "username:password". The OAuth 1.0 signature mechanism base64-encodes the HMAC output. The HTTP/2 binary framing layer occasionally uses base64 to surface internal state for debugging. AWS Signature Version 4 signs canonical requests whose HMAC-SHA-256 output is base64-encoded and then concatenated into an Authorization header. Without base64, the binary output of HMAC-SHA-256 would not be transportable in HTTP headers, which restrict themselves to printable ASCII.

Another related encoding is base32, which uses a 32-character alphabet (A through Z plus 2 through 7) and is useful when case sensitivity is a problem (for example, when users must type a code from a printed QR code or read it over the phone). Base32 produces output roughly 60 percent larger than the input, versus base64's 33 percent, so it is rarely the right choice unless human transcription is involved. Java does not have a built-in base32 encoder, but Bouncy Castle and Apache Commons Codec both provide one.

A third variant, base16 (also known as hexadecimal), uses only 16 characters (0 through 9 and A through F) and doubles the input size. Hex is useful when the output must be precisely aligned with byte boundaries, which makes it easier to read in debugging tools. The Java standard library added HexFormat in Java 17 to provide hex encoding and decoding without third-party dependencies. Hex is also case-insensitive on decode, which makes it forgiving of human input.

One subtle pitfall: base64-encoded strings can contain the equals sign as padding. When you put a base64 string into a URL, the equals sign can be interpreted as a key-value separator by some URL parsers. The URL-safe base64 variant replaces plus and slash with minus and underscore, but the equals sign remains. For URL parameters that may be re-encoded by intermediate proxies, strip the trailing equals signs before transmitting and re-add them on the receiver before decoding.

In this base64 encoding java tutorial we walked through the Base64 algorithm, its three Java encoder variants (basic, URL-safe, MIME), and a complete program that round-trips text and raw bytes. Base64 is not encryption, but it is essential plumbing for every cryptographic system that has to move binary data through text channels. Mastering it now will save you hours of debugging later when you start signing API requests.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments