deno_crypto 0.264.0

Web Cryptography API implementation for Deno
Documentation
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
// Copyright 2018-2026 the Deno authors. MIT license.

use aes::cipher::BlockEncryptMut;
use aes::cipher::KeyIvInit;
use aes::cipher::StreamCipher;
use aes::cipher::block_padding::Pkcs7;
use aes_gcm::AeadInPlace;
use aes_gcm::KeyInit;
use aes_gcm::Nonce;
use aes_gcm::aead::generic_array::ArrayLength;
use aes_gcm::aead::generic_array::typenum::U12;
use aes_gcm::aead::generic_array::typenum::U16;
use aes_gcm::aes::Aes128;
use aes_gcm::aes::Aes192;
use aes_gcm::aes::Aes256;
use aws_lc_rs::aead::Aad;
use aws_lc_rs::aead::CHACHA20_POLY1305;
use aws_lc_rs::aead::LessSafeKey;
use aws_lc_rs::aead::Nonce as AwsNonce;
use aws_lc_rs::aead::UnboundKey;
use ctr::Ctr32BE;
use ctr::Ctr64BE;
use ctr::Ctr128BE;
use deno_core::JsBuffer;
use deno_core::convert::Uint8Array;
use deno_core::op2;
use deno_core::unsync::spawn_blocking;
use rand::rngs::OsRng;
use rsa::pkcs1::DecodeRsaPublicKey;
use serde::Deserialize;
use sha1::Sha1;
use sha2::Sha256;
use sha2::Sha384;
use sha2::Sha512;
use sha3::Sha3_256;
use sha3::Sha3_384;
use sha3::Sha3_512;

