Implementing AES-128 In Rust
Introduction
The Advanced Encryption Standard (AES) is a symmetric-key block cipher standard published by the US National Institute of Standards and Technology (NIST) in 2001. AES is based on the Rijndael cipher, but specifies a fixed block size of 128 bits and three permitted key lengths: 128, 192, and 256 bits. AES is widely used in contemporary information-security protocols and applications, including configurations of SSH and HTTPS.
AES-128 encryption
Project objective
This tutorial develops an implementation of AES-128 block encryption and decryption in Rust. AES-128 uses a 128-bit key and applies ten rounds of transformation to each 128-bit plaintext block.
Security warning: This implementation is intended for educational purposes. Do not use unaudited or untested cryptographic code in production. For practical applications, use a maintained, well-reviewed authenticated-encryption implementation such as AES-GCM.
Overview of AES encryption
AES encryption can be understood as a sequence of key-dependent transformations. For AES-128, the process consists of an initial key addition, nine main rounds, and a final round:
- Expand the cipher key to generate eleven 128-bit round keys.
- Apply the initial
AddRoundKeytransformation. - For each of the nine main rounds:
- Apply
SubBytes. - Apply
ShiftRows. - Apply
MixColumns. - Apply
AddRoundKey.
- Apply
- Apply the final round, which omits
MixColumns:- Apply
SubBytes. - Apply
ShiftRows. - Apply
AddRoundKey.
- Apply
This structure suggests the principal operations that the implementation must provide:
sub_bytes()shift_rows()mix_cols()add_round_key()generate_round_keys()
The following sections describe these transformations, their mathematical foundations, and their Rust implementations.
SubBytes
The AES S-box (substitution box) is a bijection from the set of bytes to itself,
It replaces each state byte with a corresponding output byte. The S-box is constructed using the multiplicative inverse in , together with an affine transformation over . This construction introduces non-linearity, an important property in the resistance of AES to linear and differential cryptanalysis.
The following constant is the AES S-box lookup table:
const SBOX: [u8; 256] = [
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, 0xc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xe1, 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
];
The sub_bytes function applies this substitution independently to each of the sixteen bytes in the state. The state is passed by mutable reference, so the substitutions are performed in place.
fn sub_bytes(state: &mut [u8;16]) {
for byte in state.iter_mut() {
*byte = SBOX[*byte as usize];
}
}
ShiftRows
AES represents its 128-bit state as a matrix of bytes. The ShiftRows transformation cyclically shifts row to the left by byte positions, where rows are indexed from zero. Thus, the first row is unchanged, the second is shifted by one position, the third by two positions, and the fourth by three positions.
Let the state space be . The transformation
acts as follows:
fn shift_rows(state: &mut [u8; 16]) {
let temp = *state;
state[0] = temp[0];
state[1] = temp[5];
state[2] = temp[10];
state[3] = temp[15];
state[4] = temp[4];
state[5] = temp[9];
state[6] = temp[14];
state[7] = temp[3];
state[8] = temp[8];
state[9] = temp[13];
state[10] = temp[2];
state[11] = temp[7];
state[12] = temp[12];
state[13] = temp[1];
state[14] = temp[6];
state[15] = temp[11];
}
This permutation redistributes bytes among the columns of the state. In conjunction with MixColumns, it contributes to diffusion: after successive rounds, the influence of an individual input byte spreads across the state.
The implementation below follows the column-major layout used by AES, in which the state bytes are stored column by column in the one-dimensional Rust array.
fn gal_mul(mut a: u8, mut b: u8) -> u8 {
let mut result = 0u8;
while b > 0 {
if b & 1 != 0 {
result ^= a;
}
let carry = a & 0x80;
a <<= 1;
if carry != 0 {
a ^= 0x1b;
}
b >>= 1;
}
result
}
Finite-field multiplication and MixColumns
MixColumns is a linear transformation over the finite field , applied independently to each column of the state. To understand its arithmetic, we first define this field and its operations.
The finite field
The field has exactly elements. Each element can be represented as an 8-bit byte or, equivalently, as a polynomial of degree at most seven with coefficients in .
- Addition is polynomial addition over , which is equivalent to bitwise XOR. We write this operation as .
- Multiplication is polynomial multiplication over , followed by reduction modulo the irreducible polynomial
- Binary-to-polynomial representation: a byte with bit representation corresponds to where each coefficient belongs to .
Example: multiplication in
Consider the product of the byte values 255 and 3 in . The arithmetic is performed on their polynomial representations, with reduction modulo .
-
Represent the operands as polynomials.
The byte 255 has all eight bits set, while the byte 3 has its two least significant bits set. Therefore,
-
Multiply the polynomials.
Writing the operands as and , respectively,
and hence
-
Collect like terms.
Coefficients are added modulo two, so equal terms cancel because in characteristic two. Consequently,
-
Reduce modulo the AES polynomial.
Since the result has degree eight, it must be reduced modulo
In the quotient field,
It follows that
-
Convert the result back to a byte.
The polynomial corresponds to the bit string
00011010, which is 26 in decimal. Thus,
Notation: In this field, polynomial addition and bitwise XOR are the same operation. The symbol is used in polynomial expressions, while makes the XOR interpretation explicit.
Rust implementation of field multiplication
The function below implements multiplication in using the shift-and-add method. The reduction constant 0x1b is the low-byte representation of the terms remaining after the leading term is removed from the AES modulus.
fn mix_cols(state: &mut [u8; 16]) {
let temp = *state;
for col in 0..4 {
let offset = col * 4;
let s = [
temp[offset],
temp[offset + 1],
temp[offset + 2],
temp[offset + 3],
];
state[offset] = gal_mul(s[0], 0x02) ^ gal_mul(s[1], 0x03) ^ s[2] ^ s[3];
state[offset + 1] = s[0] ^ gal_mul(s[1], 0x02) ^ gal_mul(s[2], 0x03) ^ s[3];
state[offset + 2] = s[0] ^ s[1] ^ gal_mul(s[2], 0x02) ^ gal_mul(s[3], 0x03);
state[offset + 3] = gal_mul(s[0], 0x03) ^ s[1] ^ s[2] ^ gal_mul(s[3], 0x02);
}
}
AddRoundKey
The AddRoundKey transformation combines the 128-bit state with a 128-bit round key by applying bitwise XOR to corresponding bytes. Equivalently, it performs addition in on each corresponding bit. Since XOR is its own inverse, the same operation is used during encryption and decryption.
fn add_round_key(state: &mut [u8; 16], key: &[u8; 16]) {
for (s, k) in state.iter_mut().zip(key.iter()) {
*s ^= k;
}
}
AES-128 key expansion
The AES-128 key schedule expands the original 128-bit cipher key into eleven round keys, each 128 bits long. These keys are used for the initial key addition and the ten encryption rounds.
Key expansion overview
- Initial key: The key consists of four 32-bit words, denoted .
- Round keys: Each round key consists of four consecutive 32-bit words. The original key forms the first round key.
- Total number of words: Eleven round keys require words, denoted .
Key expansion operations
The key schedule uses three operations:
-
SubWord: Apply the AES S-box independently to each byte of a 32-bit word:
-
RotWord: Cyclically rotate the four bytes of a word one position to the left:
-
Round constant: For round , define
where the exponentiation is computed in , and denotes the byte
0x02.
Generation of the round-key words
The first four words are copied directly from the original key. For each , the next word is computed by
Here, XOR is applied wordwise (byte by byte). The implementation below constructs each new 128-bit round key from the four words generated by this recurrence.
const RCON: [u8; 10] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];
fn generate_round_keys(key: &[u8; 16]) -> [[u8; 16]; 11] {
let mut round_keys = [[0u8; 16]; 11];
round_keys[0].copy_from_slice(key);
let mut temp = [0u8; 4];
for i in 1..11 {
temp.copy_from_slice(&round_keys[i - 1][12..16]);
temp.rotate_left(1);
for byte in &mut temp {
*byte = SBOX[*byte as usize];
}
temp[0] ^= RCON[i - 1];
for j in 0..4 {
round_keys[i][j] = round_keys[i - 1][j] ^ temp[j];
round_keys[i][j + 4] = round_keys[i - 1][j + 4] ^ round_keys[i][j];
round_keys[i][j + 8] = round_keys[i - 1][j + 8] ^ round_keys[i][j + 4];
round_keys[i][j + 12] = round_keys[i - 1][j + 12] ^ round_keys[i][j + 8];
}
}
round_keys
}
AES-128 block encryption
Encrypting a block
The encryption routine combines the transformations defined above. It first applies the initial round key, then performs nine full rounds, and finally performs the tenth round without MixColumns. This is the AES-128 encryption structure specified by NIST.
pub fn block_encrypt(state: &mut [u8; 16], key: &[u8; 16]) {
let round_keys = generate_round_keys(key);
add_round_key(state, &round_keys[0]);
for round in round_keys.iter().take(10).skip(1) {
sub_bytes(state);
shift_rows(state);
mix_cols(state);
add_round_key(state, round);
}
sub_bytes(state);
shift_rows(state);
add_round_key(state, &round_keys[10]);
}
AES-128 decryption
Decryption overview
Decryption reverses the sequence of transformations applied during encryption. It uses the inverse S-box, inverse row shift, and inverse column-mixing transformations. AddRoundKey does not require a separate inverse operation because XOR is an involution: applying the same round key twice restores the original state.
The required operations are:
add_round_key()inv_sub_bytes()inv_shift_rows()inv_mix_cols()
The next sections define these inverse transformations and explain why they recover the original state.
InvSubBytes
const INVSBOX: [u8; 256] = [
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
];
The inverse S-box is obtained by reversing the AES S-box permutation. If the forward S-box maps byte to byte , the inverse S-box maps back to . The table below is the inverse lookup table used by the implementation.
fn inv_sub_bytes(state: &mut [u8; 16]) {
for byte in state.iter_mut() {
*byte = INVSBOX[*byte as usize]
}
}
InvShiftRows
The inverse of ShiftRows cyclically shifts row to the right by byte positions. As before, row indices begin at zero, so the first row remains unchanged. The following matrix illustrates the inverse permutation:
fn inv_shift_rows(state: &mut [u8; 16]) {
let temp = *state;
state[0] = temp[0];
state[4] = temp[4];
state[8] = temp[8];
state[12] = temp[12];
state[1] = temp[13];
state[2] = temp[10];
state[3] = temp[7];
state[5] = temp[1];
state[6] = temp[14];
state[7] = temp[11];
state[9] = temp[5];
state[10] = temp[2];
state[11] = temp[15];
state[13] = temp[9];
state[14] = temp[6];
state[15] = temp[3];
}
InvMixColumns
InvMixColumns applies the inverse of the MixColumns linear transformation to each column. Its matrix is the inverse of the forward mixing matrix over . The inverse matrix has coefficients 0e, 0b, 0d, and 09 (hexadecimal); multiplication by these coefficients is carried out in the same finite field defined earlier.
The implementation below applies this inverse transformation independently to each column of the state.
fn inv_mix_cols(state: &mut [u8; 16]) {
let temp = *state;
for col in 0..4 {
let offset = col * 4;
let s = [
temp[offset],
temp[offset + 1],
temp[offset + 2],
temp[offset + 3],
];
state[offset] =
gal_mul(s[0], 0x0e) ^ gal_mul(s[1], 0x0b) ^ gal_mul(s[2], 0x0d) ^ gal_mul(s[3], 0x09);
state[offset + 1] =
gal_mul(s[0], 0x09) ^ gal_mul(s[1], 0x0e) ^ gal_mul(s[2], 0x0b) ^ gal_mul(s[3], 0x0d);
state[offset + 2] =
gal_mul(s[0], 0x0d) ^ gal_mul(s[1], 0x09) ^ gal_mul(s[2], 0x0e) ^ gal_mul(s[3], 0x0b);
state[offset + 3] =
gal_mul(s[0], 0x0b) ^ gal_mul(s[1], 0x0d) ^ gal_mul(s[2], 0x09) ^ gal_mul(s[3], 0x0e);
}
}
Decrypting a block
The decryption routine applies the inverse transformations in the order required to undo encryption. It first adds the final round key, then processes the remaining round keys in descending order. Each intermediate inverse round applies InvShiftRows, InvSubBytes, AddRoundKey, and InvMixColumns. The final inverse round omits InvMixColumns and uses the original cipher key.
The round-key array is indexed from zero, so the final encryption round key is round_keys[10] and the initial key is round_keys[0].
pub fn block_decrypt(state: &mut [u8; 16], key: &[u8; 16]) {
let round_keys = generate_round_keys(key);
add_round_key(state, &round_keys[10]);
for round in round_keys.iter().take(10).skip(1).rev() {
inv_shift_rows(state);
inv_sub_bytes(state);
add_round_key(state, round);
inv_mix_cols(state);
}
inv_shift_rows(state);
inv_sub_bytes(state);
add_round_key(state, &round_keys[0]);
}
Testing and conclusion
The implementation is now complete at the block-cipher level. The tests below check the individual transformations, verify that selected operations are inverses of one another, and compare the encryption and decryption routines against a known AES-128 test vector published in NIST’s FIPS 197 specification.
Passing these tests provides useful evidence that the implementation follows the expected AES-128 transformations for the tested inputs. It is not, by itself, a substitute for comprehensive validation, independent review, side-channel analysis, or use of a vetted cryptographic library. In particular, this code implements single-block AES operations; a complete application must also use an appropriate mode of operation and, in most cases, authenticated encryption.
#[cfg(test)]
mod tests {
use hex_lit::hex;
use super::*;
#[test]
fn test_shift_rows() {
let mut state = [
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15,
];
let expected = [
0, 5, 10, 15,
4, 9, 14, 3,
8, 13, 2, 7,
12, 1, 6, 11,
];
let original = [
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15,
];
shift_rows(&mut state);
assert_eq!(state, expected);
inv_shift_rows(&mut state);
assert_eq!(state, original);
}
#[test]
fn test_byte_sub() {
let original = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4];
let mut state = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4];
sub_bytes(&mut state);
inv_sub_bytes(&mut state);
assert_eq!(state, original);
}
#[test]
fn test_gal_mul() {
assert_eq!(gal_mul(2, 2), 4);
assert_eq!(gal_mul(6, 3), 10);
assert_eq!(gal_mul(7, 12), 36);
assert_eq!(gal_mul(12, 12), 80);
}
#[test]
fn test_col_shift() {
let mut state = [
0xd4, 0xbf, 0x5d, 0x30,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
];
let original = state;
let expected = [
0x04, 0x66, 0x81, 0xe5,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
];
mix_cols(&mut state);
assert_eq!(state, expected);
inv_mix_cols(&mut state);
assert_eq!(state, original);
}
#[test]
fn test_encryption() {
let key = hex!("000102030405060708090a0b0c0d0e0f");
let mut plaintext = hex!("00112233445566778899aabbccddeeff");
let expected = hex!("69c4e0d86a7b0430d8cdb78070b4c55a");
block_encrypt(&mut plaintext, &key);
assert_eq!(plaintext, expected);
}
#[test]
fn test_decryption() {
let key = hex!("000102030405060708090a0b0c0d0e0f");
let mut ciphertext = hex!("69c4e0d86a7b0430d8cdb78070b4c55a");
let expected = hex!("00112233445566778899aabbccddeeff");
block_decrypt(&mut ciphertext, &key);
assert_eq!(ciphertext, expected);
}
}