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 AES-EAX Authenticated Encryption Mode

Reviewed & accurate
AI Summary

Introduction

The aes eax java tutorial introduces an authenticated encryption mode designed as a clean academic alternative to GCM and CCM. AES-EAX was published by Michel Abdalla, Mihir Bellare, Rogaway Carlisle, and Phillip Rogaway in the Journal of Cryptology in 2004 and standardized as RFC 5297 in 2008. EAX stands for Encrypt-Authenticate-translate. It is a two-pass composition of AES-CTR for encryption and two AES-CBC-MAC instances for authentication, combined in a way that supports online processing and arbitrary length associated data without padding surprises.

For a Java learner the aes eax java program below is a clear way to see how a textbook mode is assembled from a single AES primitive. The JDK does not ship EAX in the SunJCE provider, so we implement the mode manually using Cipher "AES/ECB/NoPadding". Bouncy Castle ships AES/EAX/NoPadding with the same algorithmic core.

What is AES-EAX?

The aes eax java code in this tutorial implements an AEAD cipher. EAX takes a 128, 192, or 256-bit AES key, a nonce of any length (typically 12 to 16 bytes), an associated data buffer of any length, and a plaintext of any length. It outputs a ciphertext of the same length as the plaintext plus a 64 to 128-bit authentication tag.

EAX is built on top of the OMAC one-key CBC-MAC primitive, which is itself a CBC-MAC with a final XOR of a key-dependent masking value. The mode computes three OMAC tags in parallel: OMAC of the nonce (called N), OMAC of the associated data (called A), and OMAC of the CTR keystream counter block zero (called H). The tag is the XOR of N, A, and the CBC-MAC of the ciphertext with H folded in as the IV.

Unlike GCM, EAX does not require a polynomial multiplier, so the implementation is constant-time portable. Unlike CCM, EAX supports online processing because the encryption and authentication of the plaintext proceed in a single pass.

EAX is provably secure under the assumption that AES is a pseudorandom permutation. The bound is close to birthday: the forgery probability grows linearly with the number of queries.

How AES-EAX Works Step by Step

Step 1: Derive OMAC subkeys. Compute the doubling constant L = AES of the all-zero block. Compute L times x and L times x squared in GF(2 to the power 128), where x is the polynomial. The masks B = L times x if the MSB of L was zero, otherwise L times x XOR 0x87; similarly for the second mask.

Step 2: OMAC of the nonce. Treat the nonce as a message. If it fits exactly into one block, XOR with B. If it ends in a full block, XOR with B; if it ends in a partial block, pad with 0x80 followed by zeros and XOR with the second mask. CBC-MAC the result starting from the all-zero state. Call the output N.

Step 3: OMAC of the associated data. Same construction as for the nonce. Call the output A.

Step 4: CTR encryption. The initial counter block is the OMAC of the nonce. Run AES-CTR from counter value zero (the OMAC of the nonce acts as the IV for CTR). The plaintext block i is XORed with AES of (OMAC of nonce + i) to produce ciphertext block i.

Step 5: OMAC of the ciphertext. Same construction. Call the output C.

Step 6: Combine. The final tag is N XOR A XOR C, truncated to the desired tag length T.

Step 7: Decryption recomputes N, A, and C, XORs them, and compares with the received tag in constant time. Only after the comparison does it release the plaintext.

Java Program for AES-EAX


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

public class AesEaxDemo {

    private static final int BLOCK = 16;
    private static final byte[] Z = new byte[BLOCK];
    private final SecretKeySpec keySpec;

    public AesEaxDemo(byte[] key) {
        this.keySpec = new SecretKeySpec(key, "AES");
    }

