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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use aes::cipher::block_padding::Pkcs7;
use aes::cipher::BlockDecryptMut;
use aes::cipher::BlockEncryptMut;
use aes::cipher::KeyIvInit;
use deno_core::error::range_error;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::Resource;
use digest::generic_array::GenericArray;
use digest::KeyInit;
use std::borrow::Cow;
use std::cell::RefCell;
use std::rc::Rc;
type Tag = Option<Vec<u8>>;
type Aes128Gcm = aead_gcm_stream::AesGcm<aes::Aes128>;
type Aes256Gcm = aead_gcm_stream::AesGcm<aes::Aes256>;
enum Cipher {
Aes128Cbc(Box<cbc::Encryptor<aes::Aes128>>),
Aes128Ecb(Box<ecb::Encryptor<aes::Aes128>>),
Aes192Ecb(Box<ecb::Encryptor<aes::Aes192>>),
Aes256Ecb(Box<ecb::Encryptor<aes::Aes256>>),
Aes128Gcm(Box<Aes128Gcm>),
Aes256Gcm(Box<Aes256Gcm>),
Aes256Cbc(Box<cbc::Encryptor<aes::Aes256>>),
// TODO(kt3k): add more algorithms Aes192Cbc, etc.
}
enum Decipher {
Aes128Cbc(Box<cbc::Decryptor<aes::Aes128>>),
Aes128Ecb(Box<ecb::Decryptor<aes::Aes128>>),
Aes192Ecb(Box<ecb::Decryptor<aes::Aes192>>),
Aes256Ecb(Box<ecb::Decryptor<aes::Aes256>>),
Aes128Gcm(Box<Aes128Gcm>),
Aes256Gcm(Box<Aes256Gcm>),
Aes256Cbc(Box<cbc::Decryptor<aes::Aes256>>),
// TODO(kt3k): add more algorithms Aes192Cbc, Aes128GCM, etc.
}
pub struct CipherContext {
cipher: Rc<RefCell<Cipher>>,
}
pub struct DecipherContext {
decipher: Rc<RefCell<Decipher>>,
}
impl CipherContext {
pub fn new(algorithm: &str, key: &[u8], iv: &[u8]) -> Result<Self, AnyError> {
Ok(Self {
cipher: Rc::new(RefCell::new(Cipher::new(algorithm, key, iv)?)),
})
}
pub fn set_aad(&self, aad: &[u8]) {
self.cipher.borrow_mut().set_aad(aad);
}
pub fn encrypt(&self, input: &[u8], output: &mut [u8]) {
self.cipher.borrow_mut().encrypt(input, output);
}
pub fn take_tag(self) -> Tag {
Rc::try_unwrap(self.cipher).ok()?.into_inner().take_tag()
}
pub fn r#final(
self,
auto_pad: bool,
input: &[u8],
output: &mut [u8],
) -> Result<Tag, AnyError> {
Rc::try_unwrap(self.cipher)
.map_err(|_| type_error("Cipher context is already in use"))?
.into_inner()
.r#final(auto_pad, input, output)
}
}
impl DecipherContext {
pub fn new(algorithm: &str, key: &[u8], iv: &[u8]) -> Result<Self, AnyError> {
Ok(Self {
decipher: Rc::new(RefCell::new(Decipher::new(algorithm, key, iv)?)),
})
}
pub fn set_aad(&self, aad: &[u8]) {
self.decipher.borrow_mut().set_aad(aad);
}
pub fn decrypt(&self, input: &[u8], output: &mut [u8]) {
self.decipher.borrow_mut().decrypt(input, output);
}
pub fn r#final(
self,
auto_pad: bool,
input: &[u8],
output: &mut [u8],
auth_tag: &[u8],
) -> Result<(), AnyError> {
Rc::try_unwrap(self.decipher)
.map_err(|_| type_error("Decipher context is already in use"))?
.into_inner()
.r#final(auto_pad, input, output, auth_tag)
}
}
impl Resource for CipherContext {
fn name(&self) -> Cow<str> {
"cryptoCipher".into()
}
}
impl Resource for DecipherContext {
fn name(&self) -> Cow<str> {
"cryptoDecipher".into()
}
}
impl Cipher {
fn new(
algorithm_name: &str,
key: &[u8],
iv: &[u8],
) -> Result<Self, AnyError> {
use Cipher::*;
Ok(match algorithm_name {
"aes-128-cbc" => {
Aes128Cbc(Box::new(cbc::Encryptor::new(key.into(), iv.into())))
}
"aes-128-ecb" => Aes128Ecb(Box::new(ecb::Encryptor::new(key.into()))),
"aes-192-ecb" => Aes192Ecb(Box::new(ecb::Encryptor::new(key.into()))),
"aes-256-ecb" => Aes256Ecb(Box::new(ecb::Encryptor::new(key.into()))),
"aes-128-gcm" => {
if iv.len() != 12 {
return Err(type_error("IV length must be 12 bytes"));
}
let cipher =
aead_gcm_stream::AesGcm::<aes::Aes128>::new(key.into(), iv);
Aes128Gcm(Box::new(cipher))
}
"aes-256-gcm" => {
if iv.len() != 12 {
return Err(type_error("IV length must be 12 bytes"));
}
let cipher =
aead_gcm_stream::AesGcm::<aes::Aes256>::new(key.into(), iv);
Aes256Gcm(Box::new(cipher))
}
"aes256" | "aes-256-cbc" => {
if key.len() != 32 {
return Err(range_error("Invalid key length"));
}
if iv.len() != 16 {
return Err(type_error("Invalid initialization vector"));
}
Aes256Cbc(Box::new(cbc::Encryptor::new(key.into(), iv.into())))
}
_ => return Err(type_error(format!("Unknown cipher {algorithm_name}"))),
})
}
fn set_aad(&mut self, aad: &[u8]) {
use Cipher::*;
match self {
Aes128Gcm(cipher) => {
cipher.set_aad(aad);
}
Aes256Gcm(cipher) => {
cipher.set_aad(aad);
}
_ => {}
}
}
/// encrypt encrypts the data in the middle of the input.
fn encrypt(&mut self, input: &[u8], output: &mut [u8]) {
use Cipher::*;
match self {
Aes128Cbc(encryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
encryptor.encrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes128Ecb(encryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
encryptor.encrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes192Ecb(encryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
encryptor.encrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes256Ecb(encryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
encryptor.encrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes128Gcm(cipher) => {
output[..input.len()].copy_from_slice(input);
cipher.encrypt(output);
}
Aes256Gcm(cipher) => {
output[..input.len()].copy_from_slice(input);
cipher.encrypt(output);
}
Aes256Cbc(encryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
encryptor.encrypt_block_b2b_mut(input.into(), output.into());
}
}
}
}
/// r#final encrypts the last block of the input data.
fn r#final(
self,
auto_pad: bool,
input: &[u8],
output: &mut [u8],
) -> Result<Tag, AnyError> {
assert!(input.len() < 16);
use Cipher::*;
match (self, auto_pad) {
(Aes128Cbc(encryptor), true) => {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Ok(None)
}
(Aes128Cbc(mut encryptor), false) => {
encryptor.encrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(None)
}
(Aes128Ecb(encryptor), true) => {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Ok(None)
}
(Aes128Ecb(mut encryptor), false) => {
encryptor.encrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(None)
}
(Aes192Ecb(encryptor), true) => {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Ok(None)
}
(Aes192Ecb(mut encryptor), false) => {
encryptor.encrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(None)
}
(Aes256Ecb(encryptor), true) => {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Ok(None)
}
(Aes256Ecb(mut encryptor), false) => {
encryptor.encrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(None)
}
(Aes128Gcm(cipher), _) => Ok(Some(cipher.finish().to_vec())),
(Aes256Gcm(cipher), _) => Ok(Some(cipher.finish().to_vec())),
(Aes256Cbc(encryptor), true) => {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Ok(None)
}
(Aes256Cbc(mut encryptor), false) => {
encryptor.encrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(None)
}
}
}
fn take_tag(self) -> Tag {
use Cipher::*;
match self {
Aes128Gcm(cipher) => Some(cipher.finish().to_vec()),
Aes256Gcm(cipher) => Some(cipher.finish().to_vec()),
_ => None,
}
}
}
impl Decipher {
fn new(
algorithm_name: &str,
key: &[u8],
iv: &[u8],
) -> Result<Self, AnyError> {
use Decipher::*;
Ok(match algorithm_name {
"aes-128-cbc" => {
Aes128Cbc(Box::new(cbc::Decryptor::new(key.into(), iv.into())))
}
"aes-128-ecb" => Aes128Ecb(Box::new(ecb::Decryptor::new(key.into()))),
"aes-192-ecb" => Aes192Ecb(Box::new(ecb::Decryptor::new(key.into()))),
"aes-256-ecb" => Aes256Ecb(Box::new(ecb::Decryptor::new(key.into()))),
"aes-128-gcm" => {
if iv.len() != 12 {
return Err(type_error("IV length must be 12 bytes"));
}
let decipher =
aead_gcm_stream::AesGcm::<aes::Aes128>::new(key.into(), iv);
Aes128Gcm(Box::new(decipher))
}
"aes-256-gcm" => {
if iv.len() != 12 {
return Err(type_error("IV length must be 12 bytes"));
}
let decipher =
aead_gcm_stream::AesGcm::<aes::Aes256>::new(key.into(), iv);
Aes256Gcm(Box::new(decipher))
}
"aes256" | "aes-256-cbc" => {
if key.len() != 32 {
return Err(range_error("Invalid key length"));
}
if iv.len() != 16 {
return Err(type_error("Invalid initialization vector"));
}
Aes256Cbc(Box::new(cbc::Decryptor::new(key.into(), iv.into())))
}
_ => return Err(type_error(format!("Unknown cipher {algorithm_name}"))),
})
}
fn set_aad(&mut self, aad: &[u8]) {
use Decipher::*;
match self {
Aes128Gcm(decipher) => {
decipher.set_aad(aad);
}
Aes256Gcm(decipher) => {
decipher.set_aad(aad);
}
_ => {}
}
}
/// decrypt decrypts the data in the middle of the input.
fn decrypt(&mut self, input: &[u8], output: &mut [u8]) {
use Decipher::*;
match self {
Aes128Cbc(decryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
decryptor.decrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes128Ecb(decryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
decryptor.decrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes192Ecb(decryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
decryptor.decrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes256Ecb(decryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
decryptor.decrypt_block_b2b_mut(input.into(), output.into());
}
}
Aes128Gcm(decipher) => {
output[..input.len()].copy_from_slice(input);
decipher.decrypt(output);
}
Aes256Gcm(decipher) => {
output[..input.len()].copy_from_slice(input);
decipher.decrypt(output);
}
Aes256Cbc(decryptor) => {
assert!(input.len() % 16 == 0);
for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) {
decryptor.decrypt_block_b2b_mut(input.into(), output.into());
}
}
}
}
/// r#final decrypts the last block of the input data.
fn r#final(
self,
auto_pad: bool,
input: &[u8],
output: &mut [u8],
auth_tag: &[u8],
) -> Result<(), AnyError> {
use Decipher::*;
match (self, auto_pad) {
(Aes128Cbc(decryptor), true) => {
assert!(input.len() == 16);
let _ = (*decryptor)
.decrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot unpad the input data"))?;
Ok(())
}
(Aes128Cbc(mut decryptor), false) => {
decryptor.decrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(())
}
(Aes128Ecb(decryptor), true) => {
assert!(input.len() == 16);
let _ = (*decryptor)
.decrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot unpad the input data"))?;
Ok(())
}
(Aes128Ecb(mut decryptor), false) => {
decryptor.decrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(())
}
(Aes192Ecb(decryptor), true) => {
assert!(input.len() == 16);
let _ = (*decryptor)
.decrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot unpad the input data"))?;
Ok(())
}
(Aes192Ecb(mut decryptor), false) => {
decryptor.decrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(())
}
(Aes256Ecb(decryptor), true) => {
assert!(input.len() == 16);
let _ = (*decryptor)
.decrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot unpad the input data"))?;
Ok(())
}
(Aes256Ecb(mut decryptor), false) => {
decryptor.decrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(())
}
(Aes128Gcm(decipher), true) => {
let tag = decipher.finish();
if tag.as_slice() == auth_tag {
Ok(())
} else {
Err(type_error("Failed to authenticate data"))
}
}
(Aes128Gcm(_), false) => Err(type_error(
"setAutoPadding(false) not supported for Aes256Gcm yet",
)),
(Aes256Gcm(decipher), true) => {
let tag = decipher.finish();
if tag.as_slice() == auth_tag {
Ok(())
} else {
Err(type_error("Failed to authenticate data"))
}
}
(Aes256Gcm(_), false) => Err(type_error(
"setAutoPadding(false) not supported for Aes256Gcm yet",
)),
(Aes256Cbc(decryptor), true) => {
assert!(input.len() == 16);
let _ = (*decryptor)
.decrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot unpad the input data"))?;
Ok(())
}
(Aes256Cbc(mut decryptor), false) => {
decryptor.decrypt_block_b2b_mut(
GenericArray::from_slice(input),
GenericArray::from_mut_slice(output),
);
Ok(())
}
}
}
}
|