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.SEED(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            output.append("IV = {0}".format(iv))
42        elif line.startswith("PLAINTEXT"):
43            name, plaintext = line.split(" = ")
44            output.append("PLAINTEXT = {0}".format(plaintext))
45
46    output.append("CIPHERTEXT = {0}".format(encrypt(mode, key, iv, plaintext)))
47    return "\n".join(output)
48
49
50def write_file(data, filename):
51    with open(filename, "w") as f:
52        f.write(data)
53
54
55OFB_PATH = "vectors/cryptography_vectors/ciphers/AES/OFB/OFBMMT128.rsp"
56write_file(build_vectors(modes.OFB, OFB_PATH), "seed-ofb.txt")
57CFB_PATH = "vectors/cryptography_vectors/ciphers/AES/CFB/CFB128MMT128.rsp"
58write_file(build_vectors(modes.CFB, CFB_PATH), "seed-cfb.txt")
59