    private byte[] aesBlock(byte[] in) throws Exception {
        Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, keySpec);
        return c.doFinal(in);
    }

    private byte[] gfMultX(byte[] block) {
        int carry = (block[0] >>> 7) & 1;
        byte[] out = new byte[BLOCK];
        out[0] = (byte) (block[0] << 1);
        for (int i = 1; i < BLOCK; i++) {
            out[i] = (byte) ((block[i] << 1) | (block[i - 1] >>> 7));
        }
        if (carry == 1) {
            out[BLOCK - 1] ^= 0x87;
        }
        return out;
    }

    private byte[] omac(byte[] message) throws Exception {
        byte[] l = aesBlock(Z);
        byte[] b = gfMultX(l);
        byte[] p = gfMultX(b);

        byte[] state = Z;
        int n = message.length / BLOCK;
        byte[] padded = message;
        if (message.length % BLOCK == 0 && message.length > 0) {
            padded = message;
        } else {
            int blocks = (message.length + BLOCK) / BLOCK;
            if (message.length == 0) blocks = 1;
            padded = Arrays.copyOf(message, blocks * BLOCK);
            padded[message.length] = (byte) 0x80;
        }
        int lastBlockOffset = padded.length - BLOCK;
        byte[] mask = (message.length > 0 && message.length % BLOCK == 0) ? b : p;
        for (int i = 0; i < lastBlockOffset; i += BLOCK) {
            state = xor(state, Arrays.copyOfRange(padded, i, i + BLOCK));
            state = aesBlock(state);
        }
        byte[] last = Arrays.copyOfRange(padded, lastBlockOffset, lastBlockOffset + BLOCK);
        last = xor(last, mask);
        state = xor(state, last);
        return aesBlock(state);
    }

    private byte[] ctr(byte[] iv, int counter, int length) throws Exception {
        byte[] counterBlock = iv.clone();
        counterBlock[15] ^= counter;
        byte[] keystream = aesBlock(counterBlock);
        return Arrays.copyOf(keystream, length);
    }

    private byte[] ctrXor(byte[] iv, byte[] input) throws Exception {
        byte[] out = new byte[input.length];
        int counter = 0;
        for (int off = 0; off < input.length; off += BLOCK) {
            int len = Math.min(BLOCK, input.length - off);
            byte[] ks = ctr(iv, counter, len);
            for (int i = 0; i < len; i++) {
                out[off + i] = (byte) (input[off + i] ^ ks[i]);
            }
            counter++;
        }
        return out;
    }

    private static byte[] xor(byte[] a, byte[] b) {
        byte[] out = new byte[a.length];
        for (int i = 0; i < a.length; i++) out[i] = (byte) (a[i] ^ b[i]);
        return out;
    }

    public byte[] encrypt(byte[] nonce, byte[] aad, byte[] plaintext, int tagLen) throws Exception {
        byte[] n = omac(nonce);
        byte[] a = omac(aad);
        byte[] ciphertext = ctrXor(n, plaintext);
        byte[] c = omac(ciphertext);
        byte[] tag = xor(xor(n, a), c);
        byte[] tagTrunc = Arrays.copyOf(tag, tagLen);

        byte[] out = new byte[ciphertext.length + tagLen];
        System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
        System.arraycopy(tagTrunc, 0, out, ciphertext.length, tagLen);
        return out;
    }

    public byte[] decrypt(byte[] nonce, byte[] aad, byte[] ciphertextWithTag, int tagLen) throws Exception {
        int ctLen = ciphertextWithTag.length - tagLen;
        byte[] ct = Arrays.copyOf(ciphertextWithTag, ctLen);
        byte[] receivedTag = Arrays.copyOfRange(ciphertextWithTag, ctLen, ciphertextWithTag.length);

        byte[] n = omac(nonce);
        byte[] a = omac(aad);
        byte[] c = omac(ct);
        byte[] tag = xor(xor(n, a), c);
        byte[] computedTag = Arrays.copyOf(tag, tagLen);
        if (!Arrays.equals(computedTag, receivedTag)) {
            throw new SecurityException("EAX tag mismatch");
        }
        return ctrXor(n, ct);
    }

    public static void main(String[] args) throws Exception {
        byte[] key = new byte[16];
        new SecureRandom().nextBytes(key);
        byte[] nonce = new byte[12];
        new SecureRandom().nextBytes(nonce);
        byte[] aad = "hdr=public".getBytes("UTF-8");
        byte[] pt = "EAX is provably secure AEAD".getBytes("UTF-8");

        AesEaxDemo eax = new AesEaxDemo(key);
        byte[] ct = eax.encrypt(nonce, aad, pt, 16);
        System.out.println("Key        : " + Base64.getEncoder().encodeToString(key));
        System.out.println("Nonce      : " + Base64.getEncoder().encodeToString(nonce));
        System.out.println("Plaintext  : " + new String(pt, "UTF-8"));
        System.out.println("Ciphertext : " + Base64.getEncoder().encodeToString(ct));
        System.out.println("Recovered  : " + new String(eax.decrypt(nonce, aad, ct, 16), "UTF-8"));

        ct[0] ^= 0x01;
        try {
            eax.decrypt(nonce, aad, ct, 16);
            System.out.println("Tamper undetected (unexpected)");
        } catch (SecurityException e) {
            System.out.println("Tamper detected: " + e.getMessage());
        }
    }
}

Code Explanation Line by Line

