lib/crypto: tests: Add KUnit tests for CBC-based MACs

Add a KUnit test suite for the AES-CMAC, AES-XCBC-MAC, and AES-CBC-MAC
library functions.

Reviewed-by: Ard Biesheuvel <ardb@kernel.org>
Link: https://lore.kernel.org/r/20260218213501.136844-7-ebiggers@kernel.org
Link: https://lore.kernel.org/r/20260306001917.24105-1-ebiggers@kernel.org
Signed-off-by: Eric Biggers <ebiggers@kernel.org>
This commit is contained in:
Eric Biggers
2026-02-18 13:34:52 -08:00
parent 58286738b1
commit a348fd1f6e
6 changed files with 450 additions and 3 deletions

View File

@@ -3,8 +3,12 @@
#
# Script that generates test vectors for the given hash function.
#
# Requires that python-cryptography be installed.
#
# Copyright 2025 Google LLC
import cryptography.hazmat.primitives.ciphers
import cryptography.hazmat.primitives.cmac
import hashlib
import hmac
import sys
@@ -24,6 +28,20 @@ def rand_bytes(length):
out.append((seed >> 16) % 256)
return bytes(out)
AES_256_KEY_SIZE = 32
# AES-CMAC. Just wraps the implementation from python-cryptography.
class AesCmac:
def __init__(self, key):
aes = cryptography.hazmat.primitives.ciphers.algorithms.AES(key)
self.cmac = cryptography.hazmat.primitives.cmac.CMAC(aes)
def update(self, data):
self.cmac.update(data)
def digest(self):
return self.cmac.finalize()
POLY1305_KEY_SIZE = 32
# A straightforward, unoptimized implementation of Poly1305.
@@ -80,9 +98,12 @@ class Polyval:
return self.acc.to_bytes(16, byteorder='little')
def hash_init(alg):
# The keyed hash functions are assigned a fixed random key here, to present
# them as unkeyed hash functions. This allows all the test cases for
# unkeyed hash functions to work on them.
if alg == 'aes-cmac':
return AesCmac(rand_bytes(AES_256_KEY_SIZE))
if alg == 'poly1305':
# Use a fixed random key here, to present Poly1305 as an unkeyed hash.
# This allows all the test cases for unkeyed hashes to work on Poly1305.
return Poly1305(rand_bytes(POLY1305_KEY_SIZE))
if alg == 'polyval':
return Polyval(rand_bytes(POLYVAL_BLOCK_SIZE))
@@ -116,6 +137,8 @@ def print_c_struct_u8_array_field(name, value):
print('\t\t},')
def alg_digest_size_const(alg):
if alg == 'aes-cmac':
return 'AES_BLOCK_SIZE'
if alg.startswith('blake2'):
return f'{alg.upper()}_HASH_SIZE'
return f"{alg.upper().replace('-', '_')}_DIGEST_SIZE"
@@ -252,7 +275,9 @@ if len(sys.argv) != 2:
alg = sys.argv[1]
print('/* SPDX-License-Identifier: GPL-2.0-or-later */')
print(f'/* This file was generated by: {sys.argv[0]} {" ".join(sys.argv[1:])} */')
if alg.startswith('blake2'):
if alg == 'aes-cmac':
gen_unkeyed_testvecs(alg)
elif alg.startswith('blake2'):
gen_unkeyed_testvecs(alg)
gen_additional_blake2_testvecs(alg)
elif alg == 'nh':