import java.util.Base64;
import java.nio.charset.StandardCharsets; public class DecodeCredential { public static void main(String[] args) { // Kubernetes secret value, Base64-encoded String encoded = "ZGItcHJvZC51cy1lYXN0LTEuYW1hem9uYXdzLmNvbTo1NDMy"; byte[] decodedBytes = Base64.getDecoder().decode(encoded); String connectionString = new String(decodedBytes, StandardCharsets.UTF_8); System.out.println(connectionString); // db-prod.us-east-1.amazonaws.com:5432 }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class DecodeCredential { public static void main(String[] args) { // Kubernetes secret value, Base64-encoded String encoded = "ZGItcHJvZC51cy1lYXN0LTEuYW1hem9uYXdzLmNvbTo1NDMy"; byte[] decodedBytes = Base64.getDecoder().decode(encoded); String connectionString = new String(decodedBytes, StandardCharsets.UTF_8); System.out.println(connectionString); // db-prod.us-east-1.amazonaws.com:5432 }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class DecodeCredential { public static void main(String[] args) { // Kubernetes secret value, Base64-encoded String encoded = "ZGItcHJvZC51cy1lYXN0LTEuYW1hem9uYXdzLmNvbTo1NDMy"; byte[] decodedBytes = Base64.getDecoder().decode(encoded); String connectionString = new String(decodedBytes, StandardCharsets.UTF_8); System.out.println(connectionString); // db-prod.us-east-1.amazonaws.com:5432 }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class RoundTrip { public static void main(String[] args) { String original = "redis://cache-prod.internal:6379/session-store"; String encoded = Base64.getEncoder().encodeToString( original.getBytes(StandardCharsets.UTF_8) ); System.out.println(encoded); // cmVkaXM6Ly9jYWNoZS1wcm9kLmludGVybmFsOjYzNzkvc2Vzc2lvbi1zdG9yZQ== byte[] decoded = Base64.getDecoder().decode(encoded); String recovered = new String(decoded, StandardCharsets.UTF_8); System.out.println(recovered.equals(original)); // true }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class RoundTrip { public static void main(String[] args) { String original = "redis://cache-prod.internal:6379/session-store"; String encoded = Base64.getEncoder().encodeToString( original.getBytes(StandardCharsets.UTF_8) ); System.out.println(encoded); // cmVkaXM6Ly9jYWNoZS1wcm9kLmludGVybmFsOjYzNzkvc2Vzc2lvbi1zdG9yZQ== byte[] decoded = Base64.getDecoder().decode(encoded); String recovered = new String(decoded, StandardCharsets.UTF_8); System.out.println(recovered.equals(original)); // true }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class RoundTrip { public static void main(String[] args) { String original = "redis://cache-prod.internal:6379/session-store"; String encoded = Base64.getEncoder().encodeToString( original.getBytes(StandardCharsets.UTF_8) ); System.out.println(encoded); // cmVkaXM6Ly9jYWNoZS1wcm9kLmludGVybmFsOjYzNzkvc2Vzc2lvbi1zdG9yZQ== byte[] decoded = Base64.getDecoder().decode(encoded); String recovered = new String(decoded, StandardCharsets.UTF_8); System.out.println(recovered.equals(original)); // true }
}
import java.util.Base64; public class DecodeToBuffer { public static void main(String[] args) { byte[] src = "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=".getBytes(); byte[] dst = new byte[1024]; // pre-allocated int len = Base64.getDecoder().decode(src, dst); String result = new String(dst, 0, len); System.out.println(result); // {"host":"10.0.1.50","port":8443} }
}
import java.util.Base64; public class DecodeToBuffer { public static void main(String[] args) { byte[] src = "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=".getBytes(); byte[] dst = new byte[1024]; // pre-allocated int len = Base64.getDecoder().decode(src, dst); String result = new String(dst, 0, len); System.out.println(result); // {"host":"10.0.1.50","port":8443} }
}
import java.util.Base64; public class DecodeToBuffer { public static void main(String[] args) { byte[] src = "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=".getBytes(); byte[] dst = new byte[1024]; // pre-allocated int len = Base64.getDecoder().decode(src, dst); String result = new String(dst, 0, len); System.out.println(result); // {"host":"10.0.1.50","port":8443} }
}
import java.util.Base64;
import java.nio.ByteBuffer;
import java.util.UUID; public class DecodeUUID { public static UUID fromBase64(String encoded) { byte[] bytes = Base64.getUrlDecoder().decode(encoded); ByteBuffer bb = ByteBuffer.wrap(bytes); return new UUID(bb.getLong(), bb.getLong()); } public static void main(String[] args) { // Compact Base64-encoded UUID from an API response String uuidStr = "f47ac10b-58cc-4372-a567-0e02b2c3d479"; UUID original = UUID.fromString(uuidStr); // Encode to Base64 (compact form — 22 chars vs 36) ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(original.getMostSignificantBits()); bb.putLong(original.getLeastSignificantBits()); String compact = Base64.getUrlEncoder().withoutPadding() .encodeToString(bb.array()); System.out.println(compact); // 9HrBC1jMQ3KlZw4CssPUeQ // Decode back UUID recovered = fromBase64(compact); System.out.println(recovered); // f47ac10b-58cc-4372-a567-0e02b2c3d479 }
}
import java.util.Base64;
import java.nio.ByteBuffer;
import java.util.UUID; public class DecodeUUID { public static UUID fromBase64(String encoded) { byte[] bytes = Base64.getUrlDecoder().decode(encoded); ByteBuffer bb = ByteBuffer.wrap(bytes); return new UUID(bb.getLong(), bb.getLong()); } public static void main(String[] args) { // Compact Base64-encoded UUID from an API response String uuidStr = "f47ac10b-58cc-4372-a567-0e02b2c3d479"; UUID original = UUID.fromString(uuidStr); // Encode to Base64 (compact form — 22 chars vs 36) ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(original.getMostSignificantBits()); bb.putLong(original.getLeastSignificantBits()); String compact = Base64.getUrlEncoder().withoutPadding() .encodeToString(bb.array()); System.out.println(compact); // 9HrBC1jMQ3KlZw4CssPUeQ // Decode back UUID recovered = fromBase64(compact); System.out.println(recovered); // f47ac10b-58cc-4372-a567-0e02b2c3d479 }
}
import java.util.Base64;
import java.nio.ByteBuffer;
import java.util.UUID; public class DecodeUUID { public static UUID fromBase64(String encoded) { byte[] bytes = Base64.getUrlDecoder().decode(encoded); ByteBuffer bb = ByteBuffer.wrap(bytes); return new UUID(bb.getLong(), bb.getLong()); } public static void main(String[] args) { // Compact Base64-encoded UUID from an API response String uuidStr = "f47ac10b-58cc-4372-a567-0e02b2c3d479"; UUID original = UUID.fromString(uuidStr); // Encode to Base64 (compact form — 22 chars vs 36) ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(original.getMostSignificantBits()); bb.putLong(original.getLeastSignificantBits()); String compact = Base64.getUrlEncoder().withoutPadding() .encodeToString(bb.array()); System.out.println(compact); // 9HrBC1jMQ3KlZw4CssPUeQ // Decode back UUID recovered = fromBase64(compact); System.out.println(recovered); // f47ac10b-58cc-4372-a567-0e02b2c3d479 }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant; public class DecodeJsonPayload { record DeployEvent(String service, String region, Instant deployedAt, int replicas) {} public static void main(String[] args) throws Exception { // Base64-encoded JSON payload from a message queue String encoded = "eyJzZXJ2aWNlIjoicGF5bWVudC1nYXRld2F5Iiwi" + "cmVnaW9uIjoiZXUtd2VzdC0xIiwiZGVwbG95ZWRBdCI6" + "IjIwMjYtMDMtMTVUMTQ6MzA6MDBaIiwicmVwbGljYXMiOjR9"; byte[] jsonBytes = Base64.getDecoder().decode(encoded); String json = new String(jsonBytes, StandardCharsets.UTF_8); System.out.println(json); // {"service":"payment-gateway","region":"eu-west-1", // "deployedAt":"2026-03-15T14:30:00Z","replicas":4} ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); // picks up JavaTimeModule DeployEvent event = mapper.readValue(jsonBytes, DeployEvent.class); System.out.println(event.service()); // payment-gateway System.out.println(event.deployedAt()); // 2026-03-15T14:30:00Z }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant; public class DecodeJsonPayload { record DeployEvent(String service, String region, Instant deployedAt, int replicas) {} public static void main(String[] args) throws Exception { // Base64-encoded JSON payload from a message queue String encoded = "eyJzZXJ2aWNlIjoicGF5bWVudC1nYXRld2F5Iiwi" + "cmVnaW9uIjoiZXUtd2VzdC0xIiwiZGVwbG95ZWRBdCI6" + "IjIwMjYtMDMtMTVUMTQ6MzA6MDBaIiwicmVwbGljYXMiOjR9"; byte[] jsonBytes = Base64.getDecoder().decode(encoded); String json = new String(jsonBytes, StandardCharsets.UTF_8); System.out.println(json); // {"service":"payment-gateway","region":"eu-west-1", // "deployedAt":"2026-03-15T14:30:00Z","replicas":4} ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); // picks up JavaTimeModule DeployEvent event = mapper.readValue(jsonBytes, DeployEvent.class); System.out.println(event.service()); // payment-gateway System.out.println(event.deployedAt()); // 2026-03-15T14:30:00Z }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant; public class DecodeJsonPayload { record DeployEvent(String service, String region, Instant deployedAt, int replicas) {} public static void main(String[] args) throws Exception { // Base64-encoded JSON payload from a message queue String encoded = "eyJzZXJ2aWNlIjoicGF5bWVudC1nYXRld2F5Iiwi" + "cmVnaW9uIjoiZXUtd2VzdC0xIiwiZGVwbG95ZWRBdCI6" + "IjIwMjYtMDMtMTVUMTQ6MzA6MDBaIiwicmVwbGljYXMiOjR9"; byte[] jsonBytes = Base64.getDecoder().decode(encoded); String json = new String(jsonBytes, StandardCharsets.UTF_8); System.out.println(json); // {"service":"payment-gateway","region":"eu-west-1", // "deployedAt":"2026-03-15T14:30:00Z","replicas":4} ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); // picks up JavaTimeModule DeployEvent event = mapper.readValue(jsonBytes, DeployEvent.class); System.out.println(event.service()); // payment-gateway System.out.println(event.deployedAt()); // 2026-03-15T14:30:00Z }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class MimeDecode { public static void main(String[] args) { // PEM certificate body — line-wrapped at 76 characters String pemBody = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t\r\n" + "TUlJQm96Q0NBVWlnQXdJQkFnSUpBSXBhVDJU\r\n" + "aVFvZU1BMEdDU3FHU0liM0RRRUE="; // getDecoder() would throw IllegalArgumentException here byte[] decoded = Base64.getMimeDecoder().decode(pemBody); System.out.println(new String(decoded, StandardCharsets.UTF_8)); // -----BEGIN CERTIFICATE----- // MIIBozCCAUigAwIBAgIJAIpaT2T... }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class MimeDecode { public static void main(String[] args) { // PEM certificate body — line-wrapped at 76 characters String pemBody = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t\r\n" + "TUlJQm96Q0NBVWlnQXdJQkFnSUpBSXBhVDJU\r\n" + "aVFvZU1BMEdDU3FHU0liM0RRRUE="; // getDecoder() would throw IllegalArgumentException here byte[] decoded = Base64.getMimeDecoder().decode(pemBody); System.out.println(new String(decoded, StandardCharsets.UTF_8)); // -----BEGIN CERTIFICATE----- // MIIBozCCAUigAwIBAgIJAIpaT2T... }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class MimeDecode { public static void main(String[] args) { // PEM certificate body — line-wrapped at 76 characters String pemBody = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t\r\n" + "TUlJQm96Q0NBVWlnQXdJQkFnSUpBSXBhVDJU\r\n" + "aVFvZU1BMEdDU3FHU0liM0RRRUE="; // getDecoder() would throw IllegalArgumentException here byte[] decoded = Base64.getMimeDecoder().decode(pemBody); System.out.println(new String(decoded, StandardCharsets.UTF_8)); // -----BEGIN CERTIFICATE----- // MIIBozCCAUigAwIBAgIJAIpaT2T... }
}
import java.util.Base64;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; public class DecodeFile { public static void main(String[] args) { Path inputPath = Path.of("tls-cert.pem.b64"); Path outputPath = Path.of("tls-cert.pem"); try { String encoded = Files.readString(inputPath).strip(); byte[] decoded = Base64.getMimeDecoder().decode(encoded); Files.write(outputPath, decoded); System.out.printf("Decoded %d bytes → %s%n", decoded.length, outputPath); } catch (IOException e) { System.err.println("File error: " + e.getMessage()); } catch (IllegalArgumentException e) { System.err.println("Invalid Base64: " + e.getMessage()); } }
}
import java.util.Base64;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; public class DecodeFile { public static void main(String[] args) { Path inputPath = Path.of("tls-cert.pem.b64"); Path outputPath = Path.of("tls-cert.pem"); try { String encoded = Files.readString(inputPath).strip(); byte[] decoded = Base64.getMimeDecoder().decode(encoded); Files.write(outputPath, decoded); System.out.printf("Decoded %d bytes → %s%n", decoded.length, outputPath); } catch (IOException e) { System.err.println("File error: " + e.getMessage()); } catch (IllegalArgumentException e) { System.err.println("Invalid Base64: " + e.getMessage()); } }
}
import java.util.Base64;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; public class DecodeFile { public static void main(String[] args) { Path inputPath = Path.of("tls-cert.pem.b64"); Path outputPath = Path.of("tls-cert.pem"); try { String encoded = Files.readString(inputPath).strip(); byte[] decoded = Base64.getMimeDecoder().decode(encoded); Files.write(outputPath, decoded); System.out.printf("Decoded %d bytes → %s%n", decoded.length, outputPath); } catch (IOException e) { System.err.println("File error: " + e.getMessage()); } catch (IllegalArgumentException e) { System.err.println("Invalid Base64: " + e.getMessage()); } }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; public class DecodeApiResponse { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/secrets/db-password")) .header("Authorization", "Bearer sk-prod-9f8e7d6c") .build(); try { HttpResponse<String> response = client.send( request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { System.err.printf("Unexpected status: %d%n", response.statusCode()); return; } ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(response.body()); // API returns: {"name":"db-password","value":"cG9zdGdyZXM6eGs5...","version":3} String encodedValue = root.get("value").asText(); byte[] decoded = Base64.getDecoder().decode(encodedValue); String secret = new String(decoded, StandardCharsets.UTF_8); System.out.println("Secret: " + secret); // Secret: postgres:xk9mP2qR@db-prod:5432/orders } catch (Exception e) { System.err.println("Failed to fetch secret: " + e.getMessage()); } }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; public class DecodeApiResponse { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/secrets/db-password")) .header("Authorization", "Bearer sk-prod-9f8e7d6c") .build(); try { HttpResponse<String> response = client.send( request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { System.err.printf("Unexpected status: %d%n", response.statusCode()); return; } ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(response.body()); // API returns: {"name":"db-password","value":"cG9zdGdyZXM6eGs5...","version":3} String encodedValue = root.get("value").asText(); byte[] decoded = Base64.getDecoder().decode(encodedValue); String secret = new String(decoded, StandardCharsets.UTF_8); System.out.println("Secret: " + secret); // Secret: postgres:xk9mP2qR@db-prod:5432/orders } catch (Exception e) { System.err.println("Failed to fetch secret: " + e.getMessage()); } }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; public class DecodeApiResponse { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/secrets/db-password")) .header("Authorization", "Bearer sk-prod-9f8e7d6c") .build(); try { HttpResponse<String> response = client.send( request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { System.err.printf("Unexpected status: %d%n", response.statusCode()); return; } ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(response.body()); // API returns: {"name":"db-password","value":"cG9zdGdyZXM6eGs5...","version":3} String encodedValue = root.get("value").asText(); byte[] decoded = Base64.getDecoder().decode(encodedValue); String secret = new String(decoded, StandardCharsets.UTF_8); System.out.println("Secret: " + secret); // Secret: postgres:xk9mP2qR@db-prod:5432/orders } catch (Exception e) { System.err.println("Failed to fetch secret: " + e.getMessage()); } }
}
# Decode a Base64 string (Linux / macOS)
echo "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=" | base64 --decode
# {"host":"10.0.1.50","port":8443} # Decode and pretty-print with jq
echo "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=" | base64 --decode | jq .
# {
# "host": "10.0.1.50",
# "port": 8443
# } # Quick decode with jshell (JDK 9+)
echo 'System.out.println(new String(java.util.Base64.getDecoder().decode("c2VydmVyLWNvbmZpZw==")))' | jshell -
# server-config # macOS uses -D instead of --decode
echo "c2VydmVyLWNvbmZpZw==" | base64 -D
# Decode a Base64 string (Linux / macOS)
echo "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=" | base64 --decode
# {"host":"10.0.1.50","port":8443} # Decode and pretty-print with jq
echo "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=" | base64 --decode | jq .
# {
# "host": "10.0.1.50",
# "port": 8443
# } # Quick decode with jshell (JDK 9+)
echo 'System.out.println(new String(java.util.Base64.getDecoder().decode("c2VydmVyLWNvbmZpZw==")))' | jshell -
# server-config # macOS uses -D instead of --decode
echo "c2VydmVyLWNvbmZpZw==" | base64 -D
# Decode a Base64 string (Linux / macOS)
echo "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=" | base64 --decode
# {"host":"10.0.1.50","port":8443} # Decode and pretty-print with jq
echo "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=" | base64 --decode | jq .
# {
# "host": "10.0.1.50",
# "port": 8443
# } # Quick decode with jshell (JDK 9+)
echo 'System.out.println(new String(java.util.Base64.getDecoder().decode("c2VydmVyLWNvbmZpZw==")))' | jshell -
# server-config # macOS uses -D instead of --decode
echo "c2VydmVyLWNvbmZpZw==" | base64 -D
<!-- pom.xml -->
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.17.0</version>
</dependency>
<!-- pom.xml -->
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.17.0</version>
</dependency>
<!-- pom.xml -->
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.17.0</version>
</dependency>
import org.apache.commons.codec.binary.Base64; public class CommonsCodecDecode { public static void main(String[] args) { // Commons Codec is more lenient — handles whitespace and line breaks String encoded = "eyJob3N0IjoiMTAuMC4xLjUw\nIiwicG9ydCI6ODQ0M30="; byte[] decoded = Base64.decodeBase64(encoded); System.out.println(new String(decoded)); // {"host":"10.0.1.50","port":8443} }
}
import org.apache.commons.codec.binary.Base64; public class CommonsCodecDecode { public static void main(String[] args) { // Commons Codec is more lenient — handles whitespace and line breaks String encoded = "eyJob3N0IjoiMTAuMC4xLjUw\nIiwicG9ydCI6ODQ0M30="; byte[] decoded = Base64.decodeBase64(encoded); System.out.println(new String(decoded)); // {"host":"10.0.1.50","port":8443} }
}
import org.apache.commons.codec.binary.Base64; public class CommonsCodecDecode { public static void main(String[] args) { // Commons Codec is more lenient — handles whitespace and line breaks String encoded = "eyJob3N0IjoiMTAuMC4xLjUw\nIiwicG9ydCI6ODQ0M30="; byte[] decoded = Base64.decodeBase64(encoded); System.out.println(new String(decoded)); // {"host":"10.0.1.50","port":8443} }
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; public class StreamDecode { public static void main(String[] args) throws IOException { Path src = Path.of("database-dump.sql.b64"); Path dst = Path.of("database-dump.sql"); try (InputStream in = Base64.getMimeDecoder().wrap( new BufferedInputStream(Files.newInputStream(src))); OutputStream out = new BufferedOutputStream(Files.newOutputStream(dst))) { byte[] buffer = new byte[8192]; int bytesRead; long total = 0; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); total += bytesRead; } System.out.printf("Decoded %d bytes → %s%n", total, dst); } }
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; public class StreamDecode { public static void main(String[] args) throws IOException { Path src = Path.of("database-dump.sql.b64"); Path dst = Path.of("database-dump.sql"); try (InputStream in = Base64.getMimeDecoder().wrap( new BufferedInputStream(Files.newInputStream(src))); OutputStream out = new BufferedOutputStream(Files.newOutputStream(dst))) { byte[] buffer = new byte[8192]; int bytesRead; long total = 0; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); total += bytesRead; } System.out.printf("Decoded %d bytes → %s%n", total, dst); } }
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; public class StreamDecode { public static void main(String[] args) throws IOException { Path src = Path.of("database-dump.sql.b64"); Path dst = Path.of("database-dump.sql"); try (InputStream in = Base64.getMimeDecoder().wrap( new BufferedInputStream(Files.newInputStream(src))); OutputStream out = new BufferedOutputStream(Files.newOutputStream(dst))) { byte[] buffer = new byte[8192]; int bytesRead; long total = 0; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); total += bytesRead; } System.out.printf("Decoded %d bytes → %s%n", total, dst); } }
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; public class StreamDecodeSimple { public static void main(String[] args) throws IOException { try (InputStream in = Base64.getMimeDecoder().wrap( new BufferedInputStream(Files.newInputStream(Path.of("backup.tar.b64")))); OutputStream out = Files.newOutputStream(Path.of("backup.tar"))) { in.transferTo(out); // Java 9+ } }
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; public class StreamDecodeSimple { public static void main(String[] args) throws IOException { try (InputStream in = Base64.getMimeDecoder().wrap( new BufferedInputStream(Files.newInputStream(Path.of("backup.tar.b64")))); OutputStream out = Files.newOutputStream(Path.of("backup.tar"))) { in.transferTo(out); // Java 9+ } }
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; public class StreamDecodeSimple { public static void main(String[] args) throws IOException { try (InputStream in = Base64.getMimeDecoder().wrap( new BufferedInputStream(Files.newInputStream(Path.of("backup.tar.b64")))); OutputStream out = Files.newOutputStream(Path.of("backup.tar"))) { in.transferTo(out); // Java 9+ } }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class JWTInspect { public static String decodeJwtPayload(String token) { String[] parts = token.split("\\."); if (parts.length != 3) { throw new IllegalArgumentException( "Invalid JWT: expected 3 segments, got " + parts.length); } // JWT uses URL-safe Base64 without padding byte[] payload = Base64.getUrlDecoder().decode(parts[1]); return new String(payload, StandardCharsets.UTF_8); } public static void main(String[] args) { String token = "eyJhbGciOiJSUzI1NiJ9" + ".eyJzdWIiOiJ1c3ItNjcyIiwiaXNzIjoiYXV0aC5leGFtcGxlLmNvbSIs" + "ImV4cCI6MTc0MTk1NjgwMCwicm9sZXMiOlsiYWRtaW4iLCJiaWxsaW5nIl19" + ".SIGNATURE_PLACEHOLDER"; String payload = decodeJwtPayload(token); System.out.println(payload); // {"sub":"usr-672","iss":"auth.example.com", // "exp":1741956800,"roles":["admin","billing"]} }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class JWTInspect { public static String decodeJwtPayload(String token) { String[] parts = token.split("\\."); if (parts.length != 3) { throw new IllegalArgumentException( "Invalid JWT: expected 3 segments, got " + parts.length); } // JWT uses URL-safe Base64 without padding byte[] payload = Base64.getUrlDecoder().decode(parts[1]); return new String(payload, StandardCharsets.UTF_8); } public static void main(String[] args) { String token = "eyJhbGciOiJSUzI1NiJ9" + ".eyJzdWIiOiJ1c3ItNjcyIiwiaXNzIjoiYXV0aC5leGFtcGxlLmNvbSIs" + "ImV4cCI6MTc0MTk1NjgwMCwicm9sZXMiOlsiYWRtaW4iLCJiaWxsaW5nIl19" + ".SIGNATURE_PLACEHOLDER"; String payload = decodeJwtPayload(token); System.out.println(payload); // {"sub":"usr-672","iss":"auth.example.com", // "exp":1741956800,"roles":["admin","billing"]} }
}
import java.util.Base64;
import java.nio.charset.StandardCharsets; public class JWTInspect { public static String decodeJwtPayload(String token) { String[] parts = token.split("\\."); if (parts.length != 3) { throw new IllegalArgumentException( "Invalid JWT: expected 3 segments, got " + parts.length); } // JWT uses URL-safe Base64 without padding byte[] payload = Base64.getUrlDecoder().decode(parts[1]); return new String(payload, StandardCharsets.UTF_8); } public static void main(String[] args) { String token = "eyJhbGciOiJSUzI1NiJ9" + ".eyJzdWIiOiJ1c3ItNjcyIiwiaXNzIjoiYXV0aC5leGFtcGxlLmNvbSIs" + "ImV4cCI6MTc0MTk1NjgwMCwicm9sZXMiOlsiYWRtaW4iLCJiaWxsaW5nIl19" + ".SIGNATURE_PLACEHOLDER"; String payload = decodeJwtPayload(token); System.out.println(payload); // {"sub":"usr-672","iss":"auth.example.com", // "exp":1741956800,"roles":["admin","billing"]} }
}
// Before — BROKEN
String header = "eyJhbGciOiJSUzI1NiJ9";
byte[] decoded = Base64.getDecoder().decode(header);
// IllegalArgumentException: Illegal base64 character 2d // After — FIXED
String header = "eyJhbGciOiJSUzI1NiJ9";
byte[] decoded = Base64.getUrlDecoder().decode(header);
System.out.println(new String(decoded));
// {"alg":"RS256"}
// Before — BROKEN
String header = "eyJhbGciOiJSUzI1NiJ9";
byte[] decoded = Base64.getDecoder().decode(header);
// IllegalArgumentException: Illegal base64 character 2d // After — FIXED
String header = "eyJhbGciOiJSUzI1NiJ9";
byte[] decoded = Base64.getUrlDecoder().decode(header);
System.out.println(new String(decoded));
// {"alg":"RS256"}
// Before — BROKEN
String header = "eyJhbGciOiJSUzI1NiJ9";
byte[] decoded = Base64.getDecoder().decode(header);
// IllegalArgumentException: Illegal base64 character 2d // After — FIXED
String header = "eyJhbGciOiJSUzI1NiJ9";
byte[] decoded = Base64.getUrlDecoder().decode(header);
System.out.println(new String(decoded));
// {"alg":"RS256"}
// Before — BROKEN
byte[] decoded = Base64.getDecoder().decode(encoded);
String result = new String(decoded);
// platform-dependent — may corrupt multi-byte characters // After — FIXED
byte[] decoded = Base64.getDecoder().decode(encoded);
String result = new String(decoded, StandardCharsets.UTF_8);
// consistent across all platforms
// Before — BROKEN
byte[] decoded = Base64.getDecoder().decode(encoded);
String result = new String(decoded);
// platform-dependent — may corrupt multi-byte characters // After — FIXED
byte[] decoded = Base64.getDecoder().decode(encoded);
String result = new String(decoded, StandardCharsets.UTF_8);
// consistent across all platforms
// Before — BROKEN
byte[] decoded = Base64.getDecoder().decode(encoded);
String result = new String(decoded);
// platform-dependent — may corrupt multi-byte characters // After — FIXED
byte[] decoded = Base64.getDecoder().decode(encoded);
String result = new String(decoded, StandardCharsets.UTF_8);
// consistent across all platforms
// Before — BROKEN
String encoded = System.getenv("DB_PASSWORD_B64"); // "cG9zdGdyZXM=\n"
byte[] decoded = Base64.getDecoder().decode(encoded);
// IllegalArgumentException: Illegal base64 character a // After — FIXED
String encoded = System.getenv("DB_PASSWORD_B64");
byte[] decoded = Base64.getDecoder().decode(encoded.strip());
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// postgres
// Before — BROKEN
String encoded = System.getenv("DB_PASSWORD_B64"); // "cG9zdGdyZXM=\n"
byte[] decoded = Base64.getDecoder().decode(encoded);
// IllegalArgumentException: Illegal base64 character a // After — FIXED
String encoded = System.getenv("DB_PASSWORD_B64");
byte[] decoded = Base64.getDecoder().decode(encoded.strip());
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// postgres
// Before — BROKEN
String encoded = System.getenv("DB_PASSWORD_B64"); // "cG9zdGdyZXM=\n"
byte[] decoded = Base64.getDecoder().decode(encoded);
// IllegalArgumentException: Illegal base64 character a // After — FIXED
String encoded = System.getenv("DB_PASSWORD_B64");
byte[] decoded = Base64.getDecoder().decode(encoded.strip());
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// postgres
// Before — BROKEN
byte[] decoded = Base64.getDecoder().decode(pngBase64);
String imageStr = new String(decoded); // corrupts binary
Files.writeString(Path.of("image.png"), imageStr); // broken file // After — FIXED
byte[] decoded = Base64.getDecoder().decode(pngBase64);
// Write bytes directly — no String conversion
Files.write(Path.of("image.png"), decoded);
// Before — BROKEN
byte[] decoded = Base64.getDecoder().decode(pngBase64);
String imageStr = new String(decoded); // corrupts binary
Files.writeString(Path.of("image.png"), imageStr); // broken file // After — FIXED
byte[] decoded = Base64.getDecoder().decode(pngBase64);
// Write bytes directly — no String conversion
Files.write(Path.of("image.png"), decoded);
// Before — BROKEN
byte[] decoded = Base64.getDecoder().decode(pngBase64);
String imageStr = new String(decoded); // corrupts binary
Files.writeString(Path.of("image.png"), imageStr); // broken file // After — FIXED
byte[] decoded = Base64.getDecoder().decode(pngBase64);
// Write bytes directly — no String conversion
Files.write(Path.of("image.png"), decoded);
import java.util.Base64;
import java.nio.charset.StandardCharsets; byte[] decoded = Base64.getDecoder().decode("c2VydmVyLWNvbmZpZw==");
String result = new String(decoded, StandardCharsets.UTF_8);
System.out.println(result); // server-config
import java.util.Base64;
import java.nio.charset.StandardCharsets; byte[] decoded = Base64.getDecoder().decode("c2VydmVyLWNvbmZpZw==");
String result = new String(decoded, StandardCharsets.UTF_8);
System.out.println(result); // server-config
import java.util.Base64;
import java.nio.charset.StandardCharsets; byte[] decoded = Base64.getDecoder().decode("c2VydmVyLWNvbmZpZw==");
String result = new String(decoded, StandardCharsets.UTF_8);
System.out.println(result); // server-config
String wrapped = "c2VydmVyLWNv\r\nbmZpZw=="; // getDecoder() throws IllegalArgumentException
// Base64.getDecoder().decode(wrapped); // FAILS // getMimeDecoder() handles it
byte[] decoded = Base64.getMimeDecoder().decode(wrapped);
System.out.println(new String(decoded)); // server-config
String wrapped = "c2VydmVyLWNv\r\nbmZpZw=="; // getDecoder() throws IllegalArgumentException
// Base64.getDecoder().decode(wrapped); // FAILS // getMimeDecoder() handles it
byte[] decoded = Base64.getMimeDecoder().decode(wrapped);
System.out.println(new String(decoded)); // server-config
String wrapped = "c2VydmVyLWNv\r\nbmZpZw=="; // getDecoder() throws IllegalArgumentException
// Base64.getDecoder().decode(wrapped); // FAILS // getMimeDecoder() handles it
byte[] decoded = Base64.getMimeDecoder().decode(wrapped);
System.out.println(new String(decoded)); // server-config
import java.util.Base64; // JWT header — URL-safe, no padding
String jwtHeader = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
byte[] decoded = Base64.getUrlDecoder().decode(jwtHeader);
System.out.println(new String(decoded));
// {"alg":"HS256","typ":"JWT"}
import java.util.Base64; // JWT header — URL-safe, no padding
String jwtHeader = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
byte[] decoded = Base64.getUrlDecoder().decode(jwtHeader);
System.out.println(new String(decoded));
// {"alg":"HS256","typ":"JWT"}
import java.util.Base64; // JWT header — URL-safe, no padding
String jwtHeader = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
byte[] decoded = Base64.getUrlDecoder().decode(jwtHeader);
System.out.println(new String(decoded));
// {"alg":"HS256","typ":"JWT"}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; try (InputStream in = Base64.getDecoder().wrap( new BufferedInputStream(new FileInputStream("payload.b64"))); OutputStream out = new FileOutputStream("payload.bin")) { in.transferTo(out);
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; try (InputStream in = Base64.getDecoder().wrap( new BufferedInputStream(new FileInputStream("payload.b64"))); OutputStream out = new FileOutputStream("payload.bin")) { in.transferTo(out);
}
import java.util.Base64;
import java.io.*;
import java.nio.file.*; try (InputStream in = Base64.getDecoder().wrap( new BufferedInputStream(new FileInputStream("payload.b64"))); OutputStream out = new FileOutputStream("payload.bin")) { in.transferTo(out);
}
String raw = "c2VydmVyLWNvbmZpZw==\n"; // trailing newline // Option 1: trim whitespace
byte[] decoded = Base64.getDecoder().decode(raw.strip()); // Option 2: use MIME decoder which ignores whitespace
byte[] decoded2 = Base64.getMimeDecoder().decode(raw);
String raw = "c2VydmVyLWNvbmZpZw==\n"; // trailing newline // Option 1: trim whitespace
byte[] decoded = Base64.getDecoder().decode(raw.strip()); // Option 2: use MIME decoder which ignores whitespace
byte[] decoded2 = Base64.getMimeDecoder().decode(raw);
String raw = "c2VydmVyLWNvbmZpZw==\n"; // trailing newline // Option 1: trim whitespace
byte[] decoded = Base64.getDecoder().decode(raw.strip()); // Option 2: use MIME decoder which ignores whitespace
byte[] decoded2 = Base64.getMimeDecoder().decode(raw); - Base64.getDecoder().decode(s) is the standard approach — built into java.util.Base64 since JDK 8, no dependencies needed.
- Use getUrlDecoder() for JWT tokens and OAuth payloads — they use the - and _ alphabet, not + and /.
- getMimeDecoder() ignores line breaks and whitespace, making it the right choice for email attachments and PEM certificates.
- decoder.wrap(InputStream) decodes on the fly for large files without loading everything into memory.
- The basic decoder is strict — trailing newlines, spaces, or wrong alphabet characters throw IllegalArgumentException immediately.