AES Encryption in Java: CBC, GCM Modes & SecretKey Generation

AES is the standard symmetric cipher: the same secret key encrypts and decrypts. Using it safely depends less on AES itself than on the mode around it. This page builds AES-GCM encryption step by step and shows, with running code, what goes wrong with ECB and with a reused IV.

Share

Contents

How AES and its modes work

AES (the Advanced Encryption Standard, FIPS 197, 2001) is a block cipher: with a key of 128, 192 or 256 bits, it turns one 16-byte block into another 16-byte block, in 10, 12 or 14 rounds of substitution and mixing. On its own it can only encrypt exactly 16 bytes. A mode of operation defines how to encrypt longer data, and the choice of mode decides most of the security. Modern processors have AES instructions (AES-NI), and the JDK uses them through HotSpot intrinsics.

In Java, a cipher is chosen with a transformation string of the form algorithm/mode/padding, such as AES/GCM/NoPadding, passed to Cipher.getInstance. The cipher is then initialized with a key, a mode (encrypt or decrypt) and parameters such as the IV.

Symmetric encryption modes in the JDK
TransformationAuthenticatedIVBest for
AES/GCM/NoPaddingYes (16-byte tag)12 bytes, unique per messageNew code: the default choice
ChaCha20-Poly1305 (Java 11, JEP 329)Yes12 bytes, unique per messageCPUs without AES instructions; TLS 1.3
AES/CTR/NoPaddingNo16 bytes, uniqueBuilding blocks; random access into encrypted data
AES/CBC/PKCS5PaddingNo16 bytes, randomLegacy formats, always with an HMAC
AES/ECB/...NoNoneNothing: it leaks patterns

All programs use only the JDK and were run on JDK 21.

Encrypting with AES-GCM

AES encrypts 16-byte blocks with a 128-, 192- or 256-bit key. A mode defines how longer messages are handled. GCM is the recommended mode because it is authenticated encryption: besides hiding the data, it adds a 16-byte tag that detects any change. Each encryption needs a unique 12-byte IV (also called a nonce), which does not have to be secret, so it is stored in front of the ciphertext.

The program first checks the JDK against test case 2 of the GCM specification (all-zero key, IV and data), then encrypts a short message with a random 256-bit key and attempts two kinds of tampering.

Java
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HexFormat;
import javax.crypto.AEADBadTagException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AesGcm {

    static final int IV_BYTES = 12;
    static final int TAG_BITS = 128;
    static final SecureRandom RANDOM = new SecureRandom();

    // Output layout: IV (12 bytes) followed by ciphertext with the 16-byte tag at the end
    static byte[] encrypt(SecretKey key, byte[] plaintext, byte[] aad) throws Exception {
        byte[] iv = new byte[IV_BYTES];
        RANDOM.nextBytes(iv);                        // a fresh IV for every message
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
        c.updateAAD(aad);
        byte[] ct = c.doFinal(plaintext);
        return ByteBuffer.allocate(IV_BYTES + ct.length).put(iv).put(ct).array();
    }

    static byte[] decrypt(SecretKey key, byte[] message, byte[] aad) throws Exception {
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, message, 0, IV_BYTES));
        c.updateAAD(aad);
        return c.doFinal(message, IV_BYTES, message.length - IV_BYTES);
    }

    public static void main(String[] args) throws Exception {
        // Known-answer test from the GCM specification (test case 2: all-zero key, IV, data)
        Cipher kat = Cipher.getInstance("AES/GCM/NoPadding");
        kat.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[16], "AES"),
                new GCMParameterSpec(128, new byte[12]));
        String out = HexFormat.of().formatHex(kat.doFinal(new byte[16]));
        System.out.println("test vector matches: " + out.equals(
                "0388dace60b6a392f328c2b971b2fe78" + "ab6e47d42cec13bdf53a67b21257bddf"));

        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(256);
        SecretKey key = kg.generateKey();
        byte[] aad = "user=42".getBytes(StandardCharsets.UTF_8);   // authenticated, not secret
        byte[] plain = "card ending 4242, expires 09/28".getBytes(StandardCharsets.UTF_8);

        byte[] msg = encrypt(key, plain, aad);
        System.out.println("plaintext " + plain.length + " bytes -> message " + msg.length
                + " bytes (12 IV + " + plain.length + " ciphertext + 16 tag)");
        System.out.println("decrypted: " + new String(decrypt(key, msg, aad),
                StandardCharsets.UTF_8));

        byte[] again = encrypt(key, plain, aad);
        System.out.println("same plaintext encrypted twice gives different bytes: "
                + !HexFormat.of().formatHex(msg).equals(HexFormat.of().formatHex(again)));

        byte[] tampered = msg.clone();
        tampered[20] ^= 1;                           // flip one bit of the ciphertext
        try {
            decrypt(key, tampered, aad);
        } catch (AEADBadTagException e) {
            System.out.println("one flipped bit: AEADBadTagException (" + e.getMessage() + ")");
        }
        try {
            decrypt(key, msg, "user=43".getBytes(StandardCharsets.UTF_8));
        } catch (AEADBadTagException e) {
            System.out.println("different associated data: AEADBadTagException");
        }
    }
}