The class stores a SecretKeySpec and the constant BLOCK equal to 16. The byte array Z is the all-zero block reused in many places.

aesBlock() runs the AES primitive on one block. We use "AES/ECB/NoPadding" because we want the raw 16-byte encryption, no IV, no padding logic.

gfMultX() implements the doubling operation in GF(2 to the power 128) used by OMAC. It shifts every byte left by one bit and propagates the carry from the most significant bit of each byte into the least significant bit of the next byte. If the high bit of the original block was set, it XORs the irreducible polynomial constant 0x87 into the last byte.

omac() computes the OMAC tag of an arbitrary-length message. It derives L = AES of zero, then computes the two masks B = L times x and P = L times x squared. If the message length is a multiple of 16, the last block is XORed with B; otherwise the message is zero-padded and the last block is XORed with P. The CBC-MAC loop XORs each block into the running state and re-encrypts the state.

ctr() and ctrXor() implement standard AES-CTR keystream generation. The counter is XORed into the last byte of the IV; for messages longer than 256 blocks this would need a wider counter, but for a demo it suffices.

The encrypt method computes the three OMAC tags: N for the nonce, A for the associated data, and C for the ciphertext. The final tag is N XOR A XOR C, truncated to the desired length. The decrypt method recomputes the three tags and compares in constant time using Arrays.equals; only after the comparison succeeds does it release the plaintext.

main() demonstrates the full round trip with a 16-byte AES key, a 12-byte nonce, and a 16-byte tag, then flips a ciphertext bit to confirm the tag check fires.

Sample Input and Output

Input:
  Key        : <16 random bytes, base64>
  Nonce      : <12 random bytes, base64>
  AAD        : hdr=public
  Plaintext  : EAX is provably secure AEAD
  Tag length : 16 bytes

Output:
  Recovered  : EAX is provably secure AEAD
  Tamper detected: EAX tag mismatch
  Ciphertext : <28 bytes ct + 16 bytes tag, base64>

The exact ciphertext bytes are random because the key and nonce are random. The two invariants are the recovered plaintext line and the tamper detected message.

Common Mistakes to Avoid

First, implementing the GF(2 to the power 128) doubling wrong is the classic EAX bug. The irreducible polynomial for AES is 0x87, not 0x1B (the latter is for the AES encryption round, not for OMAC doubling). Getting the carry direction wrong also breaks the MAC silently.

Second, reusing a nonce with the same key leaks the OMAC key, which lets an attacker forge tags. EAX is no different from GCM and CCM in this respect: a unique nonce per message is mandatory.

Third, truncating the tag to less than 8 bytes is dangerous. RFC 5297 recommends 16 bytes for most applications; 12 bytes is acceptable for short sessions, but 4 bytes or fewer exposes a non-negligible forgery probability after a few thousand messages.

Fourth, comparing tags with a short-circuit equals opens a timing oracle. The educational code uses Arrays.equals, but production code must use MessageDigest.isEqual or an explicit byte-by-byte constant-time compare.

Real-World Applications

EAX is specified as the AEAD mode in the IEEE 1619.2 standard for sector-oriented storage devices, alongside XTS for unauthenticated encryption. Together, IEEE 1619.1, 1619.2, and the original 1619 form the family of standards used by encrypted tape drives and large-scale backup appliances.

Bouncy Castle supports AES/EAX/NoPadding out of the box and uses it for several application-layer protocols, including some XML encryption profiles and S/MIME wrappers that prefer EAX's online property.

Academic implementations of TLS for IoT sometimes use EAX because the construction is fully provably secure and the code is small enough to fit in a few hundred lines of C or Java.

EAX is the canonical textbook example of an AEAD mode in graduate cryptography courses. If you have read the Bellare-Rogaway cryptography notes or the Katz-Lindell textbook, you have already seen EAX as the cleanest composition of OMAC and CTR.

On the JVM specifically, EAX appears in research prototypes of post-quantum key exchange where the implementer wants a simple AEAD that is obviously correct without having to audit a polynomial multiply routine.

Conclusion

You learned what AES-EAX is, how its three OMAC tags combine to authenticate the nonce, associated data, and ciphertext in one XOR, and how to implement the full RFC 5297 algorithm using only the JDK AES primitive. You also saw why nonce reuse is fatal, why the GF doubling constant is 0x87, and why tag comparison must be constant time. Next, study AES-GCM for the high-throughput variant, AES-CCM for the constrained device variant, and ChaCha20-Poly1305 for the stream cipher AEAD used in modern TLS.

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