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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! The libvault::crypto module abstracts a set of generic cryptography methods. These methods
//! are used by other modules in RustyVault.
//!
//! This module depends on underlying cryptography library. One crypto adaptors MUST be specified
//! during the configuration, then it's compiled into RustyVault.
//!
//! # Crypto Adaptor Configurations
//!
//! In RustyVault, the real cryptographic operations are done via "crypto_adaptor"s.
//!
//! A crypto adaptor is a module that conveys and translates high level cryptography
//! operations like encryption, signing into the APIs provided by underlying cryptography
//! libraries such as OpenSSL, Tongsuo and so forth.
//!
//! At current stage, only one crypto_adaptor can be enabled at compilation phase and later
//! be used at run-time. "crypto_adaptor"s are configured as 'feature's in the Cargo context.
//!
//! Currently, the supported feature names of crypto adaptors are as follows, you can enable
//! them by adding one '--features crypto_adaptor_name' option when running "cargo build":
//!
//! 1. the OpenSSL adaptor: crypto_adaptor_openssl
//! 2. the Tongsuo adaptor: crypto_adaptor_tongsuo
//!
//! If there is no explicit crypto adpator configured, then the `crypto_adaptor_openssl` is used as
//! the default option.
//!
//! # Enable the Tongsuo adaptor
//!
//! Tongsuo is a variant of OpenSSL but with more features on SMx algorithms and protocols.
//! RustyVault can use SM algorithms only if Tongsuo is built as the crypto adaptor.
//!
//! You need to build and install Tongsuo first into your local environment before building
//! RustyVault with Tongsuo. Check the following link for detailed installation steps:
//! [Tongsuo](https://github.com/Tongsuo-Project/Tongsuo)
//!
//! ~~~text
//! $ export OPENSSL_DIR=/path/to/tongsuo/install/directory
//! $ cargo build --features crypto_adaptor_tongsuo \
//! --no-default-features \
//! --config 'patch.crates-io.openssl.git="https://github.com/Tongsuo-Project/rust-tongsuo.git"'\
//! --config 'patch.crates-io.openssl-sys.git="https://github.com/Tongsuo-Project/rust-tongsuo.git"'
//! ~~~
//!
//! Or you can just uncomment the following lines in Cargo.toml:
//!
//! ~~~text
//! #[patch.crates-io]
//! #openssl = { git = "https://github.com/Tongsuo-Project/rust-tongsuo.git" }
//! #openssl-sys = { git = "https://github.com/Tongsuo-Project/rust-tongsuo.git" }
//! ~~~
//!
//! and then:
//!
//! ~~~text
//! $ cargo build --features crypto_adaptor_tongsuo --no-default-features
//! ~~~
use AdaptorCTX;
use AdaptorCTX;
use crateRvError;
/// This defines common modes for block ciphers.
/// This enum defines common AES key size constants.
/// This enum defines public key algorithm type constants.
// All structs are defined here. Every struct represents a type of cryptography algorithm.
/// The AES block cipher structure.
// we add this lint here because it's not guaranteed all underlying adaptors support this
// algorithm. And it's logical to suppress warnings when building the code.
/// The SM4 block cipher structure.
/// BlockCipher is the 'base' trait for all kinds of block cipher alogrithms. In this trait,
/// neccessary methods are defined. Cryptography adaptors need to implement this trait to provide
/// real algorithms.
///
/// # Examples
///
/// The following are some examples on how to use the functions of trait BlockCipher.
///
/// ## One-shot encryption and decryption
///
/// ~~~
/// use libvault::modules::crypto::{AES, AESKeySize, CipherMode, BlockCipher};
///
/// let data = b"The best way to not feel hopeless is to get up and do something.".to_vec();
/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F".to_vec();
/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07".to_vec();
/// let mut aes_encrypter = AES::new(false, Some(AESKeySize::AES128),
/// Some(CipherMode::CBC), Some(key.clone()), Some(iv.clone())).unwrap();
/// let mut aes_decrypter = AES::new(false, Some(AESKeySize::AES128),
/// Some(CipherMode::CBC), Some(key), Some(iv)).unwrap();
///
/// let ct = aes_encrypter.encrypt(&data).unwrap();
/// let pt = aes_decrypter.decrypt(&ct).unwrap();
/// assert_eq!(data.to_vec(), pt);
/// ~~~
///
/// ## Stream encryption and decryption
///
/// The following code works only with `crypto_adaptor_tongsuo`.
///
/// use libvault::modules::crypto::{SM4, CipherMode, BlockCipher};
///
/// let data: [&[u8]; 2] = [b"The best way to not feel hopeless ",
/// b"is to get up and do something."];
/// let data2 = b"The best way to not feel hopeless is to get up and do something.";
/// let data_len = data.iter().fold(0, |sum, x| sum + x.len());
/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F".to_vec();
/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07".to_vec();
/// let mut sm4_encrypter = SM4::new(false, Some(CipherMode::CBC),
/// Some(key.clone()), Some(iv.clone())).unwrap();
/// let mut sm4_decrypter = SM4::new(false, Some(CipherMode::CBC),
/// Some(key), Some(iv)).unwrap();
/// let mut ct: Vec<u8> = vec![];
///
/// let mut v1: Vec<u8> = vec![0; data_len + 16];
/// let mut v2: Vec<u8>= vec![0; data_len + 16];
/// let mut v3: Vec<u8>= vec![0; data_len + 16];
/// let mut count = sm4_encrypter.encrypt_update((&data[0]).to_vec(), &mut v1).unwrap();
/// v1.truncate(count);
/// count = sm4_encrypter.encrypt_update((&data[1]).to_vec(), &mut v2).unwrap();
/// v2.truncate(count);
/// count = sm4_encrypter.encrypt_final(&mut v3).unwrap();
/// v3.truncate(count);
/// ct.extend(v1);
/// ct.extend(v2);
/// ct.extend(v3);
///
/// let data_len2 = ct.len();
/// let mut pt1: Vec<u8> = vec![0; data_len2 + 16];
/// let mut pt2: Vec<u8>= vec![0; data_len2 + 16];
/// let mut pt3: Vec<u8>= vec![0; data_len2 + 16];
/// let mut pt: Vec<u8> = vec![];
/// // separate ciphertext into 2 pieces.
/// let cts = [&ct[..9], &ct[9..]];
///
/// count = sm4_decrypter.decrypt_update((&cts[0]).to_vec(), &mut pt1).unwrap();
/// pt1.truncate(count);
/// count = sm4_decrypter.decrypt_update((&cts[1]).to_vec(), &mut pt2).unwrap();
/// pt2.truncate(count);
/// count = sm4_decrypter.decrypt_final(&mut pt3).unwrap();
/// pt3.truncate(count);
/// pt.extend(pt1);
/// pt.extend(pt2);
/// pt.extend(pt3);
///
/// // evaluate the result.
/// assert_eq!(data2.to_vec(), pt);
/// ~~~
///
/// ## Use an auto-generated key
///
/// ~~~
/// use libvault::modules::crypto::{AES, AESKeySize, CipherMode, BlockCipher};
///
/// let data = b"The best way to not feel hopeless is to get up and do something.".to_vec();
/// let mut aes_encrypter = AES::new(true, Some(AESKeySize::AES128),
/// Some(CipherMode::CBC), None, None).unwrap();
/// let mut aes_decrypter = AES::new(false, Some(AESKeySize::AES128),
/// Some(CipherMode::CBC), Some(aes_encrypter.get_key_iv().0),
/// Some(aes_encrypter.get_key_iv().1)).unwrap();
///
/// let ct = aes_encrypter.encrypt(&data).unwrap();
/// let pt = aes_decrypter.decrypt(&ct).unwrap();
/// assert_eq!(data, pt);
/// ~~~
/// AEADCipher defines a block cipher in AEAD mode, such as GCM or CCM.
/// This trait is an extention of BlockCipher for some additional functions.
///
/// # Examples
///
/// The following are some examples on how to use the functions of trait AEADCipher.
///
/// # One-shot encryption and decryption using AEAD cipher
///
/// ~~~
/// use libvault::modules::crypto::{AES, AESKeySize, CipherMode, BlockCipher, AEADCipher};
///
/// let data = b"The best way to not feel hopeless is to get up and do something.".to_vec();
/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F".to_vec();
/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07".to_vec();
/// let aad = b"some additional authenticated data.".to_vec();
/// let mut aes_encrypter = AES::new(false, Some(AESKeySize::AES128),
/// Some(CipherMode::GCM), Some(key.clone()), Some(iv.clone())).unwrap();
/// let mut aes_decrypter = AES::new(false, Some(AESKeySize::AES128),
/// Some(CipherMode::GCM), Some(key), Some(iv)).unwrap();
///
/// // set aad, encrypt and get tag.
/// aes_encrypter.set_aad(aad.clone()).unwrap();
/// let ct = aes_encrypter.encrypt(&data).unwrap();
/// let tag = aes_encrypter.get_tag().unwrap();
///
/// // set aad, set tag and decrypt.
/// aes_decrypter.set_aad(aad).unwrap();
/// aes_decrypter.set_tag(tag).unwrap();
/// let pt = aes_decrypter.decrypt(&ct).unwrap();
///
/// // evaluate the result.
/// assert_eq!(data.to_vec(), pt);
/// ~~~
///
/// # Stream encryption and decryption using AEAD cipher
///
/// The following code works only with `crypto_adaptor_tongsuo`.
///
/// ~~~
/// use libvault::modules::crypto::{SM4, CipherMode, BlockCipher, AEADCipher};
///
/// let data: [&[u8]; 2] = [b"The best way to not feel hopeless ",
/// b"is to get up and do something."];
/// let data2 = b"The best way to not feel hopeless is to get up and do something.";
/// let data_len = data.iter().fold(0, |sum, x| sum + x.len());
/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F".to_vec();
/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07".to_vec();
/// let aad = b"some additional authenticated data.".to_vec();
/// let mut sm4_encrypter = SM4::new(false, Some(CipherMode::GCM),
/// Some(key.clone()), Some(iv.clone())).unwrap();
/// let mut sm4_decrypter = SM4::new(false, Some(CipherMode::GCM),
/// Some(key), Some(iv)).unwrap();
/// let mut ct: Vec<u8> = vec![];
///
/// // set aad, encrypt and get tag.
/// sm4_encrypter.set_aad(aad.clone()).unwrap();
/// let mut v1: Vec<u8> = vec![0; data_len + 16];
/// let mut v2: Vec<u8>= vec![0; data_len + 16];
/// let mut v3: Vec<u8>= vec![0; data_len + 16];
/// let mut count = sm4_encrypter.encrypt_update((&data[0]).to_vec(), &mut v1).unwrap();
/// v1.truncate(count);
/// count = sm4_encrypter.encrypt_update((&data[1]).to_vec(), &mut v2).unwrap();
/// v2.truncate(count);
/// count = sm4_encrypter.encrypt_final(&mut v3).unwrap();
/// v3.truncate(count);
/// ct.extend(v1);
/// ct.extend(v2);
/// ct.extend(v3);
/// let tag = sm4_encrypter.get_tag().unwrap();
///
/// // set aad, set tag and decrypt.
/// sm4_decrypter.set_aad(aad).unwrap();
/// sm4_decrypter.set_tag(tag).unwrap();
/// // separate cipher into 2 pieces.
/// let data_len2 = ct.len();
/// let mut pt1: Vec<u8> = vec![0; data_len2 + 16];
/// let mut pt2: Vec<u8>= vec![0; data_len2 + 16];
/// let mut pt3: Vec<u8>= vec![0; data_len2 + 16];
/// let mut pt: Vec<u8> = vec![];
/// let cts = [&ct[..9], &ct[9..]];
/// count = sm4_decrypter.decrypt_update((&cts[0]).to_vec(), &mut pt1).unwrap();
/// pt1.truncate(count);
/// count = sm4_decrypter.decrypt_update((&cts[1]).to_vec(), &mut pt2).unwrap();
/// pt2.truncate(count);
/// count = sm4_decrypter.decrypt_final(&mut pt3).unwrap();
/// pt3.truncate(count);
/// pt.extend(pt1);
/// pt.extend(pt2);
/// pt.extend(pt3);
///
/// // evaluate the result.
/// assert_eq!(data2.to_vec(), pt);
/// ~~~
/// The PublicKey trait abstracts a common function set for public key algorithms. Public key
/// algorithms usually refer to signature or encryption algorithms such as RSA, SM2 and so forth.
/// The Signature trait defines a signature algorithm, such as RSA, ECDSA or SM2.
/// This trait is a sub-trait of PublicKey trait.
/// The Encryption trait defines an public key encryption algorithm, such as RSA and SM4.
/// This trait is a sub-trait of PublicKey trait.