aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/test/toolkit.py
blob: e94fe295fd0b126b7015ee33bc7752287b8d6319 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# Copyright 2015 Egor Tensin <Egor.Tensin@gmail.com>
# This file is licensed under the terms of the MIT License.
# See LICENSE.txt for details.

import collections
from enum import Enum
import logging
import os.path
import subprocess

class Algorithm(Enum):
    @staticmethod
    def parse(s):
        return Algorithm(s.lower())

    @staticmethod
    def try_parse(s):
        try:
            return Algorithm.parse(s)
        except ValueError:
            return None

    AES128, AES192, AES256 = 'aes128', 'aes192', 'aes256'

    def __str__(self):
        return self.value


class Mode(Enum):
    @staticmethod
    def parse(s):
        s = s.lower()
        if '{}128'.format(Mode.CFB) == s:
            return Mode.CFB
        return Mode(s)

    @staticmethod
    def try_parse(s):
        try:
            return Mode.parse(s)
        except ValueError:
            return None

    ECB, CBC, CFB, OFB, CTR = 'ecb', 'cbc', 'cfb', 'ofb', 'ctr'

    def requires_init_vector(self):
        return self != Mode.ECB

    def __str__(self):
        return self.value

class BlockInput:
    def __init__(self, key, plaintexts, iv=None):
        self.key = key
        self.plaintexts = plaintexts
        self.iv = iv

    def to_args(self):
        args = [self.key]
        if self.iv is not None:
            args.append(self.iv)
        args.extend(self.plaintexts)
        return args

class Tools:
    def __init__(self, search_dirs, use_sde=False):
        if search_dirs:
            if isinstance(search_dirs, str):
                os.environ['PATH'] += os.pathsep + search_dirs
            elif isinstance(search_dirs, collections.Iterable):
                os.environ['PATH'] += os.pathsep + os.pathsep.join(search_dirs)
            else:
                os.environ['PATH'] += os.pathsep + str(search_dirs)
        self._use_sde = use_sde
        self._logger = logging.getLogger(__name__)

    _ENCRYPT_BLOCK = 'encrypt_block.exe'
    _DECRYPT_BLOCK = 'decrypt_block.exe'
    _ENCRYPT_FILE = 'encrypt_file.exe'
    _DECRYPT_FILE = 'decrypt_file.exe'

    def run(self, tool_path, args):
        cmd_list = ['sde', '--', tool_path] if self._use_sde else [tool_path]
        cmd_list.extend(args)
        logging.info('Trying to execute: {0}'.format(
            subprocess.list2cmdline(cmd_list)))
        try:
            output = subprocess.check_output(
                cmd_list, universal_newlines=True, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            logging.error('Output:\n' + e.output)
            raise
        logging.info('Output:\n' + output)
        return output.split()

    @staticmethod
    def _block_inputs_to_args(inputs):
        args = []
        while True:
            head = next(inputs, None)
            if head is None:
                break
            args.append('--')
            args.extend(head.to_args())
        return args

    @staticmethod
    def _block_settings_to_args(algorithm, mode, use_boxes=False):
        args = [
            '--algorithm', str(algorithm),
            '--mode', str(mode),
        ]
        if use_boxes:
            args.append('--use-boxes')
        return args

    @staticmethod
    def _build_block_args(algorithm, mode, inputs, use_boxes=False):
        args = Tools._block_settings_to_args(algorithm, mode, use_boxes)
        if isinstance(inputs, collections.Iterable):
            args.extend(Tools._block_inputs_to_args(iter(inputs)))
        else:
            args.extend(inputs.to_args())
        return args

    def run_encrypt_block(self, algorithm, mode, inputs, use_boxes=False):
        return self.run(self._ENCRYPT_BLOCK,
                        self._build_block_args(algorithm, mode, inputs, use_boxes))

    def run_decrypt_block(self, algorithm, mode, inputs, use_boxes=False):
        return self.run(self._DECRYPT_BLOCK,
                        self._build_block_args(algorithm, mode, inputs, use_boxes))

    @staticmethod
    def _file_settings_to_args(algorithm, mode, key, input_path, output_path, iv=None):
        args = [
            '--algorithm', str(algorithm),
            '--mode', str(mode),
            '--key', key,
            '--input-path', input_path,
            '--output-path', output_path
        ]
        if iv is not None:
            args.extend(('--iv', iv))
        return args

    def run_encrypt_file(self, algorithm, mode, key, input_path, output_path, iv=None):
        return self.run(self._ENCRYPT_FILE,
                        self._file_settings_to_args(algorithm, mode, key, input_path, output_path, iv))

    def run_decrypt_file(self, algorithm, mode, key, input_path, output_path, iv=None):
        return self.run(self._DECRYPT_FILE,
                        self._file_settings_to_args(algorithm, mode, key, input_path, output_path, iv))