use crate::shared::*;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EncryptOptions {
  key: V8RawKeyData,
  #[serde(flatten)]
  algorithm: EncryptAlgorithm,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", tag = "algorithm")]
pub enum EncryptAlgorithm {
  #[serde(rename = "RSA-OAEP")]
  RsaOaep {
    hash: ShaHash,
    #[serde(with = "serde_bytes")]
    label: Vec<u8>,
  },
  #[serde(rename = "AES-CBC", rename_all = "camelCase")]
  AesCbc {
    #[serde(with = "serde_bytes")]
    iv: Vec<u8>,
    length: usize,
  },
  #[serde(rename = "AES-GCM", rename_all = "camelCase")]
  AesGcm {
    #[serde(with = "serde_bytes")]
    iv: Vec<u8>,
    #[serde(with = "serde_bytes")]
    additional_data: Option<Vec<u8>>,
    length: usize,
    tag_length: usize,
  },
  #[serde(rename = "AES-OCB", rename_all = "camelCase")]
  AesOcb {
    #[serde(with = "serde_bytes")]
    iv: Vec<u8>,
    #[serde(with = "serde_bytes")]
    additional_data: Option<Vec<u8>>,
    length: usize,
    tag_length: usize,
  },
  #[serde(rename = "AES-CTR", rename_all = "camelCase")]
  AesCtr {
    #[serde(with = "serde_bytes")]
    counter: Vec<u8>,
    ctr_length: usize,
    key_length: usize,
  },
  #[serde(rename = "ChaCha20-Poly1305", rename_all = "camelCase")]
  ChaCha20Poly1305 {
    #[serde(with = "serde_bytes")]
    nonce: Vec<u8>,
    #[serde(with = "serde_bytes")]
    additional_data: Option<Vec<u8>>,
  },
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
pub enum EncryptError {
  #[class(inherit)]
  #[error(transparent)]
  General(
    #[from]
    #[inherit]
    SharedError,
  ),
  #[class(type)]
  #[error("invalid length")]
  InvalidLength,
  #[class("DOMExceptionOperationError")]
  #[error("invalid key or iv")]
  InvalidKeyOrIv,
  #[class(type)]
  #[error("iv length not equal to 12 or 16")]
  InvalidIvLength,
  #[class(type)]
  #[error("invalid ChaCha20-Poly1305 nonce length: expected 12 bytes")]
  InvalidChaChaNonceLength,
  #[class(type)]
  #[error("invalid ChaCha20-Poly1305 key length: expected 32 bytes")]
  InvalidChaChaKeyLength,
  #[class(type)]
  #[error("invalid counter length. Currently supported 32/64/128 bits")]
  InvalidCounterLength,
  #[class("DOMExceptionOperationError")]
  #[error("tried to encrypt too much data")]
  TooMuchData,
  #[class("DOMExceptionOperationError")]
  #[error("Encryption failed")]
  Failed,
}

#[op2]
pub async fn op_crypto_encrypt(
  #[serde] opts: EncryptOptions,
  #[buffer] data: JsBuffer,
) -> Result<Uint8Array, EncryptError> {
  let key = opts.key;
  let fun = move || match opts.algorithm {
    EncryptAlgorithm::RsaOaep { hash, label } => {
      encrypt_rsa_oaep(key, hash, label, &data)
    }
    EncryptAlgorithm::AesCbc { iv, length } => {
      encrypt_aes_cbc(key, length, iv, &data)
    }
    EncryptAlgorithm::AesGcm {
      iv,
      additional_data,
      length,
      tag_length,
    } => encrypt_aes_gcm(key, length, tag_length, iv, additional_data, &data),
    EncryptAlgorithm::AesOcb {
      iv,
      additional_data,
      length,
      tag_length,
    } => encrypt_aes_ocb(key, length, tag_length, iv, additional_data, &data),
    EncryptAlgorithm::AesCtr {
      counter,
      ctr_length,
      key_length,
    } => encrypt_aes_ctr(key, key_length, &counter, ctr_length, &data),
    EncryptAlgorithm::ChaCha20Poly1305 {
      nonce,
      additional_data,
    } => encrypt_chacha20_poly1305(key, &nonce, additional_data, &data),
  };
  let buf = spawn_blocking(fun).await.unwrap()?;
  Ok(buf.into())
}

fn encrypt_rsa_oaep(
  key: V8RawKeyData,
  hash: ShaHash,
  label: Vec<u8>,
  data: &[u8],
) -> Result<Vec<u8>, EncryptError> {
  let label = String::from_utf8_lossy(&label).to_string();

  let public_key = key.as_rsa_public_key()?;
  let public_key = rsa::RsaPublicKey::from_pkcs1_der(&public_key)
    .map_err(|_| SharedError::FailedDecodePublicKey)?;
  let mut rng = OsRng;
  let padding = match hash {
    ShaHash::Sha1 => rsa::Oaep {
      digest: Box::<Sha1>::default(),
      mgf_digest: Box::<Sha1>::default(),
      label: Some(label),
    },
    ShaHash::Sha256 => rsa::Oaep {
      digest: Box::<Sha256>::default(),
      mgf_digest: Box::<Sha256>::default(),
      label: Some(label),
    },
    ShaHash::Sha384 => rsa::Oaep {
      digest: Box::<Sha384>::default(),
      mgf_digest: Box::<Sha384>::default(),
      label: Some(label),
    },
    ShaHash::Sha512 => rsa::Oaep {
      digest: Box::<Sha512>::default(),
      mgf_digest: Box::<Sha512>::default(),
      label: Some(label),
    },
    ShaHash::Sha3_256 => rsa::Oaep {
      digest: Box::<Sha3_256>::default(),
      mgf_digest: Box::<Sha3_256>::default(),
      label: Some(label),
    },
    ShaHash::Sha3_384 => rsa::Oaep {
      digest: Box::<Sha3_384>::default(),
      mgf_digest: Box::<Sha3_384>::default(),
      label: Some(label),
    },
    ShaHash::Sha3_512 => rsa::Oaep {
      digest: Box::<Sha3_512>::default(),
      mgf_digest: Box::<Sha3_512>::default(),
      label: Some(label),
    },
  };
  let encrypted = public_key
    .encrypt(&mut rng, padding, data)
    .map_err(|_| EncryptError::Failed)?;
  Ok(encrypted)
}

fn encrypt_aes_cbc(
  key: V8RawKeyData,
  length: usize,
  iv: Vec<u8>,
  data: &[u8],
) -> Result<Vec<u8>, EncryptError> {
  let key = key.as_secret_key()?;
  let ciphertext = match length {
    128 => {
      // Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
      type Aes128CbcEnc = cbc::Encryptor<aes::Aes128>;

      let cipher = Aes128CbcEnc::new_from_slices(key, &iv)
        .map_err(|_| EncryptError::InvalidKeyOrIv)?;
      cipher.encrypt_padded_vec_mut::<Pkcs7>(data)
    }
    192 => {
      // Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
      type Aes192CbcEnc = cbc::Encryptor<aes::Aes192>;

      let cipher = Aes192CbcEnc::new_from_slices(key, &iv)
        .map_err(|_| EncryptError::InvalidKeyOrIv)?;
      cipher.encrypt_padded_vec_mut::<Pkcs7>(data)
    }
    256 => {
      // Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
      type Aes256CbcEnc = cbc::Encryptor<aes::Aes256>;

      let cipher = Aes256CbcEnc::new_from_slices(key, &iv)
        .map_err(|_| EncryptError::InvalidKeyOrIv)?;
      cipher.encrypt_padded_vec_mut::<Pkcs7>(data)
    }
    _ => return Err(EncryptError::InvalidLength),
  };
  Ok(ciphertext)
}

fn encrypt_aes_gcm_general<N: ArrayLength<u8>>(
  key: &[u8],
  iv: Vec<u8>,
  length: usize,
  ciphertext: &mut [u8],
  additional_data: Vec<u8>,
) -> Result<aes_gcm::Tag, EncryptError> {
  let nonce = Nonce::<N>::from_slice(&iv);
  let tag = match length {
    128 => {
      let cipher = aes_gcm::AesGcm::<Aes128, N>::new_from_slice(key)
        .map_err(|_| EncryptError::Failed)?;
      cipher
        .encrypt_in_place_detached(nonce, &additional_data, ciphertext)
        .map_err(|_| EncryptError::Failed)?
    }
    192 => {
      let cipher = aes_gcm::AesGcm::<Aes192, N>::new_from_slice(key)
        .map_err(|_| EncryptError::Failed)?;
      cipher
        .encrypt_in_place_detached(nonce, &additional_data, ciphertext)
        .map_err(|_| EncryptError::Failed)?
    }
    256 => {
      let cipher = aes_gcm::AesGcm::<Aes256, N>::new_from_slice(key)
        .map_err(|_| EncryptError::Failed)?;
      cipher
        .encrypt_in_place_detached(nonce, &additional_data, ciphertext)
        .map_err(|_| EncryptError::Failed)?
    }
    _ => return Err(EncryptError::InvalidLength),
  };

  Ok(tag)
}

fn encrypt_aes_gcm(
  key: V8RawKeyData,
  length: usize,
  tag_length: usize,
  iv: Vec<u8>,
  additional_data: Option<Vec<u8>>,
  data: &[u8],
) -> Result<Vec<u8>, EncryptError> {
  let key = key.as_secret_key()?;
  let additional_data = additional_data.unwrap_or_default();

  let mut ciphertext = data.to_vec();
  // Fixed 96-bit OR 128-bit nonce
  let tag = match iv.len() {
    12 => encrypt_aes_gcm_general::<U12>(
      key,
      iv,
      length,
      &mut ciphertext,
      additional_data,
    )?,
    16 => encrypt_aes_gcm_general::<U16>(
      key,
      iv,
      length,
      &mut ciphertext,
      additional_data,
    )?,
    _ => return Err(EncryptError::InvalidIvLength),
  };

  // Truncated tag to the specified tag length.
  // `tag` is fixed to be 16 bytes long and (tag_length / 8) is always <= 16
  let tag = &tag[..(tag_length / 8)];

  // C | T
  ciphertext.extend_from_slice(tag);

  Ok(ciphertext)
}

fn encrypt_aes_ocb(
  key: V8RawKeyData,
  length: usize,
  tag_length: usize,
  iv: Vec<u8>,
  additional_data: Option<Vec<u8>>,
  data: &[u8],
) -> Result<Vec<u8>, EncryptError> {
  use aes_gcm::aead::generic_array::GenericArray;
  use ocb3::Ocb3;
  use ocb3::aead::AeadInPlace as Ocb3AeadInPlace;
  use ocb3::aead::KeyInit as Ocb3KeyInit;

  let key = key.as_secret_key()?;
  let additional_data = additional_data.unwrap_or_default();

  let mut ciphertext = data.to_vec();

  // OCB supports nonce sizes from 1 to 15 bytes (recommended: 12 bytes)
  if iv.is_empty() || iv.len() > 15 {
    return Err(EncryptError::InvalidIvLength);
  }

  let nonce = GenericArray::from_slice(&iv);

  let tag = match length {
    128 => {
      let cipher = Ocb3::<aes::Aes128>::new_from_slice(key)
        .map_err(|_| EncryptError::Failed)?;
      cipher
        .encrypt_in_place_detached(nonce, &additional_data, &mut ciphertext)
        .map_err(|_| EncryptError::Failed)?
    }
    192 => {
      let cipher = Ocb3::<aes::Aes192>::new_from_slice(key)
        .map_err(|_| EncryptError::Failed)?;
      cipher
        .encrypt_in_place_detached(nonce, &additional_data, &mut ciphertext)
        .map_err(|_| EncryptError::Failed)?
    }
    256 => {
      let cipher = Ocb3::<aes::Aes256>::new_from_slice(key)
        .map_err(|_| EncryptError::Failed)?;
      cipher
        .encrypt_in_place_detached(nonce, &additional_data, &mut ciphertext)
        .map_err(|_| EncryptError::Failed)?
    }
    _ => return Err(EncryptError::InvalidLength),
  };

  // Truncate tag to the specified tag length
  // OCB tag is 16 bytes by default
  let tag = &tag[..(tag_length / 8)];

  // C | T
  ciphertext.extend_from_slice(tag);

  Ok(ciphertext)
}

fn encrypt_chacha20_poly1305(
  key: V8RawKeyData,
  nonce: &[u8],
  additional_data: Option<Vec<u8>>,
  data: &[u8],
) -> Result<Vec<u8>, EncryptError> {
  let key_bytes = key.as_secret_key()?;
  if key_bytes.len() != 32 {
    return Err(EncryptError::InvalidChaChaKeyLength);
  }
  if nonce.len() != 12 {
    return Err(EncryptError::InvalidChaChaNonceLength);
  }
  // RFC 8439 caps plaintext length per nonce at 2^32 * 64 - 64 bytes.
  if data.len() as u64 > ((1u64 << 32) - 1) * 64 {
    return Err(EncryptError::TooMuchData);
  }

  let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, key_bytes)
    .map_err(|_| EncryptError::Failed)?;
  let sealing_key = LessSafeKey::new(unbound_key);
  let aws_nonce = AwsNonce::try_assume_unique_for_key(nonce)
    .map_err(|_| EncryptError::Failed)?;
  let aad = additional_data.unwrap_or_default();

  let mut in_out = data.to_vec();
  sealing_key
    .seal_in_place_append_tag(aws_nonce, Aad::from(&aad), &mut in_out)
    .map_err(|_| EncryptError::Failed)?;

  Ok(in_out)
}

fn encrypt_aes_ctr_gen<B>(
  key: &[u8],
  counter: &[u8],
  data: &[u8],
) -> Result<Vec<u8>, EncryptError>
where
  B: KeyIvInit + StreamCipher,
{
  let mut cipher = B::new(key.into(), counter.into());

  let mut ciphertext = data.to_vec();
  cipher
    .try_apply_keystream(&mut ciphertext)
    .map_err(|_| EncryptError::TooMuchData)?;

  Ok(ciphertext)
}

fn encrypt_aes_ctr(
  key: V8RawKeyData,
  key_length: usize,
  counter: &[u8],
  ctr_length: usize,
  data: &[u8],
) -> Result<Vec<u8>, EncryptError> {
  let key = key.as_secret_key()?;

  match ctr_length {
    32 => match key_length {
      128 => encrypt_aes_ctr_gen::<Ctr32BE<aes::Aes128>>(key, counter, data),
      192 => encrypt_aes_ctr_gen::<Ctr32BE<aes::Aes192>>(key, counter, data),
      256 => encrypt_aes_ctr_gen::<Ctr32BE<aes::Aes256>>(key, counter, data),
      _ => Err(EncryptError::InvalidLength),
    },
    64 => match key_length {
      128 => encrypt_aes_ctr_gen::<Ctr64BE<aes::Aes128>>(key, counter, data),
      192 => encrypt_aes_ctr_gen::<Ctr64BE<aes::Aes192>>(key, counter, data),
      256 => encrypt_aes_ctr_gen::<Ctr64BE<aes::Aes256>>(key, counter, data),
      _ => Err(EncryptError::InvalidLength),
    },
    128 => match key_length {
      128 => encrypt_aes_ctr_gen::<Ctr128BE<aes::Aes128>>(key, counter, data),
      192 => encrypt_aes_ctr_gen::<Ctr128BE<aes::Aes192>>(key, counter, data),
      256 => encrypt_aes_ctr_gen::<Ctr128BE<aes::Aes256>>(key, counter, data),
      _ => Err(EncryptError::InvalidLength),
    },
    _ => Err(EncryptError::InvalidCounterLength),
  }
}