1# This file is dual licensed under the terms of the Apache License, Version 2# 2.0, and the BSD License. See the LICENSE file in the root of this repository 3# for complete details. 4 5from __future__ import absolute_import, division, print_function 6 7import binascii 8 9from cryptography.hazmat.backends import default_backend 10from cryptography.hazmat.primitives.ciphers import algorithms, base, modes 11 12 13def encrypt(mode, key, iv, plaintext): 14 cipher = base.Cipher( 15 algorithms.CAST5(binascii.unhexlify(key)), 16 mode(binascii.unhexlify(iv)), 17 default_backend() 18 ) 19 encryptor = cipher.encryptor() 20 ct = encryptor.update(binascii.unhexlify(plaintext)) 21 ct += encryptor.finalize() 22 return binascii.hexlify(ct) 23 24 25def build_vectors(mode, filename): 26 vector_file = open(filename, "r") 27 28 count = 0 29 output = [] 30 key = None 31 iv = None 32 plaintext = None 33 for line in vector_file: 34 line = line.strip() 35 if line.startswith("KEY"): 36 if count != 0: 37 output.append("CIPHERTEXT = {}".format( 38 encrypt(mode, key, iv, plaintext)) 39 ) 40 output.append("\nCOUNT = {}".format(count)) 41 count += 1 42 name, key = line.split(" = ") 43 output.append("KEY = {}".format(key)) 44 elif line.startswith("IV"): 45 name, iv = line.split(" = ") 46 iv = iv[0:16] 47 output.append("IV = {}".format(iv)) 48 elif line.startswith("PLAINTEXT"): 49 name, plaintext = line.split(" = ") 50 output.append("PLAINTEXT = {}".format(plaintext)) 51 52 output.append("CIPHERTEXT = {}".format(encrypt(mode, key, iv, plaintext))) 53 return "\n".join(output) 54 55 56def write_file(data, filename): 57 with open(filename, "w") as f: 58 f.write(data) 59 60 61cbc_path = "tests/hazmat/primitives/vectors/ciphers/AES/CBC/CBCMMT128.rsp" 62write_file(build_vectors(modes.CBC, cbc_path), "cast5-cbc.txt") 63ofb_path = "tests/hazmat/primitives/vectors/ciphers/AES/OFB/OFBMMT128.rsp" 64write_file(build_vectors(modes.OFB, ofb_path), "cast5-ofb.txt") 65cfb_path = "tests/hazmat/primitives/vectors/ciphers/AES/CFB/CFB128MMT128.rsp" 66write_file(build_vectors(modes.CFB, cfb_path), "cast5-cfb.txt") 67ctr_path = "tests/hazmat/primitives/vectors/ciphers/AES/CTR/aes-128-ctr.txt" 68write_file(build_vectors(modes.CTR, ctr_path), "cast5-ctr.txt") 69