Output:

Output
test vector matches: true
plaintext 31 bytes -> message 59 bytes (12 IV + 31 ciphertext + 16 tag)
decrypted: card ending 4242, expires 09/28
same plaintext encrypted twice gives different bytes: true
one flipped bit: AEADBadTagException (Tag mismatch)
different associated data: AEADBadTagException
  • The test vector matches, so AES/GCM/NoPadding is the standard algorithm.
  • The 31-byte text became 59 bytes: GCM does not pad, so the ciphertext has the same length as the plaintext, plus the 12-byte IV and the 16-byte tag.
  • Encrypting the same text twice gives different output because each call uses a fresh random IV. An observer cannot tell that two messages are equal.
  • Flipping a single bit made decryption fail with AEADBadTagException instead of returning altered data. With unauthenticated modes such as CBC, the same change would silently produce garbage, or worse, a controlled change.
  • The associated data ("user=42") is not encrypted but is covered by the tag. Decrypting with "user=43" fails, so a ciphertext cannot be moved to another user's record.

What goes wrong with ECB and reused IVs

The second program shows three mistakes that still appear in production code.

Java
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;

public class ModePitfalls {

    public static void main(String[] args) throws Exception {
        SecretKey key = KeyGenerator.getInstance("AES").generateKey();

        // ECB encrypts equal 16-byte blocks to equal ciphertext blocks: patterns leak
        byte[] twoSameBlocks = "SALARY=0100000;;SALARY=0100000;;"
                .getBytes(StandardCharsets.US_ASCII);
        Cipher ecb = Cipher.getInstance("AES/ECB/NoPadding");
        ecb.init(Cipher.ENCRYPT_MODE, key);
        String hex = HexFormat.of().formatHex(ecb.doFinal(twoSameBlocks));
        System.out.println("ECB block 1: " + hex.substring(0, 32));
        System.out.println("ECB block 2: " + hex.substring(32));
        System.out.println("ECB blocks identical: "
                + hex.substring(0, 32).equals(hex.substring(32)));

        // "AES" alone means ECB with padding in the default provider
        System.out.println("Cipher.getInstance(\"AES\") algorithm: "
                + Cipher.getInstance("AES").getAlgorithm()
                + ", block mode is ECB: " + isEcb(key));

        // GCM with a repeated IV: the JDK refuses to encrypt twice with the same key and IV
        byte[] iv = new byte[12];
        Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding");
        gcm.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        gcm.doFinal("first".getBytes(StandardCharsets.US_ASCII));
        try {
            gcm.doFinal("second".getBytes(StandardCharsets.US_ASCII));
        } catch (IllegalStateException e) {
            System.out.println("reusing the IV in one Cipher: IllegalStateException");
        }

        // With separate Cipher objects nothing stops it, and the plaintexts leak:
        // XOR of the two ciphertexts equals XOR of the two plaintexts
        byte[] p1 = "attack at dawn!!".getBytes(StandardCharsets.US_ASCII);
        byte[] p2 = "retreat at noon!".getBytes(StandardCharsets.US_ASCII);
        byte[] c1 = encryptWith(key, iv, p1);
        byte[] c2 = encryptWith(key, iv, p2);
        boolean leaks = true;
        for (int i = 0; i < p1.length; i++) {
            leaks &= (c1[i] ^ c2[i]) == (p1[i] ^ p2[i]);
        }
        System.out.println("repeated IV: c1 XOR c2 == p1 XOR p2 for every byte: " + leaks);
    }

