Skip to main content
Cipher Visualizers home

The Square Attack: Breaking AES Reduced to Four Rounds

Full AES has no practical break, but reduced-round AES does. The Square attack feeds 256 chosen plaintexts through 4-round AES, uses a balance property that survives three rounds, and peels off the last round key one byte at a time, then runs the key schedule backwards to the master key.

Pashalis Laoutaris 16 min read

Try it

Interactive AES Square Attack (4 Rounds)

🔐 AES Square Attack (4 Rounds)

Real AES-128 arithmetic, stopped after 4 rounds. The attacker chooses plaintexts and reads ciphertexts, and recovers the key without ever seeing it.
Enter text and click a button to start!
1. A Λ-set: one active byte, fifteen fixed
2. The balance vanishes in round 4
3. Guess the last round key, one byte at a time
4. Run the key schedule backwards to the master key
Click the button to recover an AES key from 4-round ciphertexts.

The Square Attack: Breaking AES Reduced to Four Rounds

Introduction

Full AES has no practical attack. After decades of study, the best known attacks on all ten rounds are barely faster than trying every key. That is why AES is the workhorse of modern cryptography. The story is different when AES is cut to fewer rounds. Reduced-round AES is a standard way to study how the cipher resists attacks, and the Square attack is the classic example.

The Square attack predates AES itself. Joan Daemen, Lars Knudsen, and Vincent Rijmen published it in 1997 against the cipher Square, the direct ancestor of Rijndael, which became AES. It is a chosen-plaintext attack. The attacker encrypts a carefully built set of 256 plaintexts, watches a structural property survive three rounds and break in the fourth, and uses that to recover the last round key. From there the full key falls out. This guide builds the attack against 4-round AES and recovers the key.

Table of Contents

The Λ-Set and the Balance Property

The attack works with a special set of 256 plaintexts, called a Λ-set (lambda-set). In it, one byte position takes every value from 00 to ff, exactly once each, while the other fifteen bytes hold the same constant across all 256 texts. The varying byte is called active; the fixed ones are passive.

The key idea is a property called balance. A byte position is balanced over a set of states when the XOR of that byte across all the states is zero. The active byte of a Λ-set is balanced, because XORing 00 through ff gives zero. A passive byte is also balanced, because the same constant XORed 256 times cancels. So a Λ-set starts out balanced in every byte.

The Square attack tracks what happens to balance as the texts pass through AES. It holds through round three and breaks in round four, and that gap is the whole attack.

Why the Balance Survives Three Rounds

Walk the active byte through AES. AddRoundKey XORs a constant, which keeps a byte active or passive. SubBytes is a bijection, so the active byte still runs through all 256 values, still active. ShiftRows just moves bytes around. MixColumns mixes the four bytes of a column, so one active byte in a column makes all four bytes of that column active.

Follow it round by round:

  • Round 1. The single active byte spreads, through MixColumns, to a full column of four active bytes.
  • Round 2. ShiftRows scatters those four active bytes into four different columns, then MixColumns makes every one of the sixteen bytes active.
  • Round 3. Here the active bytes stop being simple. After the round-3 MixColumns, the bytes are no longer each active, but they are still balanced: the XOR of each byte over the 256 texts is zero. This follows because MixColumns outputs are fixed linear combinations of inputs that are each balanced, and a sum of balanced bytes is balanced. AddRoundKey then XORs a constant 256 times, which cancels, so balance survives.

So the state entering round four is balanced in all sixteen bytes. Then round four applies SubBytes, which is non-linear, and that destroys the balance. The ciphertext is almost never balanced. The attacker sees the broken balance in the ciphertext and works backwards to find where it was still intact.

Peeling Off the Last Round

The final AES round is SubBytes, then ShiftRows, then AddRoundKey, with no MixColumns. To undo it for a single ciphertext byte, the attacker guesses one byte of the last round key and computes:

state_byte = InvSubBytes( ciphertext_byte xor key_guess )

That state_byte is one byte of the balanced state, just before round four’s SubBytes. If the guess is right, this byte is balanced across the 256 ciphertexts, so its XOR-sum is zero. If the guess is wrong, the InvSubBytes scrambles the values, and the sum is zero only by chance, about one time in 256.

