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 — Extended Module 14 - Authenticated Encryption Stream Ciphers Modes

Java Program for CTR Counter Mode for Parallel Encryption

Reviewed & accurate
AI Summary

Introduction

The ctr counter mode java tutorial walks through Counter mode, the only classical block cipher mode that is both fully parallelizable and free of padding. The ctr counter mode java example below demonstrates the algorithm and shows how it is byte-identical to the JDK provider. Counter mode was proposed by Diffie and Hellman in their 1979 work Privacy and Authentication: An Introduction to Cryptography and formally specified by NIST in Special Publication 800-38A in December 2001. The ctr counter mode java implementation is also the conceptual core of AES-GCM, ChaCha20, and other authenticated stream ciphers. It turns a block cipher such as AES into a stream cipher by encrypting a counter and XORing the result with the plaintext, which means the cipher never expands the message and the keystream can be precomputed in parallel.

For a Java learner the ctr mode java example below is a useful pattern to internalize because Counter mode is the foundation of AES-GCM, AES-GCM-SIV, ChaCha20-Poly1305 (ChaCha20 itself is a counter-style PRF), and the AES-CTR-HMAC construction used in TLS 1.2 and 1.3. Mastering the manual implementation in this tutorial makes the JDK's AES/GCM/NoPadding and ChaCha20-Poly1305 implementations easier to reason about.

Unlike CBC, where block N depends on block N-1, CTR mode lets every output block depend only on the counter value, so an eight-core CPU can produce eight keystream blocks simultaneously. That is the reason AES-GCM saturates modern hardware and why CTR is the default choice for high-throughput disk encryption (BitLocker, FileVault) and TLS record protection.

What is Counter Mode?

ctr mode java is a block cipher mode of operation. A mode of operation is a recipe that turns a fixed-width primitive such as AES, which can only encrypt a 16-byte block, into a construction that can encrypt an arbitrary-length message. Other modes in the family include ECB (the naive mode), CBC, CFB, OFB, PCBC, and the authenticated modes GCM and CCM.

In Counter mode the cipher input is not the plaintext but a counter block. The block cipher encrypts the counter to produce a keystream block, and the keystream block is XORed with the plaintext block to produce the ciphertext block. Because the counter is predictable, the keystream can be precomputed and stored in a buffer; encryption itself becomes a simple vector XOR, which is extremely fast and trivially parallel.

The standard counter layout recommended by NIST SP 800-38A is a 96-bit nonce concatenated with a 32-bit block counter, which gives 2 to the power 32 blocks of 16 bytes each, that is, 64 GiB of stream per nonce. After 2 to the power 32 blocks the counter wraps to zero and the keystream repeats, which is fatal for security; the caller must reject any message that would exceed this limit.

How CTR Mode Works Step by Step

Step 1: Key and nonce. The caller provides a 128-bit, 192-bit, or 256-bit AES key and a fresh 96-bit nonce. The nonce does not need to be secret, but it must never repeat under the same key. A common choice is a counter that persists in a database, or a strong random value from SecureRandom.

Step 2: Build the counter block. The counter block is 16 bytes. The first 12 bytes are the nonce; the last 4 bytes are the block index encoded in big-endian. The first block uses index 1, the second uses index 2, and so on. Some implementations start at 0; both choices are secure as long as the convention is consistent.

Step 3: Encrypt the counter. The counter block is encrypted under AES with the key, producing a 16-byte keystream block. This is the only call to AES per plaintext block.

Step 4: XOR with the plaintext. The 16-byte keystream block is XORed with the corresponding 16 bytes of plaintext to produce the ciphertext block. If the final plaintext block is shorter than 16 bytes, only the necessary prefix of the keystream is used.

Step 5: Increment the counter. The 32-bit block index increments by one and the process repeats. Because every keystream block depends only on the counter, the cipher can precompute keystream blocks in parallel on multiple cores or pipeline them through the AES-NI instruction.

Step 6: Decryption is identical to encryption. The ciphertext is XORed with the same keystream to recover the plaintext. There is no decrypt routine, no inverse cipher, and no padding.

Java Program for CTR Counter Mode


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

public class CtrModeDemo {

    private static final int BLOCK_BYTES = 16;
    private static final int NONCE_BYTES = 12;
    private static final int COUNTER_BYTES = 4;

