xref: /linux/scripts/crypto/gen-fips-testvecs.py (revision 40286d6379aacfcc053253ef78dc78b09addffda)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0-or-later
3#
4# Script that generates lib/crypto/fips.h
5#
6# Requires that python-cryptography be installed.
7#
8# Copyright 2025 Google LLC
9
10import cryptography.hazmat.primitives.ciphers
11import cryptography.hazmat.primitives.cmac
12import hashlib
13import hmac
14
15fips_test_data = b"fips test data\0\0"
16fips_test_key = b"fips test key\0\0\0"
17
18def print_static_u8_array_definition(name, value):
19    print('')
20    print(f'static const u8 {name}[] __initconst __maybe_unused = {{')
21    for i in range(0, len(value), 8):
22        line = '\t' + ''.join(f'0x{b:02x}, ' for b in value[i:i+8])
23        print(f'{line.rstrip()}')
24    print('};')
25
26print('/* SPDX-License-Identifier: GPL-2.0-or-later */')
27print(f'/* This file was generated by: gen-fips-testvecs.py */')
28print()
29print('#include <linux/fips.h>')
30
31print_static_u8_array_definition("fips_test_data", fips_test_data)
32print_static_u8_array_definition("fips_test_key", fips_test_key)
33
34for alg in 'sha1', 'sha256', 'sha512':
35    ctx = hmac.new(fips_test_key, digestmod=alg)
36    ctx.update(fips_test_data)
37    print_static_u8_array_definition(f'fips_test_hmac_{alg}_value', ctx.digest())
38
39print_static_u8_array_definition(f'fips_test_sha3_256_value',
40                                 hashlib.sha3_256(fips_test_data).digest())
41
42aes = cryptography.hazmat.primitives.ciphers.algorithms.AES(fips_test_key)
43aes_cmac = cryptography.hazmat.primitives.cmac.CMAC(aes)
44aes_cmac.update(fips_test_data)
45print_static_u8_array_definition('fips_test_aes_cmac_value',
46                                 aes_cmac.finalize())
47