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
//! This is the Tongsuo adaptor.
use openssl::{
rand::rand_priv_bytes,
symm::{Cipher, Crypter, Mode, decrypt, decrypt_aead, encrypt, encrypt_aead},
};
use crate::{
errors::RvError,
modules::crypto::{
AEADCipher, AES, AESKeySize, BlockCipher, CipherMode, SM4, crypto_adaptors::common,
},
};
pub struct AdaptorCTX {
ctx: Crypter,
tag_set: bool,
aad_set: bool,
}
impl AES {
/// This function is the constructor of the AES struct, it returns a new AES object on success.
///
/// keygen: true stands for generating a key and iv; if false, then the caller needs to feed in
/// the specific key and iv values through the parameters.
/// size: bit-length of AES. If omitted, AESKeySize::AES128 is used as default.
/// mode: cipher mode of AES, such as CBC, GCM, etc. If omitted, CipherMode::CBC is default.
/// key: symmetric key that is used to encrypt and decrypt data.
/// iv: initialization vector. This depends on specific mode, for instance, ECB requires no IV.
pub fn new(
keygen: bool,
size: Option<AESKeySize>,
mode: Option<CipherMode>,
key: Option<Vec<u8>>,
iv: Option<Vec<u8>>,
) -> Result<Self, RvError> {
common_aes_new!(keygen, size, mode, key, iv);
}
/// This function returns the key and iv vaule stored in one AES object.
///
/// Two values are returned in a tuple: the first element represents the key, and the second
/// element represents the IV. Elements may be None if unset.
pub fn get_key_iv(&self) -> (Vec<u8>, Vec<u8>) {
common_get_key_iv!(self);
}
}
impl BlockCipher for AES {
fn encrypt(&mut self, plaintext: &Vec<u8>) -> Result<Vec<u8>, RvError> {
common_aes_encrypt!(self, plaintext);
}
fn encrypt_update(
&mut self,
plaintext: Vec<u8>,
ciphertext: &mut Vec<u8>,
) -> Result<usize, RvError> {
common_aes_encrypt_update!(self, plaintext, ciphertext);
}
fn encrypt_final(&mut self, ciphertext: &mut Vec<u8>) -> Result<usize, RvError> {
common_aes_encrypt_final!(self, ciphertext);
}
fn decrypt(&mut self, ciphertext: &Vec<u8>) -> Result<Vec<u8>, RvError> {
common_aes_decrypt!(self, ciphertext);
}
fn decrypt_update(
&mut self,
ciphertext: Vec<u8>,
plaintext: &mut Vec<u8>,
) -> Result<usize, RvError> {
common_aes_decrypt_update!(self, ciphertext, plaintext);
}
fn decrypt_final(&mut self, plaintext: &mut Vec<u8>) -> Result<usize, RvError> {
common_aes_decrypt_final!(self, plaintext);
}
}
impl AEADCipher for AES {
fn set_aad(&mut self, aad: Vec<u8>) -> Result<(), RvError> {
common_aes_set_aad!(self, aad);
}
fn get_tag(&mut self) -> Result<Vec<u8>, RvError> {
common_aes_get_tag!(self);
}
fn set_tag(&mut self, tag: Vec<u8>) -> Result<(), RvError> {
common_aes_set_tag!(self, tag);
}
}
impl SM4 {
/// This function is the constructor of the SM4 struct, it returns a new SM4 object on success.
///
/// keygen: true stands for generating a key and iv; if false, then the caller needs to feed in
/// the specific key and iv values through the parameters.
/// mode: cipher mode of SM4, such as CBC, GCM, etc. If omitted, CipherMode::CBC is default.
/// key: symmetric key that is used to encrypt and decrypt data.
/// iv: initialization vector. This depends on specific mode, for instance, ECB requires no IV.
pub fn new(
keygen: bool,
mode: Option<CipherMode>,
key: Option<Vec<u8>>,
iv: Option<Vec<u8>>,
) -> Result<Self, RvError> {
// default algorithm: SM4-CBC.
let mut c_mode = CipherMode::CBC;
let sm4_key: Vec<u8>;
let sm4_iv: Vec<u8>;
if let Some(x) = mode {
c_mode = x;
}
if keygen == false {
match (key, iv) {
(Some(x), Some(y)) => {
sm4_key = x.clone();
sm4_iv = y.clone();
}
_ => return Err(RvError::ErrCryptoCipherInitFailed),
}
} else {
// generate new key and iv based on k_size.
// for SM4, key is 16 bytes and iv is 16 bytes
let mut buf = [0; 16];
let mut buf2 = [0; 16];
rand_priv_bytes(&mut buf)?;
sm4_key = buf.to_vec();
rand_priv_bytes(&mut buf2)?;
sm4_iv = buf2.to_vec();
}
Ok(SM4 {
mode: c_mode,
key: sm4_key,
iv: sm4_iv,
aad: None,
ctx: None,
tag: None,
})
}
/// This function returns the key and iv vaule stored in one SM4 object.
///
/// Two values are returned in a tuple: the first element represents the key, and the second
/// element represents the IV. Elements may be None if unset.
pub fn get_key_iv(&self) -> (Vec<u8>, Vec<u8>) {
(self.key.clone(), self.iv.clone())
}
}
impl BlockCipher for SM4 {
fn encrypt(&mut self, plaintext: &Vec<u8>) -> Result<Vec<u8>, RvError> {
match self.mode {
CipherMode::CBC => {
let ciphertext = encrypt(Cipher::sm4_cbc(), &self.key, Some(&self.iv), plaintext)?;
return Ok(ciphertext.to_vec());
}
CipherMode::GCM => {
// aes_128_gcm's tag is 16-bytes long.
let tag: &mut [u8] = &mut [0; 16];
let ciphertext = encrypt_aead(
Cipher::sm4_gcm(),
&self.key,
Some(&self.iv),
&self.aad.clone().unwrap(),
plaintext,
tag,
)?;
self.tag = Some(tag.to_vec());
return Ok(ciphertext.to_vec());
}
_ => Err(RvError::ErrCryptoCipherOPNotSupported),
}
}
fn encrypt_update(
&mut self,
plaintext: Vec<u8>,
ciphertext: &mut Vec<u8>,
) -> Result<usize, RvError> {
let cipher;
match self.mode {
CipherMode::CBC => {
cipher = Cipher::sm4_cbc();
}
CipherMode::GCM => {
cipher = Cipher::sm4_gcm();
}
_ => {
return Err(RvError::ErrCryptoCipherOPNotSupported);
}
}
if let None = self.ctx {
// init adaptor ctx if it's not inited.
let encrypter = Crypter::new(cipher, Mode::Encrypt, &self.key, Some(&self.iv))?;
let adaptor_ctx = AdaptorCTX {
ctx: encrypter,
tag_set: false,
aad_set: false,
};
self.ctx = Some(adaptor_ctx);
}
if self.mode == CipherMode::GCM || self.mode == CipherMode::CCM {
// set additional authenticated data before doing real jobs.
if self.ctx.as_mut().unwrap().aad_set == false {
if let Some(aad) = &self.aad {
self.ctx.as_mut().unwrap().ctx.aad_update(aad)?;
self.ctx.as_mut().unwrap().aad_set = true;
}
}
}
// do real jobs.
// this Crypter::update returns a Result<usize, ErrorStack>, we simply ignore the detailed
// error information by unwrapping it.
// we also can't use the question mark operatior since the error codes are differently
// defined in RustyVault and underlying adaptor, such as rust-openssl.
let count = self
.ctx
.as_mut()
.unwrap()
.ctx
.update(&plaintext, &mut ciphertext[..])?;
Ok(count)
}
fn encrypt_final(&mut self, ciphertext: &mut Vec<u8>) -> Result<usize, RvError> {
// Unlike encrypt_update() function, we don't do auto-initialization here.
if self.ctx.is_none() {
return Err(RvError::ErrCryptoCipherNotInited);
}
let count = self.ctx.as_mut().unwrap().ctx.finalize(ciphertext)?;
if self.mode == CipherMode::GCM {
// set tag for caller to obtain.
if self.tag.is_some() {
// tag should not be set before encrypt_final() is called.
return Err(RvError::ErrCryptoCipherAEADTagPresent);
}
// 16-byte long is enough for all types of AEAD cipher tag.
let mut tag: Vec<u8> = vec![0; 16];
self.ctx.as_mut().unwrap().ctx.get_tag(&mut tag)?;
self.tag = Some(tag);
}
Ok(count)
}
fn decrypt(&mut self, ciphertext: &Vec<u8>) -> Result<Vec<u8>, RvError> {
match self.mode {
CipherMode::CBC => {
let plaintext = decrypt(Cipher::sm4_cbc(), &self.key, Some(&self.iv), ciphertext)?;
return Ok(plaintext.to_vec());
}
CipherMode::GCM => {
// SM4 is a fixed 128-bit cipher, the tag is 16-bytes long.
let plaintext = decrypt_aead(
Cipher::sm4_gcm(),
&self.key,
Some(&self.iv),
&self.aad.clone().unwrap(),
ciphertext,
&self.tag.clone().unwrap(),
)?;
return Ok(plaintext.to_vec());
}
_ => Err(RvError::ErrCryptoCipherOPNotSupported),
}
}
fn decrypt_update(
&mut self,
ciphertext: Vec<u8>,
plaintext: &mut Vec<u8>,
) -> Result<usize, RvError> {
let cipher;
match self.mode {
CipherMode::CBC => {
cipher = Cipher::sm4_cbc();
}
CipherMode::GCM => {
cipher = Cipher::sm4_gcm();
}
_ => {
return Err(RvError::ErrCryptoCipherOPNotSupported);
}
}
if self.ctx.is_none() {
// init adaptor ctx if it's not inited.
let encrypter = Crypter::new(cipher, Mode::Decrypt, &self.key, Some(&self.iv))?;
let adaptor_ctx = AdaptorCTX {
ctx: encrypter,
tag_set: false,
aad_set: false,
};
self.ctx = Some(adaptor_ctx);
}
// set additional authenticated data before doing real jobs.
if self.mode == CipherMode::GCM {
if self.ctx.as_mut().unwrap().aad_set == false {
if let Some(aad) = &self.aad {
self.ctx.as_mut().unwrap().ctx.aad_update(aad)?;
self.ctx.as_mut().unwrap().aad_set = true;
}
}
}
// do real jobs.
// this Crypter::update returns a Result<usize, ErrorStack>, print detailed error if any.
match self
.ctx
.as_mut()
.unwrap()
.ctx
.update(&ciphertext, plaintext)
{
Ok(count) => {
return Ok(count);
}
Err(err_stack) => {
let errs = err_stack.errors();
log::error!("{}", errs.len());
for err in errs.iter() {
log::error!("{:?}", err.reason());
}
Err(RvError::ErrCryptoCipherUpdateFailed)
}
}
}
fn decrypt_final(&mut self, plaintext: &mut Vec<u8>) -> Result<usize, RvError> {
// Unlike decrypt_update() function, we don't do auto-initialization here.
if self.ctx.is_none() {
return Err(RvError::ErrCryptoCipherNotInited);
}
// set tag before doing real jobs.
if self.mode == CipherMode::GCM {
if self.ctx.as_mut().unwrap().tag_set == false {
if let Some(tag) = &self.tag {
self.ctx.as_mut().unwrap().ctx.set_tag(tag)?;
self.ctx.as_mut().unwrap().tag_set = true;
} else {
// if tag is missing, then return an error.
return Err(RvError::ErrCryptoCipherNoTag);
}
}
}
match self.ctx.as_mut().unwrap().ctx.finalize(plaintext) {
Ok(count) => {
return Ok(count);
}
Err(err_stack) => {
let errs = err_stack.errors();
log::error!("{}", errs.len());
for err in errs.iter() {
log::error!("{:?}", err.reason());
}
Err(RvError::ErrCryptoCipherFinalizeFailed)
}
}
}
}
impl AEADCipher for SM4 {
fn set_aad(&mut self, aad: Vec<u8>) -> Result<(), RvError> {
self.aad = Some(aad.clone());
Ok(())
}
fn get_tag(&mut self) -> Result<Vec<u8>, RvError> {
if self.tag.is_none() {
return Err(RvError::ErrCryptoCipherNoTag);
}
Ok(self.tag.clone().unwrap())
}
fn set_tag(&mut self, tag: Vec<u8>) -> Result<(), RvError> {
self.tag = Some(tag.clone());
Ok(())
}
}