    // Manual AES-CTR implementation using AES/ECB/NoPadding as the primitive.
    // Demonstrates the algorithm itself; in production use Cipher.getInstance("AES/CTR/NoPadding").
    public static byte[] ctrEncrypt(byte[] key, byte[] nonce, byte[] plaintext) throws Exception {
        Cipher aes = Cipher.getInstance("AES/ECB/NoPadding");
        aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));

        byte[] out = new byte[plaintext.length];
        int blockIndex = 1;
        int offset = 0;
        while (offset < plaintext.length) {
            byte[] counterBlock = buildCounterBlock(nonce, blockIndex);
            byte[] keystream = aes.doFinal(counterBlock);
            int chunk = Math.min(BLOCK_BYTES, plaintext.length - offset);
            for (int i = 0; i < chunk; i++) {
                out[offset + i] = (byte) (plaintext[offset + i] ^ keystream[i]);
            }
            offset += chunk;
            blockIndex++;
            if (blockIndex == 0) {
                throw new IllegalStateException("Counter wrapped; nonce reused beyond 2^32 blocks");
            }
        }
        return out;
    }

    private static byte[] buildCounterBlock(byte[] nonce, int blockIndex) {
        byte[] block = new byte[BLOCK_BYTES];
        System.arraycopy(nonce, 0, block, 0, NONCE_BYTES);
        block[12] = (byte) (blockIndex >>> 24);
        block[13] = (byte) (blockIndex >>> 16);
        block[14] = (byte) (blockIndex >>> 8);
        block[15] = (byte) (blockIndex);
        return block;
    }

    public static void main(String[] args) throws Exception {
        byte[] key = new byte[16];
        new SecureRandom().nextBytes(key);

        byte[] nonce = new byte[NONCE_BYTES];
        new SecureRandom().nextBytes(nonce);

        String message = "Counter mode is parallel and needs no padding.";
        byte[] plaintext = message.getBytes("UTF-8");

        byte[] ciphertext = ctrEncrypt(key, nonce, plaintext);
        byte[] recovered = ctrEncrypt(key, nonce, ciphertext); // identical to encrypt

        System.out.println("Key        : " + Base64.getEncoder().encodeToString(key));
        System.out.println("Nonce      : " + Base64.getEncoder().encodeToString(nonce));
        System.out.println("Plaintext  : " + message);
        System.out.println("Ciphertext : " + Base64.getEncoder().encodeToString(ciphertext));
        System.out.println("Recovered  : " + new String(recovered, "UTF-8"));
        System.out.println("Round trip ok: " + Arrays.equals(plaintext, recovered));

        // Cross-check against the JDK AES/CTR/NoPadding provider.
        Cipher jdk = Cipher.getInstance("AES/CTR/NoPadding");
        // The JDK accepts a 16-byte IV that is nonce(12) || counter(4).
        byte[] iv = new byte[BLOCK_BYTES];
        System.arraycopy(nonce, 0, iv, 0, NONCE_BYTES);
        iv[15] = 1; // starting block index 1
        jdk.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
        byte[] jdkCiphertext = jdk.doFinal(plaintext);
        System.out.println("JDK match  : " + Arrays.equals(ciphertext, jdkCiphertext));
    }
}

Code Explanation Line by Line

The class CtrModeDemo declares three constants: BLOCK_BYTES is the 16-byte AES block, NONCE_BYTES is the 12-byte nonce, and COUNTER_BYTES is the 4-byte trailing counter field. The ctrEncrypt method takes a key, a nonce, and a plaintext and returns the ciphertext. It first obtains an AES cipher in ECB mode with no padding. ECB here is purely a primitive: we feed it a single 16-byte block at a time and the cipher returns a single 16-byte keystream block. We never use ECB to encrypt the actual message.

The loop walks the plaintext in 16-byte strides. For each block we call buildCounterBlock, which concatenates the nonce with the 32-bit big-endian block index. The block index starts at 1 and increments. The keystream is AES(counterBlock). The chunk size is the smaller of 16 or the remaining plaintext length, so the last block can be a partial block without padding.

After XORing the keystream with the plaintext chunk we move the offset forward and increment the block index. The line if (blockIndex == 0) detects 32-bit wraparound, which would happen after 2 to the power 32 blocks. When that happens we throw IllegalStateException because reusing the keystream would reveal the XOR of two plaintexts.

