xref: /linux/scripts/crypto/gen-aead-testvecs.py (revision 85cdaca6970028bf6f544c355c90035586836ddf)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0-or-later
3#
4# Script that generates known-good data used in the AEAD tests.
5#
6# Requires that python-cryptography be installed.
7#
8# Copyright 2026 Google LLC
9
10import hashlib
11import sys
12import cryptography.hazmat.primitives.ciphers.aead
13
14
15# Deterministically generate 'length' random bytes.
16def rand_bytes(length):
17    seed = length
18    out = []
19    for _ in range(length):
20        seed = (seed * 25214903917 + 11) % 2**48
21        out.append((seed >> 16) % 256)
22    return bytes(out)
23
24
25# Deterministically generate many different AEAD inputs using exactly the same
26# method that the test uses; encrypt them using an independent implementation of
27# the algorithm; compute the checksum of all the resulting (ciphertext, authtag)
28# pairs concatenated to each other; and print the checksum as a C struct.
29def gen_monte_carlo_checksum(alg):
30    blake2s = hashlib.blake2s()
31    for data_len in range(1025):
32        ad_len = data_len % 293
33        pt = rand_bytes(data_len)
34        ad = rand_bytes(ad_len)
35        if alg == "aes-ccm":
36            key_len = [16, 24, 32][data_len % 3]
37            key = rand_bytes(key_len)
38            nonce = rand_bytes([7, 8, 9, 10, 11, 12, 13][data_len % 7])
39            tag_len = [4, 6, 8, 10, 12, 14, 16][data_len % 7]
40            ccm = cryptography.hazmat.primitives.ciphers.aead.AESCCM(
41                key, tag_length=tag_len
42            )
43            ct_and_tag = ccm.encrypt(nonce, pt, ad)
44        elif alg == "aes-gcm":
45            key_len = [16, 24, 32][data_len % 3]
46            key = rand_bytes(key_len)
47            nonce = rand_bytes(12)
48            tag_len = [4, 8, 12, 13, 14, 15, 16][data_len % 7]
49            gcm = cryptography.hazmat.primitives.ciphers.aead.AESGCM(key)
50            # python-cryptography supports only 16-byte GCM tags.  However, in
51            # GCM, shorter tags are simply truncated.  Do that below.
52            ct_and_tag = gcm.encrypt(nonce, pt, ad)[: data_len + tag_len]
53
54        blake2s.update(ct_and_tag)
55
56    name = f"{alg.replace('-', '_')}_monte_carlo_checksum"
57    value = blake2s.digest()
58    print(f"static const u8 {name}[BLAKE2S_HASH_SIZE] = {{")
59    for i in range(0, len(value), 11):
60        line = "\t" + "".join(f"0x{b:02x}, " for b in value[i : i + 11])
61        print(f"{line.rstrip()}")
62    print("};")
63
64
65if len(sys.argv) != 2 or sys.argv[1] not in ("aes-ccm", "aes-gcm"):
66    sys.stderr.write("Usage: gen-aead-testvecs.py [aes-ccm|aes-gcm]\n")
67    sys.exit(1)
68
69gen_monte_carlo_checksum(sys.argv[1])
70