So the attacker tries all 256 guesses for one key byte and keeps those whose sum is zero. The correct byte always survives; a handful of wrong ones survive too. Because balance holds for every byte of the round-3 state, the attacker can do this independently for all sixteen key-byte positions. One Λ-set usually narrows each position to a few candidates. A second Λ-set, with a different constant, removes the rest. In testing, two Λ-sets pinned every byte for most keys, and three were always enough.

From the Round Key to the Master Key

The attack recovers the round-4 key, not the master key. But the AES key schedule is fully reversible. Each word of a round key is built from earlier words by XOR, a byte rotation, the S-box, and a round constant, all of which can be undone. Starting from the four words of the round-4 key, the attacker runs the schedule backwards, round by round, until it reaches the original key. That key is the master AES key.

Interactive Visualizer

The visualizer above runs the whole attack in your browser. Enter any 16-byte key, or keep the default, which is the example key from the AES specification. The attacker never sees that key; it drives a real AES-128 stopped after four rounds.

The four cards show the Λ-set with its one active byte, the balance that is gone from the ciphertext, the last round key recovered byte by byte, and the key schedule run backwards to the master key. The recovered round-4 key and master key are checked against the real ones. The same arithmetic runs in the Python below, and the two agree byte for byte.

A Worked Example

The key is the one from the AES specification, 2b7e151628aed2a6abf7158809cf4f3c. The attacker does not know it. It builds a Λ-set with byte 0 active and the other bytes set to a fixed pattern, encrypts all 256 texts through 4-round AES, and looks at the ciphertexts.

Balance is gone. XOR each ciphertext byte over the 256 texts. The result is 2ca5f3f2c2d611be14932193f0e178be, nowhere near zero. Round four hid the balance.

Recovering the round-4 key. For each key-byte position, the attacker keeps the guesses that restore balance. One Λ-set leaves this many candidates per byte:

[3, 4, 2, 1, 1, 5, 5, 2, 2, 1, 2, 1, 1, 1, 3, 2]

A second Λ-set, with a different constant, narrows every byte to exactly one:

round-4 key: ef44a541a8525b7fb671253bdb0bad00

The master key. Running the key schedule backwards from that round-4 key gives 2b7e151628aed2a6abf7158809cf4f3c, the original key. The attacker recovered it from 512 chosen plaintexts, without ever seeing it.

Python Implementation

This is real AES-128 arithmetic, stopped after four rounds, followed by the attack: the Λ-set, the balance check, the per-byte key recovery, and the backward key schedule.

# square_attack.py
#
# The Square attack (Daemen, Knudsen, Rijmen, 1997) on AES reduced to 4 rounds. It recovers the last
# round key from chosen plaintexts, with no knowledge of the key, then runs the key schedule backwards
# to the master key. The attack does NOT reach full 10-round AES; it is a lesson in how structure leaks.
# The block cipher here is real AES-128 arithmetic, stopped after four rounds. Teaching code.

SBOX = [
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16,
]
INV_SBOX = [0] * 256
for _i, _v in enumerate(SBOX):
    INV_SBOX[_v] = _i
RCON = [0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36]


def xtime(a):
    a <<= 1
    return (a ^ 0x11b) & 0xff if a & 0x100 else a


def gmul(a, b):
    p = 0
    for _ in range(8):
        if b & 1:
            p ^= a
        a = xtime(a)
        b >>= 1
    return p