The main method shows the round trip: the same function encrypts and decrypts, which is the textbook signature of a stream cipher. The cross-check against the JDK AES/CTR/NoPadding provider verifies that our manual implementation produces byte-identical output. The JDK takes a 16-byte IV that we build by concatenating the 12-byte nonce with the 4-byte starting counter; setting iv[15] = 1 sets the low byte of the starting block index to 1, matching our convention.

Sample Input and Output

Key        : p1q...your-base64-key-here...
Nonce      : r2s...your-base64-nonce-here...
Plaintext  : Counter mode is parallel and needs no padding.
Ciphertext : 8Hk2vKq...your-base64-ciphertext-here...
Recovered  : Counter mode is parallel and needs no padding.
Round trip ok: true
JDK match  : true

The round trip succeeds because CTR mode is symmetric. The JDK match line confirms that the manual implementation is byte-identical to the JDK provider, which validates the algorithm.

Common Mistakes to Avoid

The first mistake is nonce reuse. If two messages are encrypted with the same key and the same nonce, the first keystream block is identical for both messages. XORing the two ciphertexts cancels the keystream and yields the XOR of the two plaintexts, which is enough to recover both. The fix is to generate a fresh nonce for every encryption, either from a monotonic counter or from SecureRandom.

The second mistake is letting the counter wrap. After 2 to the power 32 blocks (64 GiB for AES-128) the counter returns to zero and the keystream repeats. Long-lived sessions such as disk encryption need to either rotate the key before the wrap or use a wider counter.

The third mistake is using CTR mode alone for authentication. CTR mode provides confidentiality but no integrity. An attacker can flip a bit in the ciphertext and the corresponding plaintext bit flips. Always pair CTR with a MAC; the standard authenticated constructions AES-GCM, AES-GCM-SIV, and ChaCha20-Poly1305 all use a counter underneath.

The fourth mistake is to assume the JDK IV is the same as the nonce. The JDK AES/CTR/NoPadding cipher takes a 16-byte IV that combines the nonce and the starting counter. A common bug is to pass only a 12-byte nonce, which the JDK rejects, or to pass a 16-byte IV that has a non-zero counter field when the caller expected a pure nonce.

Real-World Applications

Counter mode is the foundation of the most widely deployed authenticated cipher on the internet, AES-GCM, defined in NIST SP 800-38D and RFC 5288. The TLS 1.3 record layer uses AES-GCM with a 96-bit salt and a 64-bit sequence number packed into the counter field, which is exactly the layout described in this tutorial. SSH uses aes128-ctr and aes256-ctr as the symmetric cipher for terminal sessions, and IPSec ESP can be configured with aes-ctr.

Disk encryption tools such as Linux dm-crypt, Apple FileVault, Microsoft BitLocker, and LUKS2 use AES-CTR as the underlying primitive. BitLocker uses the AES-XTS construction, which is a tweakable block cipher that composes two AES keys but underneath still operates in a counter-like fashion per sector.

Random number generators such as NIST SP 800-90A AES-CTR-DRBG use the same construction to turn a seed into an arbitrary-length keystream. Java's SecureRandom implementations on some platforms historically used SHA1PRNG, but the FIPS-compliant variants prefer AES-CTR-DRBG because it is fast and well-analyzed.

At the protocol level, the Signal messaging app uses AES-CTR for the message body in the AES256-CBC-HMAC-SHA256 cipher suite (a leftover of the early Axolotl design that predated the wide deployment of AES-GCM). Modern Signal also offers the ChaCha20-Poly1305 suite, which itself is built on a counter-style stream generator. In each case the ctr mode java pattern shown here is the conceptual core.

Conclusion

In this ctr counter mode java tutorial we built a complete manual Counter mode implementation, showed it is byte-identical to the JDK provider, and explained why CTR is the workhorse of modern authenticated encryption. The ctr counter mode java example demonstrates that Counter mode is parallel, padding-free, and turns any block cipher into a stream cipher with a single primitive call per block. The ctr counter mode java pattern is the conceptual core of AES-GCM, ChaCha20-Poly1305, and the AES-CTR-HMAC construction. The two things to remember are never to reuse a nonce under the same key and never to ship CTR without a MAC. Next, study AES-GCM (which adds GHASH authentication on top of CTR), ChaCha20 (a dedicated counter-style stream cipher), and AES-XTS (the disk-encryption variant).

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