1import binascii 2 3from cryptography.hazmat.backends.openssl.backend import backend 4from cryptography.hazmat.primitives.ciphers import algorithms, base, modes 5 6 7def encrypt(mode, key, iv, plaintext): 8 cipher = base.Cipher( 9 algorithms.IDEA(binascii.unhexlify(key)), 10 mode(binascii.unhexlify(iv)), 11 backend 12 ) 13 encryptor = cipher.encryptor() 14 ct = encryptor.update(binascii.unhexlify(plaintext)) 15 ct += encryptor.finalize() 16 return binascii.hexlify(ct) 17 18 19def build_vectors(mode, filename): 20 with open(filename, "r") as f: 21 vector_file = f.read().splitlines() 22 23 count = 0 24 output = [] 25 key = None 26 iv = None 27 plaintext = None 28 for line in vector_file: 29 line = line.strip() 30 if line.startswith("KEY"): 31 if count != 0: 32 output.append("CIPHERTEXT = {0}".format( 33 encrypt(mode, key, iv, plaintext)) 34 ) 35 output.append("\nCOUNT = {0}".format(count)) 36 count += 1 37 name, key = line.split(" = ") 38 output.append("KEY = {0}".format(key)) 39 elif line.startswith("IV"): 40 name, iv = line.split(" = ") 41 iv = iv[0:16] 42 output.append("IV = {0}".format(iv)) 43 elif line.startswith("PLAINTEXT"): 44 name, plaintext = line.split(" = ") 45 output.append("PLAINTEXT = {0}".format(plaintext)) 46 47 output.append("CIPHERTEXT = {0}".format(encrypt(mode, key, iv, plaintext))) 48 return "\n".join(output) 49 50 51def write_file(data, filename): 52 with open(filename, "w") as f: 53 f.write(data) 54 55 56CBC_PATH = "tests/hazmat/primitives/vectors/ciphers/AES/CBC/CBCMMT128.rsp" 57write_file(build_vectors(modes.CBC, CBC_PATH), "idea-cbc.txt") 58OFB_PATH = "tests/hazmat/primitives/vectors/ciphers/AES/OFB/OFBMMT128.rsp" 59write_file(build_vectors(modes.OFB, OFB_PATH), "idea-ofb.txt") 60CFB_PATH = "tests/hazmat/primitives/vectors/ciphers/AES/CFB/CFB128MMT128.rsp" 61write_file(build_vectors(modes.CFB, CFB_PATH), "idea-cfb.txt") 62