History

lib/crypto: tests: Add KUnit test suite for AES-CCM

Add a KUnit test suite for the AES-CCM library API. It consists of: - All the shared test cases from aead-test-template.h. These include extensive consistency tests, a "Monte-Carlo test", and a benchmark. - Tests against hardcoded AES-CCM test vectors from external sources. - Tests for CCM-specific message length validation. To generate the expected aes_ccm_monte_carlo_checksum[] value, add a script gen-aead-testvecs.py which computes it using python-cryptography.

Eric Biggers committed 3 months ago

Commit 2aeef501 parent 9396dc95 files · +427 −0Browse files

Showing the changes to scripts (1 of 5 files). Show all

Unified · Split

scripts/crypto/gen-aead-testvecs.py+60−0
@@ -0,0 +1,60 @@
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
45 blake2s.update(ct_and_tag)
46
47 name = f"{alg.replace('-', '_')}_monte_carlo_checksum"
48 value = blake2s.digest()
49 print(f"static const u8 {name}[BLAKE2S_HASH_SIZE] = {{")
50 for i in range(0, len(value), 11):
51 line = "\t" + "".join(f"0x{b:02x}, " for b in value[i : i + 11])
52 print(f"{line.rstrip()}")
53 print("};")
54
55
56if len(sys.argv) != 2 or sys.argv[1] not in ("aes-ccm"):
57 sys.stderr.write("Usage: gen-aead-testvecs.py [aes-ccm]\n")
58 sys.exit(1)
59
60gen_monte_carlo_checksum(sys.argv[1])