genkat_aead.py (2146B)
1 #!/usr/bin/env python3 2 3 # Python port of genkat_aead.c. 4 # 5 # Authors, hereby denoted as "the implementer": 6 # Kévin Le Gouguec, 7 # 2019. 8 # 9 # For more information, feedback or questions, refer to our website: 10 # https://paclido.fr/lilliput-ae 11 # 12 # To the extent possible under law, the implementer has waived all copyright 13 # and related or neighboring rights to the source code in this file. 14 # http://creativecommons.org/publicdomain/zero/1.0/ 15 16 """Python port of the genkat_aead.c program.""" 17 18 from os import path 19 from sys import argv 20 21 import crypto_aead 22 23 24 class DecryptionError(Exception): 25 def __init__(self): 26 super().__init__('crypto_aead.decrypt did not recover the plaintext') 27 28 29 MAX_MESSAGE_LENGTH = 32 30 MAX_ASSOCIATED_DATA_LENGTH = 32 31 32 33 def print_bstr(output, label, buf): 34 print('{l} = {b}'.format(l=label, b=buf.hex().upper()), file=output) 35 36 37 def generate_test_vectors(output_dir): 38 count = 1 39 filename = 'LWC_AEAD_KAT_{key}_{npub}.txt'.format( 40 key=crypto_aead.KEYBYTES*8, npub=crypto_aead.NPUBBYTES*8 41 ) 42 43 npub = bytes(range(crypto_aead.NPUBBYTES)) 44 key = bytes(range(crypto_aead.KEYBYTES)) 45 46 with open(path.join(output_dir, filename), 'w') as output: 47 48 for mlen in range(MAX_MESSAGE_LENGTH+1): 49 for adlen in range(MAX_ASSOCIATED_DATA_LENGTH+1): 50 51 msg = bytes(range(mlen)) 52 ad = bytes(range(adlen)) 53 54 print('Count = {c}'.format(c=count), file=output) 55 count += 1 56 57 print_bstr(output, 'Key', key) 58 print_bstr(output, 'Nonce', npub) 59 print_bstr(output, 'PT', msg) 60 print_bstr(output, 'AD', ad) 61 62 ct = crypto_aead.encrypt(msg, ad, npub, key) 63 64 print_bstr(output, 'CT', ct) 65 66 msg2 = crypto_aead.decrypt(ct, ad, npub, key) 67 68 if msg != msg2: 69 raise DecryptionError() 70 71 print(file=output) 72 73 74 def main(argv): 75 output_dir = path.curdir 76 if len(argv) > 1: 77 output_dir = argv[1] 78 79 generate_test_vectors(output_dir) 80 81 82 if __name__ == '__main__': 83 main(argv)