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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::{
    constants::AlgorithmIdentifier,
    interface_types::{
        algorithm::{HashingAlgorithm, SymmetricAlgorithm, SymmetricMode, SymmetricObject},
        key_bits::{AesKeyBits, CamelliaKeyBits, Sm4KeyBits},
    },
    structures::{SymmetricCipherParameters, SymmetricDefinition, SymmetricDefinitionObject},
    Error, Result, WrapperErrorKind,
};
use std::convert::{TryFrom, TryInto};
/// Block cipher identifiers
///
/// Structure useful for handling an abstract representation of ciphers. Ciphers are
/// defined foremost through their symmetric algorithm and, depending on the type of that
/// algorithm, on a set of other values.
#[derive(Copy, Clone, Debug)]
pub struct Cipher {
    algorithm: SymmetricAlgorithm,
    mode: Option<SymmetricMode>,
    key_bits: Option<u16>,
    hash: Option<HashingAlgorithm>,
}

impl Cipher {
    /// Constructor for AES cipher identifier
    ///
    /// `key_bits` must be one of 128, 192 or 256.
    pub fn aes(mode: SymmetricMode, key_bits: u16) -> Result<Self> {
        match key_bits {
            128 | 192 | 256 => (),
            _ => return Err(Error::local_error(WrapperErrorKind::InvalidParam)),
        }

        Ok(Cipher {
            algorithm: SymmetricAlgorithm::Aes,
            mode: Some(mode),
            key_bits: Some(key_bits),
            hash: None,
        })
    }

    /// Constructor for Camellia cipher identifier
    ///
    /// `key_bits` must be one of 128, 192 or 256.
    pub fn camellia(mode: SymmetricMode, key_bits: u16) -> Result<Self> {
        match key_bits {
            128 | 192 | 256 => (),
            _ => return Err(Error::local_error(WrapperErrorKind::InvalidParam)),
        }

        Ok(Cipher {
            algorithm: SymmetricAlgorithm::Camellia,
            mode: Some(mode),
            key_bits: Some(key_bits),
            hash: None,
        })
    }

    /// Constructor for Triple DES cipher identifier
    ///
    /// `key_bits` must be one of 56, 112 or 168.
    pub fn tdes(mode: SymmetricMode, key_bits: u16) -> Result<Self> {
        match key_bits {
            56 | 112 | 168 => (),
            _ => return Err(Error::local_error(WrapperErrorKind::InvalidParam)),
        }

        Ok(Cipher {
            algorithm: SymmetricAlgorithm::Tdes,
            mode: Some(mode),
            key_bits: Some(key_bits),
            hash: None,
        })
    }

    /// Constructor for SM4 cipher identifier
    pub fn sm4(mode: SymmetricMode) -> Self {
        Cipher {
            algorithm: SymmetricAlgorithm::Sm4,
            mode: Some(mode),
            key_bits: Some(128),
            hash: None,
        }
    }

    /// Constructor for XOR "cipher" identifier
    pub fn xor(hash: HashingAlgorithm) -> Self {
        Cipher {
            algorithm: SymmetricAlgorithm::Xor,
            mode: None,
            key_bits: None,
            hash: Some(hash),
        }
    }

    /// Get general object type for symmetric ciphers.
    pub fn object_type() -> AlgorithmIdentifier {
        AlgorithmIdentifier::SymCipher
    }

    /// Get the cipher key length.
    pub fn key_bits(self) -> Option<u16> {
        self.key_bits
    }

    /// Get the cipher mode.
    pub fn mode(self) -> Option<SymmetricMode> {
        self.mode
    }

    /// Get the hash algorithm used with an XOR cipher
    pub fn hash(self) -> Option<HashingAlgorithm> {
        self.hash
    }

    /// Get the symmetrical algorithm for the cipher.
    pub fn algorithm(&self) -> SymmetricAlgorithm {
        self.algorithm
    }

    /// Constructor for 128 bit AES in CFB mode.
    pub fn aes_128_cfb() -> Self {
        Cipher {
            algorithm: SymmetricAlgorithm::Aes,
            mode: Some(SymmetricMode::Cfb),
            key_bits: Some(128),
            hash: None,
        }
    }

    /// Constructor for 256 bit AES in CFB mode.
    pub fn aes_256_cfb() -> Self {
        Cipher {
            algorithm: SymmetricAlgorithm::Aes,
            mode: Some(SymmetricMode::Cfb),
            key_bits: Some(256),
            hash: None,
        }
    }
}

impl TryFrom<Cipher> for SymmetricDefinition {
    type Error = Error;
    fn try_from(cipher: Cipher) -> Result<Self> {
        match cipher.algorithm {
            SymmetricAlgorithm::Aes => Ok(SymmetricDefinition::Aes {
                key_bits: cipher
                    .key_bits
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))
                    .and_then(AesKeyBits::try_from)?,
                mode: cipher
                    .mode
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))?,
            }),
            SymmetricAlgorithm::Sm4 => Ok(SymmetricDefinition::Sm4 {
                key_bits: cipher
                    .key_bits
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))
                    .and_then(Sm4KeyBits::try_from)?,
                mode: cipher
                    .mode
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))?,
            }),
            SymmetricAlgorithm::Camellia => Ok(SymmetricDefinition::Camellia {
                key_bits: cipher
                    .key_bits
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))
                    .and_then(CamelliaKeyBits::try_from)?,
                mode: cipher
                    .mode
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))?,
            }),
            SymmetricAlgorithm::Xor => Ok(SymmetricDefinition::Xor {
                hashing_algorithm: cipher
                    .hash
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))
                    .and_then(|ha| {
                        if ha != HashingAlgorithm::Null {
                            Ok(ha)
                        } else {
                            Err(Error::local_error(WrapperErrorKind::InvalidParam))
                        }
                    })?,
            }),
            SymmetricAlgorithm::Null => Ok(SymmetricDefinition::Null),
            SymmetricAlgorithm::Tdes => {
                // TODO: Investigate
                Err(Error::local_error(WrapperErrorKind::UnsupportedParam))
            }
        }
    }
}

impl TryFrom<Cipher> for SymmetricDefinitionObject {
    type Error = Error;
    fn try_from(cipher: Cipher) -> Result<Self> {
        match SymmetricObject::try_from(AlgorithmIdentifier::from(cipher.algorithm))? {
            SymmetricObject::Aes => Ok(SymmetricDefinitionObject::Aes {
                key_bits: cipher
                    .key_bits
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))
                    .and_then(AesKeyBits::try_from)?,
                mode: cipher
                    .mode
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))?,
            }),
            SymmetricObject::Sm4 => Ok(SymmetricDefinitionObject::Sm4 {
                key_bits: cipher
                    .key_bits
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))
                    .and_then(Sm4KeyBits::try_from)?,
                mode: cipher
                    .mode
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))?,
            }),
            SymmetricObject::Camellia => Ok(SymmetricDefinitionObject::Camellia {
                key_bits: cipher
                    .key_bits
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))
                    .and_then(CamelliaKeyBits::try_from)?,
                mode: cipher
                    .mode
                    .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))?,
            }),
            SymmetricObject::Null => Ok(SymmetricDefinitionObject::Null),
            SymmetricObject::Tdes => {
                // TODO investigate
                Err(Error::local_error(WrapperErrorKind::UnsupportedParam))
            }
        }
    }
}

impl TryFrom<Cipher> for SymmetricCipherParameters {
    type Error = Error;
    fn try_from(cipher: Cipher) -> Result<Self> {
        Ok(SymmetricCipherParameters::new(cipher.try_into()?))
    }
}