    static boolean isEcb(SecretKey key) throws Exception {
        Cipher plain = Cipher.getInstance("AES");
        Cipher ecb = Cipher.getInstance("AES/ECB/PKCS5Padding");
        plain.init(Cipher.ENCRYPT_MODE, key);
        ecb.init(Cipher.ENCRYPT_MODE, key);
        byte[] data = "same input".getBytes(StandardCharsets.US_ASCII);
        return Arrays.equals(plain.doFinal(data), ecb.doFinal(data));
    }

    static byte[] encryptWith(SecretKey key, byte[] iv, byte[] p) throws Exception {
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        return c.doFinal(p);
    }
}

Output (the hex values change with the random key; the comparisons do not):

Output
ECB block 1: 733d7485335fba1ef396bbeba4db0582
ECB block 2: 733d7485335fba1ef396bbeba4db0582
ECB blocks identical: true
Cipher.getInstance("AES") algorithm: AES, block mode is ECB: true
reusing the IV in one Cipher: IllegalStateException
repeated IV: c1 XOR c2 == p1 XOR p2 for every byte: true
  1. ECB leaks patterns: ECB encrypts each block independently, so the two identical 16-byte blocks produced identical ciphertext. Anyone can see which records share a value without knowing the key.
  2. Cipher.getInstance("AES") means ECB: the JDK's default for a bare "AES" is ECB with PKCS5 padding, confirmed by comparing the outputs. Always name the full transformation, such as AES/GCM/NoPadding.
  3. Never reuse an IV with the same key in GCM: the JDK refuses a second encryption with the same key and IV in one Cipher object, but separate objects cannot know about each other. With a repeated IV, the XOR of the two ciphertexts equals the XOR of the two plaintexts, which often reveals both, and it also allows tags to be forged. A random 12-byte IV per message is safe for up to about 232 messages per key; beyond that, rotate keys.

CBC: padding and silent tampering

CBC is still common in older systems, so it is worth seeing why unauthenticated encryption is dangerous. The program shows how padding rounds up the ciphertext, then changes a payment amount inside an encrypted message without knowing the key, by flipping bits in the IV.

