| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 |
|
| 10 | import hashlib
|
| 11 | import sys
|
| 12 | import cryptography.hazmat.primitives.ciphers.aead
|
| 13 |
|
| 14 |
|
| 15 | |
| 16 | def 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 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | def 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 | |
| 51 | |
| 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 |
|
| 65 | if 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 |
|
| 69 | gen_monte_carlo_checksum(sys.argv[1])
|