def key_expansion(key):
    """The 44 words of the AES-128 key schedule, each a 4-byte list."""
    w = [list(key[4 * i:4 * i + 4]) for i in range(4)]
    for i in range(4, 44):
        t = list(w[i - 1])
        if i % 4 == 0:
            t = t[1:] + t[:1]
            t = [SBOX[b] for b in t]
            t[0] ^= RCON[i // 4 - 1]
        w.append([w[i - 4][j] ^ t[j] for j in range(4)])
    return w


def round_key_bytes(w, r):
    """Round key r as 16 bytes in column-major (state) order."""
    return bytes(w[r * 4 + c][row] for c in range(4) for row in range(4))


def add_round_key(state, rk):
    return bytes(s ^ k for s, k in zip(state, rk))


def sub_bytes(state):
    return bytes(SBOX[b] for b in state)


def shift_rows(state):
    return bytes(state[((c + r) % 4) * 4 + r] for c in range(4) for r in range(4))


def mix_columns(state):
    out = bytearray(16)
    for c in range(4):
        a = state[c * 4:c * 4 + 4]
        out[c*4+0] = gmul(a[0],2) ^ gmul(a[1],3) ^ a[2] ^ a[3]
        out[c*4+1] = a[0] ^ gmul(a[1],2) ^ gmul(a[2],3) ^ a[3]
        out[c*4+2] = a[0] ^ a[1] ^ gmul(a[2],2) ^ gmul(a[3],3)
        out[c*4+3] = gmul(a[0],3) ^ a[1] ^ a[2] ^ gmul(a[3],2)
    return bytes(out)


def encrypt_4round(block, w):
    """AES-128 stopped after four rounds. The final round has no MixColumns, like the real last round."""
    state = add_round_key(block, round_key_bytes(w, 0))
    for r in (1, 2, 3):
        state = mix_columns(shift_rows(sub_bytes(state)))
        state = add_round_key(state, round_key_bytes(w, r))
    state = add_round_key(shift_rows(sub_bytes(state)), round_key_bytes(w, 4))   # round 4, no MixColumns
    return state


def lambda_set(active_pos, const_block):
    """256 plaintexts: the active byte runs through all values, the other 15 bytes stay constant."""
    out = []
    for v in range(256):
        b = bytearray(const_block)
        b[active_pos] = v
        out.append(bytes(b))
    return out


def candidate_key_bytes(ciphertexts, pos):
    """Guesses for byte `pos` of the round-4 key that leave that byte of the round-3 state balanced.

    The state after round 3 is balanced: for every byte, the XOR over the 256 texts is zero. The final
    round is SubBytes, ShiftRows, AddRoundKey, so inverting one ciphertext byte is InvSBOX(c xor guess).
    Balance holds for whichever round-3 byte that is, so the correct guess makes the XOR-sum zero.
    """
    out = []
    for guess in range(256):
        acc = 0
        for c in ciphertexts:
            acc ^= INV_SBOX[c[pos] ^ guess]
        if acc == 0:
            out.append(guess)
    return out


def recover_round4_key(sets):
    """Each entry of `sets` is the 256 ciphertexts of one lambda-set. Intersect candidates per byte."""
    key = []
    for pos in range(16):
        cand = None
        for ciphertexts in sets:
            c = set(candidate_key_bytes(ciphertexts, pos))
            cand = c if cand is None else (cand & c)
        key.append(cand)
    return key


def invert_key_schedule(rk4_bytes):
    """From the round-4 key (16 bytes, column-major) run the schedule backwards to the master key."""
    # words 16..19 of the schedule, as 4-byte lists
    w = {}
    for c in range(4):
        w[16 + c] = [rk4_bytes[c * 4 + row] for row in range(4)]
    for i in range(19, 3, -1):
        if i % 4 == 0:
            t = list(w[i - 1])
            t = t[1:] + t[:1]
            t = [SBOX[b] for b in t]
            t[0] ^= RCON[i // 4 - 1]
        else:
            t = list(w[i - 1])
        w[i - 4] = [w[i][j] ^ t[j] for j in range(4)]
    return bytes(w[0][j] for j in range(4)) + bytes(w[1][j] for j in range(4)) + \
           bytes(w[2][j] for j in range(4)) + bytes(w[3][j] for j in range(4))


if __name__ == "__main__":
    import os
    import random

    KEY = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c")   # the FIPS-197 example key, held by the victim
    w = key_expansion(KEY)

    # one lambda-set: the first byte active, the rest fixed to a nothing-up-my-sleeve constant
    const = bytes(range(16))
    pts = lambda_set(0, const)
    cts = [encrypt_4round(p, w) for p in pts]

    print("Lambda-set: byte 0 takes all 256 values, the other 15 bytes are fixed.")
    print("After 4-round encryption, the sum (XOR) of each ciphertext byte is NOT zero:")
    col_sum = [0] * 16
    for c in cts:
        for i in range(16):
            col_sum[i] ^= c[i]
    print("  ciphertext byte sums:", bytes(col_sum).hex())

    cand = [candidate_key_bytes(cts, pos) for pos in range(16)]
    print("\nWith one lambda-set, surviving round-4 key guesses per byte:")
    print("  counts:", [len(c) for c in cand])

    # a second lambda-set (different constant) removes the extra survivors
    const2 = bytes((x + 123) & 0xff for x in range(16))
    cts2 = [encrypt_4round(p, w) for p in lambda_set(0, const2)]
    rk4 = recover_round4_key([cts, cts2])
    print("\nWith a second lambda-set, surviving guesses per byte:", [len(c) for c in rk4])
    rk4_bytes = bytes(sorted(c)[0] for c in rk4)
    print("recovered round-4 key:", rk4_bytes.hex())
    print("true round-4 key:     ", round_key_bytes(w, 4).hex())
    print("round-4 key match:    ", rk4_bytes == round_key_bytes(w, 4))

    master = invert_key_schedule(rk4_bytes)
    print("\nrecovered master key:", master.hex())
    print("true master key:     ", KEY.hex())
    print("MASTER KEY match:    ", master == KEY)

Running it prints this:

Lambda-set: byte 0 takes all 256 values, the other 15 bytes are fixed.
After 4-round encryption, the sum (XOR) of each ciphertext byte is NOT zero:
  ciphertext byte sums: 2ca5f3f2c2d611be14932193f0e178be

With one lambda-set, surviving round-4 key guesses per byte:
  counts: [3, 4, 2, 1, 1, 5, 5, 2, 2, 1, 2, 1, 1, 1, 3, 2]

With a second lambda-set, surviving guesses per byte: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
recovered round-4 key: ef44a541a8525b7fb671253bdb0bad00
true round-4 key:      ef44a541a8525b7fb671253bdb0bad00
round-4 key match:     True

recovered master key: 2b7e151628aed2a6abf7158809cf4f3c
true master key:      2b7e151628aed2a6abf7158809cf4f3c
MASTER KEY match:     True

I checked the code in several ways. The AES core reproduces the full 10-round FIPS-197 test vector, ciphertext 69c4e0d86a7b0430d8cdb78070b4c55a from plaintext 00112233445566778899aabbccddeeff and key 000102030405060708090a0b0c0d0e0f. The balance property was confirmed directly: the state after round three XORs to all zeros over a Λ-set. The attack was run on 200 random keys, and every one recovered the exact master key, using 2.07 Λ-sets on average and never more than 3. The JavaScript in the visualizer matches the Python on 150 shared cases, for the ciphertexts, the candidate lists, the round-4 key, and the key schedule inversion.

Limitations

Four rounds, not ten. This is the whole point to keep in view. The attack breaks 4-round AES. Full AES-128 has ten rounds, and this method does not reach it. Extending the balance idea costs dearly: Ferguson and others pushed a refined “partial-sum” version to 6 rounds, and the best integral-style attacks reach 7 rounds of AES-128, still far from 10 and still far from practical. The four-round attack is a teaching tool and a design check, not a threat to AES.

Chosen plaintexts. The attacker must choose the plaintexts, not just observe traffic. Each Λ-set is 256 chosen plaintexts, and the attack needs a few sets. This is a strong requirement that real protocols usually deny.

The last round has no MixColumns. The attack peels the final round precisely because AES omits MixColumns there, which lets each key byte be guessed on its own. A final round with MixColumns would mix the key bytes together and need a different step.

Teaching code. The implementation favors clarity. It guesses each key byte with a full scan of 256 values and recomputes sums directly, which is fast here but not optimized.

Security Status

AES is not broken. The Square attack is a reduced-round result, the standard way cryptographers measure a cipher’s margin of safety. AES-128 has ten rounds precisely so that attacks like this one, and their descendants, fall far short of the full cipher. The gap between the 7 rounds that integral attacks reach and the 10 rounds AES uses is the security margin, and it has held for over two decades.

The attack is worth studying because its central move recurs across modern cryptanalysis. Find a property that is preserved by the linear parts of a cipher and broken by the non-linear parts, track where the break happens, and use the boundary to recover key material. Integral cryptanalysis, the general framework Knudsen and Wagner built from the Square attack in 2002, applies this idea to many ciphers.

FAQ

Does this break real AES?

No, it does not. It breaks AES cut to four rounds. Real AES-128 uses ten rounds, and no practical attack reaches them. The four-round attack measures the cipher’s safety margin; it is not a way to read AES-protected data.

Why 256 plaintexts in a set?

A byte holds 256 values. A Λ-set runs one byte through all of them while the rest stay fixed, so the active byte is a complete permutation of 00 to ff. That completeness is what makes the XOR-sum cancel and the balance property hold.

Why does the attack target the last round key first?

The balance is intact just before the last round’s SubBytes. The attacker can only check it by undoing the last round, and undoing it needs the last round key. So the last round key is what the balance test reveals, and the key schedule then gives the rest.

Why guess each key byte separately?

The last AES round has no MixColumns, so each ciphertext byte depends on exactly one key byte and one state byte. That lets the attacker test one key byte at a time, 256 guesses each, instead of all sixteen at once, which would be astronomically more work.

How many chosen plaintexts does it take?

One Λ-set is 256. Most keys need two sets to pin every byte, and three are always enough in testing, so 512 to 768 chosen plaintexts. That is tiny compared with the 2^128 cost of trying every key, which is why four-round AES is considered broken.

References

  1. Daemen, Joan, Lars Knudsen, and Vincent Rijmen. “The Block Cipher Square.” Fast Software Encryption (FSE 1997), Lecture Notes in Computer Science 1267, Springer, 1997, pp. 149-165.

  2. Daemen, Joan, and Vincent Rijmen. The Design of Rijndael: AES, the Advanced Encryption Standard. Springer, 2002 (the Square attack on Rijndael is in the security chapter).

  3. Ferguson, Niels, John Kelsey, Stefan Lucks, Bruce Schneier, Mike Stay, David Wagner, and Doug Whiting. “Improved Cryptanalysis of Rijndael.” Fast Software Encryption (FSE 2000), Lecture Notes in Computer Science 1978, Springer, 2001, pp. 213-230.

  4. Knudsen, Lars, and David Wagner. “Integral Cryptanalysis.” Fast Software Encryption (FSE 2002), Lecture Notes in Computer Science 2365, Springer, 2002, pp. 112-127.

  5. NIST FIPS 197. “Advanced Encryption Standard (AES),” 2001.

  6. The AES guide on this site, whose round functions and key schedule this attack uses: /blog/aes_guide/

A visual representation of recovering an ECDH key from small-order points on invalid curves
Modern & Applied Cryptography Breakers Advanced

The Invalid-Curve Attack: Breaking ECDH by Sending Bad Points

ECDH point arithmetic never uses the curve's b parameter, so a server that skips the on-curve check will do math with points from other curves. This guide sends small-order points from invalid curves to a static-key ECDH server, leaks the key one small prime at a time, and reassembles it with the Chinese Remainder Theorem.

15 min read

A visual representation of a CBC ciphertext-block collision leaking a secret plaintext block
Modern & Applied Cryptography Breakers Advanced

Sweet32: Why 64-bit Block Ciphers Fall to the Birthday Bound

In CBC mode, two equal ciphertext blocks leak the XOR of their plaintexts, and for a 64-bit cipher like 3DES such a collision appears after about 2^32 blocks. This guide runs the Sweet32 attack on a reduced-block cipher so the collision actually happens, recovering a secret block from captured ciphertext.

13 min read

A visual representation of recovering a Merkle-Hellman private key from the public key with lattice reduction
Modern & Applied Cryptography Breakers Advanced

Breaking Merkle-Hellman: Recovering the Key from the Public Key

Shamir broke the basic Merkle-Hellman knapsack in 1982 without seeing a single ciphertext. This guide rebuilds his key-recovery attack with a small LLL lattice, finds a working private key for the guide's 32-bit key in milliseconds, and measures it on keys of up to 256 bits.

21 min read