• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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    count = 0
27    output = []
28    key = None
29    iv = None
30    plaintext = None
31
32    with open(filename, "r") as vector_file:
33        for line in vector_file:
34            line = line.strip()
35            if line.startswith("KEY"):
36                if count != 0:
37                    output.append(
38                        "CIPHERTEXT = {}".format(
39                            encrypt(mode, key, iv, plaintext)
40                        )
41                    )
42                output.append("\nCOUNT = {}".format(count))
43                count += 1
44                name, key = line.split(" = ")
45                output.append("KEY = {}".format(key))
46            elif line.startswith("IV"):
47                name, iv = line.split(" = ")
48                iv = iv[0:16]
49                output.append("IV = {}".format(iv))
50            elif line.startswith("PLAINTEXT"):
51                name, plaintext = line.split(" = ")
52                output.append("PLAINTEXT = {}".format(plaintext))
53        output.append(
54            "CIPHERTEXT = {}".format(encrypt(mode, key, iv, plaintext))
55        )
56    return "\n".join(output)
57
58
59def write_file(data, filename):
60    with open(filename, "w") as f:
61        f.write(data)
62
63
64cbc_path = "tests/hazmat/primitives/vectors/ciphers/AES/CBC/CBCMMT128.rsp"
65write_file(build_vectors(modes.CBC, cbc_path), "cast5-cbc.txt")
66ofb_path = "tests/hazmat/primitives/vectors/ciphers/AES/OFB/OFBMMT128.rsp"
67write_file(build_vectors(modes.OFB, ofb_path), "cast5-ofb.txt")
68cfb_path = "tests/hazmat/primitives/vectors/ciphers/AES/CFB/CFB128MMT128.rsp"
69write_file(build_vectors(modes.CFB, cfb_path), "cast5-cfb.txt")
70ctr_path = "tests/hazmat/primitives/vectors/ciphers/AES/CTR/aes-128-ctr.txt"
71write_file(build_vectors(modes.CTR, ctr_path), "cast5-ctr.txt")
72