Java
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class CbcMalleability {

    public static void main(String[] args) throws Exception {
        SecretKey key = KeyGenerator.getInstance("AES").generateKey();
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);

        // Padding: CBC output is always a whole number of 16-byte blocks
        Cipher cbc = Cipher.getInstance("AES/CBC/PKCS5Padding");
        for (int len : new int[] {0, 1, 15, 16, 17}) {
            cbc.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
            System.out.println(len + " bytes of plaintext -> " + cbc.doFinal(new byte[len]).length
                    + " bytes of ciphertext");
        }

        // An attacker who knows the format can change it without the key
        byte[] plain = "pay=0100;to=bob;".getBytes(StandardCharsets.US_ASCII);  // one block
        cbc.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
        byte[] ct = cbc.doFinal(plain);
        byte[] evilIv = iv.clone();
        // XOR the IV where the digits "0100" sit, turning them into "9100"
        evilIv[4] ^= (byte) ('0' ^ '9');
        cbc.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(evilIv));
        String tampered = new String(cbc.doFinal(ct), StandardCharsets.US_ASCII);
        System.out.println("original:          " + new String(plain, StandardCharsets.US_ASCII));
        System.out.println("after IV bit flip: " + tampered + "   (no error raised)");

        // Damage to a ciphertext block garbles that block and flips bits in the next
        byte[] two = "block one: AAAA.block two: BBBB.".getBytes(StandardCharsets.US_ASCII);
        cbc.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
        byte[] ct2 = cbc.doFinal(two);
        ct2[0] ^= 1;
        cbc.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
        byte[] out = cbc.doFinal(ct2);
        System.out.println("block 2 after flipping a bit of block 1: "
                + new String(out, 16, 16, StandardCharsets.US_ASCII));
        System.out.println("block 1 is garbage: " + !new String(out, 0, 16,
                StandardCharsets.US_ASCII).equals("block one: AAAA."));
    }
}

Output:

Output
0 bytes of plaintext -> 16 bytes of ciphertext
1 bytes of plaintext -> 16 bytes of ciphertext
15 bytes of plaintext -> 16 bytes of ciphertext
16 bytes of plaintext -> 32 bytes of ciphertext
17 bytes of plaintext -> 32 bytes of ciphertext
original:          pay=0100;to=bob;
after IV bit flip: pay=9100;to=bob;   (no error raised)
block 2 after flipping a bit of block 1: clock two: BBBB.
block 1 is garbage: true
  • PKCS5 padding always adds 1 to 16 bytes, so 0 to 15 bytes of plaintext became 16 bytes of ciphertext and exactly 16 bytes became 32: a full block of padding is added when the input is already aligned.
  • In CBC, the first plaintext block is decrypted and then XORed with the IV. XORing the IV byte at position 4 with '0' ^ '9' turned "pay=0100" into "pay=9100", and decryption raised no error. An attacker who knows or guesses the message format can make targeted edits.
  • Flipping one bit of the first ciphertext block garbled that whole block and flipped the same bit in the next one: "block two" became "clock two". Changes to the ciphertext are not detected, only made harder to control.
  • Padding errors are a further risk: a server that reports bad padding differently from other errors gives a padding oracle, which lets an attacker decrypt messages. Authenticated modes avoid both problems, or CBC must be followed by an HMAC over IV and ciphertext that is checked before decrypting.

Encrypting files and streams

For data that does not fit in one byte array, CipherOutputStream and CipherInputStream encrypt and decrypt as data flows through. The program encrypts a 3 MB file with AES-GCM, storing the IV at the start, decrypts it, and then flips one byte in the middle of the encrypted file.

Java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;

public class FileEncryption {

    // File format: 12-byte IV, then the GCM ciphertext with its 16-byte tag at the end
    static void encrypt(SecretKey key, Path in, Path out) throws Exception {
        byte[] iv = new byte[12];
        new SecureRandom().nextBytes(iv);
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        try (OutputStream raw = Files.newOutputStream(out)) {
            raw.write(iv);
            try (InputStream src = Files.newInputStream(in);
                 OutputStream enc = new CipherOutputStream(raw, c)) {
                src.transferTo(enc);                   // close() writes the tag
            }
        }
    }

