java
45 lines · 7 steps
Authenticated encryption with AES-GCM in Java
A small helper that encrypts and decrypts strings using AES-GCM, packing the random IV alongside the ciphertext.
Explained by
highlit
1public final class AesGcmCipher {
2
3 private static final String TRANSFORMATION = "AES/GCM/NoPadding";
4 private static final int GCM_TAG_BITS = 128;
5 private static final int IV_LENGTH = 12;
6
7 private final SecretKey key;
8 private final SecureRandom random = new SecureRandom();
9
10 public AesGcmCipher(SecretKey key) {
11 this.key = key;
12 }
13
14 public String encrypt(String plaintext) throws GeneralSecurityException {
15 byte[] iv = new byte[IV_LENGTH];
16 random.nextBytes(iv);
17
18 Cipher cipher = Cipher.getInstance(TRANSFORMATION);
19 cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_BITS, iv));
20 byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
21
22 byte[] combined = ByteBuffer.allocate(iv.length + ciphertext.length)
23 .put(iv)
24 .put(ciphertext)
25 .array();
26 return Base64.getEncoder().encodeToString(combined);
27 }
28
29 public String decrypt(String encoded) throws GeneralSecurityException {
30 byte[] combined = Base64.getDecoder().decode(encoded);
31 if (combined.length <= IV_LENGTH) {
32 throw new IllegalArgumentException("Malformed ciphertext");
33 }
34
35 ByteBuffer buffer = ByteBuffer.wrap(combined);
36 byte[] iv = new byte[IV_LENGTH];
37 buffer.get(iv);
38 byte[] ciphertext = new byte[buffer.remaining()];
39 buffer.get(ciphertext);
40
41 Cipher cipher = Cipher.getInstance(TRANSFORMATION);
42 cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_BITS, iv));
43 return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
44 }
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1GCM needs a fresh random IV for every encryption, so a shared key stays secure across many messages.
- 2Prepending the IV to the ciphertext lets you decrypt later with no separate metadata to track.
- 3The 128-bit GCM tag provides integrity, so tampered ciphertext fails to decrypt instead of returning garbage.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/authenticated-encryption-with-aes-gcm-in-java-explained-java-918f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.