    static byte[] decrypt(SecretKey key, Path in) throws Exception {
        try (InputStream raw = Files.newInputStream(in)) {
            byte[] iv = raw.readNBytes(12);
            Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
            c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
            try (InputStream dec = new CipherInputStream(raw, c)) {
                return dec.readAllBytes();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Path plain = Files.createTempFile("report", ".bin");
        Path sealed = Files.createTempFile("report", ".enc");
        byte[] content = new byte[3000000];
        new Random(1).nextBytes(content);
        Files.write(plain, content);
        SecretKey key = KeyGenerator.getInstance("AES").generateKey();

        encrypt(key, plain, sealed);
        System.out.println("plain " + Files.size(plain) + " bytes, encrypted "
                + Files.size(sealed) + " bytes (+12 IV +16 tag)");
        byte[] back = decrypt(key, sealed);
        System.out.println("decrypted equals original: " + MessageDigest.isEqual(back, content));

        // Change one byte in the middle of the encrypted file
        byte[] bytes = Files.readAllBytes(sealed);
        bytes[1500000] ^= 1;
        Files.write(sealed, bytes);
        try {
            decrypt(key, sealed);
            System.out.println("tampered file decrypted (unexpected)");
        } catch (IOException e) {
            System.out.println("tampered file: " + e.getClass().getSimpleName() + " caused by "
                    + e.getCause().getClass().getSimpleName());
        }
        Files.delete(plain);
        Files.delete(sealed);
    }
}

Output:

Output
plain 3000000 bytes, encrypted 3000028 bytes (+12 IV +16 tag)
decrypted equals original: true
tampered file: IOException caused by AEADBadTagException
  • The encrypted file is exactly 28 bytes longer: the 12-byte IV written first and the 16-byte tag that CipherOutputStream.close() writes at the end. Forgetting to close the stream leaves the tag out, and the file can never be decrypted.
  • The tampered file failed with an IOException whose cause is AEADBadTagException. Catch it as a decryption failure, not as a disk error.
  • GCM can only confirm the data after reading the tag at the very end, and the JDK's provider does not release decrypted bytes before that check, so CipherInputStream holds the whole plaintext in memory until the end. For multi-gigabyte files, split the data into chunks of, say, 1 MB, each encrypted with its own IV and tag, as formats such as Google Tink's streaming AEAD do.

ChaCha20-Poly1305 and the speed of each mode

ChaCha20-Poly1305, added in Java 11, is the other authenticated cipher in the JDK. The program uses it once, then measures four transformations encrypting 32 messages of 1 MB, fed in 16 KB update calls, plus GCM with one doFinal per message. Five warm-up rounds come before the best of 3; this is a rough comparison on a 2-CPU Linux virtual machine whose processor has AES, carry-less multiplication and AVX-512 instructions.

Java
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;

public class ChaChaAndSpeed {

    public static void main(String[] args) throws Exception {
        SecureRandom rnd = new SecureRandom();

        // ChaCha20-Poly1305 (Java 11+): the same AEAD shape as AES-GCM
        SecretKey chachaKey = KeyGenerator.getInstance("ChaCha20").generateKey();
        byte[] nonce = new byte[12];
        rnd.nextBytes(nonce);
        Cipher chacha = Cipher.getInstance("ChaCha20-Poly1305");
        chacha.init(Cipher.ENCRYPT_MODE, chachaKey, new IvParameterSpec(nonce));
        byte[] ct = chacha.doFinal("hello, chacha".getBytes(StandardCharsets.UTF_8));
        chacha.init(Cipher.DECRYPT_MODE, chachaKey, new IvParameterSpec(nonce));
        System.out.println("ChaCha20-Poly1305: 13 bytes -> " + ct.length + " bytes, decrypts to \""
                + new String(chacha.doFinal(ct), StandardCharsets.UTF_8) + "\"");

        // Throughput: 32 messages of 1 MB per round, fed in 16 KB update() calls,
        // except one variant that passes each 1 MB message to a single doFinal()
        byte[] data = new byte[1024 * 1024];
        rnd.nextBytes(data);
        SecretKey aes = KeyGenerator.getInstance("AES").generateKey();
        String[] names = {"AES/GCM/NoPadding", "AES/CBC/PKCS5Padding", "AES/CTR/NoPadding",
            "ChaCha20-Poly1305", "AES/GCM/NoPadding"};
        String[] how = {"16 KB updates", "16 KB updates", "16 KB updates", "16 KB updates",
            "one doFinal"};
        long[] best = new long[names.length];
        java.util.Arrays.fill(best, Long.MAX_VALUE);
        for (int round = 0; round < 8; round++) {                // rounds 0 to 4 warm up
            for (int i = 0; i < names.length; i++) {
                Cipher c = Cipher.getInstance(names[i]);
                byte[] iv = new byte[names[i].contains("CBC") || names[i].contains("CTR")
                        ? 16 : 12];
                long t0 = System.nanoTime();
                for (int m = 0; m < 32; m++) {
                    rnd.nextBytes(iv);                           // a fresh IV per message
                    if (names[i].contains("GCM")) {
                        c.init(Cipher.ENCRYPT_MODE, aes, new GCMParameterSpec(128, iv));
                    } else if (names[i].startsWith("ChaCha")) {
                        c.init(Cipher.ENCRYPT_MODE, chachaKey, new IvParameterSpec(iv));
                    } else {
                        c.init(Cipher.ENCRYPT_MODE, aes, new IvParameterSpec(iv));
                    }
                    if (i == 4) {
                        c.doFinal(data);
                    } else {
                        for (int off = 0; off < data.length; off += 16 * 1024) {
                            c.update(data, off, 16 * 1024);
                        }
                        c.doFinal();
                    }
                }
                if (round > 4) {
                    best[i] = Math.min(best[i], System.nanoTime() - t0);
                }
            }
        }
        System.out.println("encrypting 32 messages of 1 MB, best of 3 rounds:");
        for (int i = 0; i < names.length; i++) {
            System.out.printf("  %-21s %-14s %6.0f MB/s%n", names[i], how[i],
                    32 / (best[i] / 1e9));
        }
    }
}

Output of the cipher speed run:

Output
ChaCha20-Poly1305: 13 bytes -> 29 bytes, decrypts to "hello, chacha"
encrypting 32 messages of 1 MB, best of 3 rounds:
  AES/GCM/NoPadding     16 KB updates    4930 MB/s
  AES/CBC/PKCS5Padding  16 KB updates     981 MB/s
  AES/CTR/NoPadding     16 KB updates    6013 MB/s
  ChaCha20-Poly1305     16 KB updates    2002 MB/s
  AES/GCM/NoPadding     one doFinal      4894 MB/s
  • ChaCha20-Poly1305 has the same shape as GCM: a 12-byte nonce, and 13 bytes of text became 29 bytes, the text plus a 16-byte tag.
  • AES-GCM and AES-CTR ran at several gigabytes per second, because HotSpot's intrinsics process many blocks in parallel with the AES and vector instructions. Authentication with GCM cost little on top of CTR.
  • CBC was several times slower than CTR and GCM, because each block must wait for the previous block's ciphertext, so encryption cannot be parallelized. ChaCha20-Poly1305 sat in between here; on processors without AES instructions it is usually the fastest option.
  • Warm-up matters a great deal. In a separate run on the same machine that only ever called doFinal on whole 1 MB messages, GCM stayed below 100 MB/s for 15 rounds, while 16 KB messages reached over 1 GB/s after a few rounds. The fast paths need compiled code, and a few large calls give the JIT compiler little to work with. Measure in your own application before drawing conclusions from microbenchmarks.

Practical guidance

AES choices
ChoiceRecommendation
ModeGCM (AES/GCM/NoPadding); ChaCha20-Poly1305 is a good alternative on CPUs without AES instructions
Key size256 bits via KeyGenerator; 128 bits is also considered secure
IV12 random bytes from SecureRandom, new for every message, stored with the ciphertext
Tag128 bits
Key from a passwordDerive it with PBKDF2 and a salt; never use the password bytes directly. See SecureRandom and PBKDF2
Key storageA key management service or a KeyStore, not source code or plain config files

AES-CBC is still found in older systems. It needs a random 16-byte IV and padding, and because it is not authenticated it must be combined with an HMAC (encrypt-then-MAC). For new code, GCM does both in one step. For encrypting to someone without a shared key, see RSA encryption.