GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_cipher.cc Lines: 483 527 91.7 %
Date: 2022-05-03 04:14:50 Branches: 322 422 76.3 %

Line Branch Exec Source
1
#include "crypto/crypto_cipher.h"
2
#include "crypto/crypto_util.h"
3
#include "allocated_buffer-inl.h"
4
#include "base_object-inl.h"
5
#include "env-inl.h"
6
#include "memory_tracker-inl.h"
7
#include "node_buffer.h"
8
#include "node_internals.h"
9
#include "node_process-inl.h"
10
#include "v8.h"
11
12
namespace node {
13
14
using v8::Array;
15
using v8::ArrayBuffer;
16
using v8::BackingStore;
17
using v8::FunctionCallbackInfo;
18
using v8::FunctionTemplate;
19
using v8::HandleScope;
20
using v8::Int32;
21
using v8::Local;
22
using v8::Object;
23
using v8::Uint32;
24
using v8::Value;
25
26
namespace crypto {
27
namespace {
28
4742
bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
29
4742
  switch (EVP_CIPHER_mode(cipher)) {
30
1857
  case EVP_CIPH_CCM_MODE:
31
  case EVP_CIPH_GCM_MODE:
32
#ifndef OPENSSL_NO_OCB
33
  case EVP_CIPH_OCB_MODE:
34
#endif
35
1857
    return true;
36
1747
  case EVP_CIPH_STREAM_CIPHER:
37
1747
    return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305;
38
1138
  default:
39
1138
    return false;
40
  }
41
}
42
43
2442
bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
44
2442
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
45
2442
  return IsSupportedAuthenticatedMode(cipher);
46
}
47
48
66
bool IsValidGCMTagLength(unsigned int tag_len) {
49


66
  return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16);
50
}
51
52
// Collects and returns information on the given cipher
53
425
void GetCipherInfo(const FunctionCallbackInfo<Value>& args) {
54
425
  Environment* env = Environment::GetCurrent(args);
55
425
  CHECK(args[0]->IsObject());
56
850
  Local<Object> info = args[0].As<Object>();
57
58

982
  CHECK(args[1]->IsString() || args[1]->IsInt32());
59
60
  const EVP_CIPHER* cipher;
61
850
  if (args[1]->IsString()) {
62
586
    Utf8Value name(env->isolate(), args[1]);
63
293
    cipher = EVP_get_cipherbyname(*name);
64
  } else {
65
264
    int nid = args[1].As<Int32>()->Value();
66
132
    cipher = EVP_get_cipherbynid(nid);
67
  }
68
69
425
  if (cipher == nullptr)
70
7
    return;
71
72
423
  int mode = EVP_CIPHER_mode(cipher);
73
423
  int iv_length = EVP_CIPHER_iv_length(cipher);
74
423
  int key_length = EVP_CIPHER_key_length(cipher);
75
423
  int block_length = EVP_CIPHER_block_size(cipher);
76
423
  const char* mode_label = nullptr;
77



423
  switch (mode) {
78
86
    case EVP_CIPH_CBC_MODE: mode_label = "cbc"; break;
79
36
    case EVP_CIPH_CCM_MODE: mode_label = "ccm"; break;
80
96
    case EVP_CIPH_CFB_MODE: mode_label = "cfb"; break;
81
30
    case EVP_CIPH_CTR_MODE: mode_label = "ctr"; break;
82
42
    case EVP_CIPH_ECB_MODE: mode_label = "ecb"; break;
83
27
    case EVP_CIPH_GCM_MODE: mode_label = "gcm"; break;
84
25
    case EVP_CIPH_OCB_MODE: mode_label = "ocb"; break;
85
36
    case EVP_CIPH_OFB_MODE: mode_label = "ofb"; break;
86
33
    case EVP_CIPH_WRAP_MODE: mode_label = "wrap"; break;
87
6
    case EVP_CIPH_XTS_MODE: mode_label = "xts"; break;
88
6
    case EVP_CIPH_STREAM_CIPHER: mode_label = "stream"; break;
89
  }
90
91
  // If the testKeyLen and testIvLen arguments are specified,
92
  // then we will make an attempt to see if they are usable for
93
  // the cipher in question, returning undefined if they are not.
94
  // If they are, the info object will be returned with the values
95
  // given.
96

844
  if (args[2]->IsInt32() || args[3]->IsInt32()) {
97
    // Test and input IV or key length to determine if it's acceptable.
98
    // If it is, then the getCipherInfo will succeed with the given
99
    // values.
100
29
    CipherCtxPointer ctx(EVP_CIPHER_CTX_new());
101
29
    if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr, nullptr, nullptr, 1))
102
      return;
103
104
29
    if (args[2]->IsInt32()) {
105
4
      int check_len = args[2].As<Int32>()->Value();
106
2
      if (!EVP_CIPHER_CTX_set_key_length(ctx.get(), check_len))
107
1
        return;
108
1
      key_length = check_len;
109
    }
110
111
28
    if (args[3]->IsInt32()) {
112
54
      int check_len = args[3].As<Int32>()->Value();
113
      // For CCM modes, the IV may be between 7 and 13 bytes.
114
      // For GCM and OCB modes, we'll check by attempting to
115
      // set the value. For everything else, just check that
116
      // check_len == iv_length.
117
27
      switch (mode) {
118
9
        case EVP_CIPH_CCM_MODE:
119

9
          if (check_len < 7 || check_len > 13)
120
2
            return;
121
7
          break;
122
16
        case EVP_CIPH_GCM_MODE:
123
          // Fall through
124
        case EVP_CIPH_OCB_MODE:
125
16
          if (!EVP_CIPHER_CTX_ctrl(
126
                  ctx.get(),
127
                  EVP_CTRL_AEAD_SET_IVLEN,
128
                  check_len,
129
                  nullptr)) {
130
1
            return;
131
          }
132
15
          break;
133
2
        default:
134
2
          if (check_len != iv_length)
135
1
            return;
136
      }
137
23
      iv_length = check_len;
138
    }
139
  }
140
141
836
  if (mode_label != nullptr &&
142
418
      info->Set(
143
          env->context(),
144
          FIXED_ONE_BYTE_STRING(env->isolate(), "mode"),
145

2090
          OneByteString(env->isolate(), mode_label)).IsNothing()) {
146
    return;
147
  }
148
149
  // OBJ_nid2sn(EVP_CIPHER_nid(cipher)) is used here instead of
150
  // EVP_CIPHER_name(cipher) for compatibility with BoringSSL.
151
836
  if (info->Set(
152
          env->context(),
153
          env->name_string(),
154
          OneByteString(
155
            env->isolate(),
156
1672
            OBJ_nid2sn(EVP_CIPHER_nid(cipher)))).IsNothing()) {
157
    return;
158
  }
159
160
836
  if (info->Set(
161
          env->context(),
162
          FIXED_ONE_BYTE_STRING(env->isolate(), "nid"),
163
1672
          Int32::New(env->isolate(), EVP_CIPHER_nid(cipher))).IsNothing()) {
164
    return;
165
  }
166
167
  // Stream ciphers do not have a meaningful block size
168
830
  if (mode != EVP_CIPH_STREAM_CIPHER &&
169
418
      info->Set(
170
          env->context(),
171
          FIXED_ONE_BYTE_STRING(env->isolate(), "blockSize"),
172

2066
          Int32::New(env->isolate(), block_length)).IsNothing()) {
173
    return;
174
  }
175
176
  // Ciphers that do not use an IV shouldn't report a length
177
788
  if (iv_length != 0 &&
178
418
      info->Set(
179
          env->context(),
180
          FIXED_ONE_BYTE_STRING(env->isolate(), "ivLength"),
181

1898
          Int32::New(env->isolate(), iv_length)).IsNothing()) {
182
    return;
183
  }
184
185
836
  if (info->Set(
186
          env->context(),
187
          FIXED_ONE_BYTE_STRING(env->isolate(), "keyLength"),
188
1672
          Int32::New(env->isolate(), key_length)).IsNothing()) {
189
    return;
190
  }
191
192
836
  args.GetReturnValue().Set(info);
193
}
194
}  // namespace
195
196
1
void CipherBase::GetSSLCiphers(const FunctionCallbackInfo<Value>& args) {
197
1
  Environment* env = Environment::GetCurrent(args);
198
199
1
  SSLCtxPointer ctx(SSL_CTX_new(TLS_method()));
200
1
  if (!ctx) {
201
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_new");
202
  }
203
204
1
  SSLPointer ssl(SSL_new(ctx.get()));
205
1
  if (!ssl) {
206
    return ThrowCryptoError(env, ERR_get_error(), "SSL_new");
207
  }
208
209
1
  STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl.get());
210
211
  // TLSv1.3 ciphers aren't listed by EVP. There are only 5, we could just
212
  // document them, but since there are only 5, easier to just add them manually
213
  // and not have to explain their absence in the API docs. They are lower-cased
214
  // because the docs say they will be.
215
  static const char* TLS13_CIPHERS[] = {
216
    "tls_aes_256_gcm_sha384",
217
    "tls_chacha20_poly1305_sha256",
218
    "tls_aes_128_gcm_sha256",
219
    "tls_aes_128_ccm_8_sha256",
220
    "tls_aes_128_ccm_sha256"
221
  };
222
223
1
  const int n = sk_SSL_CIPHER_num(ciphers);
224
1
  std::vector<Local<Value>> arr(n + arraysize(TLS13_CIPHERS));
225
226
61
  for (int i = 0; i < n; ++i) {
227
60
    const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
228
120
    arr[i] = OneByteString(env->isolate(), SSL_CIPHER_get_name(cipher));
229
  }
230
231
6
  for (unsigned i = 0; i < arraysize(TLS13_CIPHERS); ++i) {
232
5
    const char* name = TLS13_CIPHERS[i];
233
10
    arr[n + i] = OneByteString(env->isolate(), name);
234
  }
235
236
2
  args.GetReturnValue().Set(Array::New(env->isolate(), arr.data(), arr.size()));
237
}
238
239
3
void CipherBase::GetCiphers(const FunctionCallbackInfo<Value>& args) {
240
3
  Environment* env = Environment::GetCurrent(args);
241
6
  MarkPopErrorOnReturn mark_pop_error_on_return;
242
3
  CipherPushContext ctx(env);
243
3
  EVP_CIPHER_do_all_sorted(
244
#if OPENSSL_VERSION_MAJOR >= 3
245
    array_push_back<EVP_CIPHER,
246
                    EVP_CIPHER_fetch,
247
                    EVP_CIPHER_free,
248
                    EVP_get_cipherbyname,
249
                    EVP_CIPHER_get0_name>,
250
#else
251
    array_push_back<EVP_CIPHER>,
252
#endif
253
    &ctx);
254
6
  args.GetReturnValue().Set(ctx.ToJSArray());
255
3
}
256
257
1483
CipherBase::CipherBase(Environment* env,
258
                       Local<Object> wrap,
259
1483
                       CipherKind kind)
260
    : BaseObject(env, wrap),
261
      ctx_(nullptr),
262
      kind_(kind),
263
      auth_tag_state_(kAuthTagUnknown),
264
      auth_tag_len_(kNoAuthTagLength),
265
1483
      pending_auth_failed_(false) {
266
1483
  MakeWeak();
267
1483
}
268
269
void CipherBase::MemoryInfo(MemoryTracker* tracker) const {
270
  tracker->TrackFieldWithSize("context", ctx_ ? kSizeOf_EVP_CIPHER_CTX : 0);
271
}
272
273
628
void CipherBase::Initialize(Environment* env, Local<Object> target) {
274
628
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
275
276
1256
  t->InstanceTemplate()->SetInternalFieldCount(
277
      CipherBase::kInternalFieldCount);
278
628
  t->Inherit(BaseObject::GetConstructorTemplate(env));
279
280
628
  env->SetProtoMethod(t, "init", Init);
281
628
  env->SetProtoMethod(t, "initiv", InitIv);
282
628
  env->SetProtoMethod(t, "update", Update);
283
628
  env->SetProtoMethod(t, "final", Final);
284
628
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
285
628
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
286
628
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
287
628
  env->SetProtoMethod(t, "setAAD", SetAAD);
288
628
  env->SetConstructorFunction(target, "CipherBase", t);
289
290
628
  env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers);
291
628
  env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers);
292
293
628
  env->SetMethod(target, "publicEncrypt",
294
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
295
                                         EVP_PKEY_encrypt_init,
296
                                         EVP_PKEY_encrypt>);
297
628
  env->SetMethod(target, "privateDecrypt",
298
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
299
                                         EVP_PKEY_decrypt_init,
300
                                         EVP_PKEY_decrypt>);
301
628
  env->SetMethod(target, "privateEncrypt",
302
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
303
                                         EVP_PKEY_sign_init,
304
                                         EVP_PKEY_sign>);
305
628
  env->SetMethod(target, "publicDecrypt",
306
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
307
                                         EVP_PKEY_verify_recover_init,
308
                                         EVP_PKEY_verify_recover>);
309
310
628
  env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo);
311
312
1884
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt);
313
1256
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt);
314
628
}
315
316
4950
void CipherBase::RegisterExternalReferences(
317
    ExternalReferenceRegistry* registry) {
318
4950
  registry->Register(New);
319
320
4950
  registry->Register(Init);
321
4950
  registry->Register(InitIv);
322
4950
  registry->Register(Update);
323
4950
  registry->Register(Final);
324
4950
  registry->Register(SetAutoPadding);
325
4950
  registry->Register(GetAuthTag);
326
4950
  registry->Register(SetAuthTag);
327
4950
  registry->Register(SetAAD);
328
329
4950
  registry->Register(GetSSLCiphers);
330
4950
  registry->Register(GetCiphers);
331
332
4950
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
333
                                             EVP_PKEY_encrypt_init,
334
                                             EVP_PKEY_encrypt>);
335
4950
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
336
                                             EVP_PKEY_decrypt_init,
337
                                             EVP_PKEY_decrypt>);
338
4950
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
339
                                             EVP_PKEY_sign_init,
340
                                             EVP_PKEY_sign>);
341
4950
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
342
                                             EVP_PKEY_verify_recover_init,
343
                                             EVP_PKEY_verify_recover>);
344
345
4950
  registry->Register(GetCipherInfo);
346
4950
}
347
348
1483
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
349
1483
  CHECK(args.IsConstructCall());
350
1483
  Environment* env = Environment::GetCurrent(args);
351

2966
  new CipherBase(env, args.This(), args[0]->IsTrue() ? kCipher : kDecipher);
352
1483
}
353
354
907
void CipherBase::CommonInit(const char* cipher_type,
355
                            const EVP_CIPHER* cipher,
356
                            const unsigned char* key,
357
                            int key_len,
358
                            const unsigned char* iv,
359
                            int iv_len,
360
                            unsigned int auth_tag_len) {
361
907
  CHECK(!ctx_);
362
907
  ctx_.reset(EVP_CIPHER_CTX_new());
363
364
907
  const int mode = EVP_CIPHER_mode(cipher);
365
907
  if (mode == EVP_CIPH_WRAP_MODE)
366
29
    EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
367
368
907
  const bool encrypt = (kind_ == kCipher);
369
907
  if (1 != EVP_CipherInit_ex(ctx_.get(), cipher, nullptr,
370
                             nullptr, nullptr, encrypt)) {
371
    return ThrowCryptoError(env(), ERR_get_error(),
372
                            "Failed to initialize cipher");
373
  }
374
375
907
  if (IsSupportedAuthenticatedMode(cipher)) {
376
679
    CHECK_GE(iv_len, 0);
377
679
    if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
378
74
      return;
379
  }
380
381
833
  if (!EVP_CIPHER_CTX_set_key_length(ctx_.get(), key_len)) {
382
1
    ctx_.reset();
383
1
    return THROW_ERR_CRYPTO_INVALID_KEYLEN(env());
384
  }
385
386
832
  if (1 != EVP_CipherInit_ex(ctx_.get(), nullptr, nullptr, key, iv, encrypt)) {
387
    return ThrowCryptoError(env(), ERR_get_error(),
388
                            "Failed to initialize cipher");
389
  }
390
}
391
392
89
void CipherBase::Init(const char* cipher_type,
393
                      const ArrayBufferOrViewContents<unsigned char>& key_buf,
394
                      unsigned int auth_tag_len) {
395
89
  HandleScope scope(env()->isolate());
396
89
  MarkPopErrorOnReturn mark_pop_error_on_return;
397
#if OPENSSL_VERSION_MAJOR >= 3
398
89
  if (EVP_default_properties_is_fips_enabled(nullptr)) {
399
#else
400
  if (FIPS_mode()) {
401
#endif
402
    return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
403
        "crypto.createCipher() is not supported in FIPS mode.");
404
  }
405
406
89
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
407
89
  if (cipher == nullptr)
408
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
409
410
  unsigned char key[EVP_MAX_KEY_LENGTH];
411
  unsigned char iv[EVP_MAX_IV_LENGTH];
412
413
89
  int key_len = EVP_BytesToKey(cipher,
414
                               EVP_md5(),
415
                               nullptr,
416
                               key_buf.data(),
417
89
                               key_buf.size(),
418
                               1,
419
                               key,
420
89
                               iv);
421
89
  CHECK_NE(key_len, 0);
422
423
89
  const int mode = EVP_CIPHER_mode(cipher);
424

89
  if (kind_ == kCipher && (mode == EVP_CIPH_CTR_MODE ||
425
43
                           mode == EVP_CIPH_GCM_MODE ||
426
                           mode == EVP_CIPH_CCM_MODE)) {
427
    // Ignore the return value (i.e. possible exception) because we are
428
    // not calling back into JS anyway.
429
    ProcessEmitWarning(env(),
430
                       "Use Cipheriv for counter mode of %s",
431
24
                       cipher_type);
432
  }
433
434
89
  CommonInit(cipher_type, cipher, key, key_len, iv,
435
             EVP_CIPHER_iv_length(cipher), auth_tag_len);
436
}
437
438
89
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
439
  CipherBase* cipher;
440
89
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
441
89
  Environment* env = Environment::GetCurrent(args);
442
443
89
  CHECK_GE(args.Length(), 3);
444
445
89
  const Utf8Value cipher_type(args.GetIsolate(), args[0]);
446
89
  ArrayBufferOrViewContents<unsigned char> key_buf(args[1]);
447
89
  if (!key_buf.CheckSizeInt32())
448
    return THROW_ERR_OUT_OF_RANGE(env, "password is too large");
449
450
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
451
  // represent a valid length at this point.
452
  unsigned int auth_tag_len;
453
89
  if (args[2]->IsUint32()) {
454
70
    auth_tag_len = args[2].As<Uint32>()->Value();
455
  } else {
456

162
    CHECK(args[2]->IsInt32() && args[2].As<Int32>()->Value() == -1);
457
54
    auth_tag_len = kNoAuthTagLength;
458
  }
459
460
89
  cipher->Init(*cipher_type, key_buf, auth_tag_len);
461
}
462
463
1394
void CipherBase::InitIv(const char* cipher_type,
464
                        const ByteSource& key_buf,
465
                        const ArrayBufferOrViewContents<unsigned char>& iv_buf,
466
                        unsigned int auth_tag_len) {
467
1394
  HandleScope scope(env()->isolate());
468
1394
  MarkPopErrorOnReturn mark_pop_error_on_return;
469
470
1394
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
471
1394
  if (cipher == nullptr)
472
1
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
473
474
1393
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
475
1393
  const bool is_authenticated_mode = IsSupportedAuthenticatedMode(cipher);
476
1393
  const bool has_iv = iv_buf.size() > 0;
477
478
  // Throw if no IV was passed and the cipher requires an IV
479

1393
  if (!has_iv && expected_iv_len != 0)
480
61
    return THROW_ERR_CRYPTO_INVALID_IV(env());
481
482
  // Throw if an IV was passed which does not match the cipher's fixed IV length
483
  // static_cast<int> for the iv_buf.size() is safe because we've verified
484
  // prior that the value is not larger than MAX_INT.
485
695
  if (!is_authenticated_mode &&
486

2027
      has_iv &&
487
670
      static_cast<int>(iv_buf.size()) != expected_iv_len) {
488
509
    return THROW_ERR_CRYPTO_INVALID_IV(env());
489
  }
490
491
823
  if (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305) {
492
292
    CHECK(has_iv);
493
    // Check for invalid IV lengths, since OpenSSL does not under some
494
    // conditions:
495
    //   https://www.openssl.org/news/secadv/20190306.txt.
496
292
    if (iv_buf.size() > 12)
497
5
      return THROW_ERR_CRYPTO_INVALID_IV(env());
498
  }
499
500
1636
  CommonInit(
501
      cipher_type,
502
      cipher,
503
      key_buf.data<unsigned char>(),
504
818
      key_buf.size(),
505
      iv_buf.data(),
506
818
      iv_buf.size(),
507
      auth_tag_len);
508
}
509
510
1394
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
511
  CipherBase* cipher;
512
1394
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
513
1394
  Environment* env = cipher->env();
514
515
1394
  CHECK_GE(args.Length(), 4);
516
517
1394
  const Utf8Value cipher_type(env->isolate(), args[0]);
518
519
  // The argument can either be a KeyObjectHandle or a byte source
520
  // (e.g. ArrayBuffer, TypedArray, etc). Whichever it is, grab the
521
  // raw bytes and proceed...
522
1394
  const ByteSource key_buf = ByteSource::FromSecretKeyBytes(env, args[1]);
523
524
1394
  if (UNLIKELY(key_buf.size() > INT_MAX))
525
    return THROW_ERR_OUT_OF_RANGE(env, "key is too big");
526
527
1394
  ArrayBufferOrViewContents<unsigned char> iv_buf;
528
2788
  if (!args[2]->IsNull())
529
1388
    iv_buf = ArrayBufferOrViewContents<unsigned char>(args[2]);
530
531
1394
  if (UNLIKELY(!iv_buf.CheckSizeInt32()))
532
    return THROW_ERR_OUT_OF_RANGE(env, "iv is too big");
533
534
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
535
  // represent a valid length at this point.
536
  unsigned int auth_tag_len;
537
1394
  if (args[3]->IsUint32()) {
538
932
    auth_tag_len = args[3].As<Uint32>()->Value();
539
  } else {
540

2784
    CHECK(args[3]->IsInt32() && args[3].As<Int32>()->Value() == -1);
541
928
    auth_tag_len = kNoAuthTagLength;
542
  }
543
544
1394
  cipher->InitIv(*cipher_type, key_buf, iv_buf, auth_tag_len);
545
}
546
547
679
bool CipherBase::InitAuthenticated(
548
    const char* cipher_type,
549
    int iv_len,
550
    unsigned int auth_tag_len) {
551
679
  CHECK(IsAuthenticatedMode());
552
1358
  MarkPopErrorOnReturn mark_pop_error_on_return;
553
554
679
  if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
555
                           EVP_CTRL_AEAD_SET_IVLEN,
556
                           iv_len,
557
                           nullptr)) {
558
    THROW_ERR_CRYPTO_INVALID_IV(env());
559
    return false;
560
  }
561
562
679
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
563
679
  if (mode == EVP_CIPH_GCM_MODE) {
564
184
    if (auth_tag_len != kNoAuthTagLength) {
565
24
      if (!IsValidGCMTagLength(auth_tag_len)) {
566
16
        THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
567
          env(),
568
          "Invalid authentication tag length: %u",
569
          auth_tag_len);
570
16
        return false;
571
      }
572
573
      // Remember the given authentication tag length for later.
574
8
      auth_tag_len_ = auth_tag_len;
575
    }
576
  } else {
577
495
    if (auth_tag_len == kNoAuthTagLength) {
578
      // We treat ChaCha20-Poly1305 specially. Like GCM, the authentication tag
579
      // length defaults to 16 bytes when encrypting. Unlike GCM, the
580
      // authentication tag length also defaults to 16 bytes when decrypting,
581
      // whereas GCM would accept any valid authentication tag length.
582
18
      if (EVP_CIPHER_CTX_nid(ctx_.get()) == NID_chacha20_poly1305) {
583
10
        auth_tag_len = 16;
584
      } else {
585
8
        THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
586
          env(), "authTagLength required for %s", cipher_type);
587
8
        return false;
588
      }
589
    }
590
591
    // TODO(tniessen) Support CCM decryption in FIPS mode
592
593
#if OPENSSL_VERSION_MAJOR >= 3
594


541
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher &&
595
54
        EVP_default_properties_is_fips_enabled(nullptr)) {
596
#else
597
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher && FIPS_mode()) {
598
#endif
599
      THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
600
          "CCM encryption not supported in FIPS mode");
601
      return false;
602
    }
603
604
    // Tell OpenSSL about the desired length.
605
487
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len,
606
                             nullptr)) {
607
50
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
608
          env(), "Invalid authentication tag length: %u", auth_tag_len);
609
50
      return false;
610
    }
611
612
    // Remember the given authentication tag length for later.
613
437
    auth_tag_len_ = auth_tag_len;
614
615
437
    if (mode == EVP_CIPH_CCM_MODE) {
616
      // Restrict the message length to min(INT_MAX, 2^(8*(15-iv_len))-1) bytes.
617

90
      CHECK(iv_len >= 7 && iv_len <= 13);
618
90
      max_message_size_ = INT_MAX;
619
90
      if (iv_len == 12) max_message_size_ = 16777215;
620
90
      if (iv_len == 13) max_message_size_ = 65535;
621
    }
622
  }
623
624
605
  return true;
625
}
626
627
127
bool CipherBase::CheckCCMMessageLength(int message_len) {
628
127
  CHECK(ctx_);
629
127
  CHECK(EVP_CIPHER_CTX_mode(ctx_.get()) == EVP_CIPH_CCM_MODE);
630
631
127
  if (message_len > max_message_size_) {
632
4
    THROW_ERR_CRYPTO_INVALID_MESSAGELEN(env());
633
4
    return false;
634
  }
635
636
123
  return true;
637
}
638
639
1986
bool CipherBase::IsAuthenticatedMode() const {
640
  // Check if this cipher operates in an AEAD mode that we support.
641
1986
  CHECK(ctx_);
642
1986
  return IsSupportedAuthenticatedMode(ctx_.get());
643
}
644
645
164
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
646
164
  Environment* env = Environment::GetCurrent(args);
647
  CipherBase* cipher;
648
224
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
649
650
  // Only callable after Final and if encrypting.
651
433
  if (cipher->ctx_ ||
652

269
      cipher->kind_ != kCipher ||
653
105
      cipher->auth_tag_len_ == kNoAuthTagLength) {
654
60
    return;
655
  }
656
657
104
  args.GetReturnValue().Set(
658
208
      Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
659
          .FromMaybe(Local<Value>()));
660
}
661
662
357
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
663
  CipherBase* cipher;
664
610
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
665
357
  Environment* env = Environment::GetCurrent(args);
666
667
357
  if (!cipher->ctx_ ||
668
356
      !cipher->IsAuthenticatedMode() ||
669

1069
      cipher->kind_ != kDecipher ||
670
356
      cipher->auth_tag_state_ != kAuthTagUnknown) {
671
8
    return args.GetReturnValue().Set(false);
672
  }
673
674
353
  ArrayBufferOrViewContents<char> auth_tag(args[0]);
675
353
  if (UNLIKELY(!auth_tag.CheckSizeInt32()))
676
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
677
678
353
  unsigned int tag_len = auth_tag.size();
679
680
353
  const int mode = EVP_CIPHER_CTX_mode(cipher->ctx_.get());
681
  bool is_valid;
682
353
  if (mode == EVP_CIPH_GCM_MODE) {
683
    // Restrict GCM tag lengths according to NIST 800-38d, page 9.
684
43
    is_valid = (cipher->auth_tag_len_ == kNoAuthTagLength ||
685

85
                cipher->auth_tag_len_ == tag_len) &&
686
42
               IsValidGCMTagLength(tag_len);
687
  } else {
688
    // At this point, the tag length is already known and must match the
689
    // length of the given authentication tag.
690
310
    CHECK(IsSupportedAuthenticatedMode(cipher->ctx_.get()));
691
310
    CHECK_NE(cipher->auth_tag_len_, kNoAuthTagLength);
692
310
    is_valid = cipher->auth_tag_len_ == tag_len;
693
  }
694
695
353
  if (!is_valid) {
696
249
    return THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
697
249
      env, "Invalid authentication tag length: %u", tag_len);
698
  }
699
700
104
  cipher->auth_tag_len_ = tag_len;
701
104
  cipher->auth_tag_state_ = kAuthTagKnown;
702
104
  CHECK_LE(cipher->auth_tag_len_, sizeof(cipher->auth_tag_));
703
704
104
  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
705
104
  auth_tag.CopyTo(cipher->auth_tag_, cipher->auth_tag_len_);
706
707
208
  args.GetReturnValue().Set(true);
708
}
709
710
474
bool CipherBase::MaybePassAuthTagToOpenSSL() {
711
474
  if (auth_tag_state_ == kAuthTagKnown) {
712
103
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
713
                             EVP_CTRL_AEAD_SET_TAG,
714
103
                             auth_tag_len_,
715
103
                             reinterpret_cast<unsigned char*>(auth_tag_))) {
716
      return false;
717
    }
718
103
    auth_tag_state_ = kAuthTagPassedToOpenSSL;
719
  }
720
474
  return true;
721
}
722
723
124
bool CipherBase::SetAAD(
724
    const ArrayBufferOrViewContents<unsigned char>& data,
725
    int plaintext_len) {
726

124
  if (!ctx_ || !IsAuthenticatedMode())
727
2
    return false;
728
244
  MarkPopErrorOnReturn mark_pop_error_on_return;
729
730
  int outlen;
731
122
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
732
733
  // When in CCM mode, we need to set the authentication tag and the plaintext
734
  // length in advance.
735
122
  if (mode == EVP_CIPH_CCM_MODE) {
736
55
    if (plaintext_len < 0) {
737
2
      THROW_ERR_MISSING_ARGS(env(),
738
          "options.plaintextLength required for CCM mode with AAD");
739
2
      return false;
740
    }
741
742
53
    if (!CheckCCMMessageLength(plaintext_len))
743
2
      return false;
744
745
51
    if (kind_ == kDecipher) {
746
26
      if (!MaybePassAuthTagToOpenSSL())
747
        return false;
748
    }
749
750
    // Specify the plaintext length.
751
51
    if (!EVP_CipherUpdate(ctx_.get(), nullptr, &outlen, nullptr, plaintext_len))
752
      return false;
753
  }
754
755
118
  return 1 == EVP_CipherUpdate(ctx_.get(),
756
                               nullptr,
757
                               &outlen,
758
                               data.data(),
759
236
                               data.size());
760
}
761
762
124
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
763
  CipherBase* cipher;
764
124
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
765
124
  Environment* env = Environment::GetCurrent(args);
766
767
124
  CHECK_EQ(args.Length(), 2);
768
124
  CHECK(args[1]->IsInt32());
769
248
  int plaintext_len = args[1].As<Int32>()->Value();
770
124
  ArrayBufferOrViewContents<unsigned char> buf(args[0]);
771
772
124
  if (UNLIKELY(!buf.CheckSizeInt32()))
773
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
774
248
  args.GetReturnValue().Set(cipher->SetAAD(buf, plaintext_len));
775
}
776
777
606
CipherBase::UpdateResult CipherBase::Update(
778
    const char* data,
779
    size_t len,
780
    std::unique_ptr<BackingStore>* out) {
781

606
  if (!ctx_ || len > INT_MAX)
782
    return kErrorState;
783
1212
  MarkPopErrorOnReturn mark_pop_error_on_return;
784
785
606
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
786
787

606
  if (mode == EVP_CIPH_CCM_MODE && !CheckCCMMessageLength(len))
788
2
    return kErrorMessageSize;
789
790
  // Pass the authentication tag to OpenSSL if possible. This will only happen
791
  // once, usually on the first update.
792

604
  if (kind_ == kDecipher && IsAuthenticatedMode())
793
344
    CHECK(MaybePassAuthTagToOpenSSL());
794
795
604
  int buf_len = len + EVP_CIPHER_CTX_block_size(ctx_.get());
796
  // For key wrapping algorithms, get output size by calling
797
  // EVP_CipherUpdate() with null output.
798


613
  if (kind_ == kCipher && mode == EVP_CIPH_WRAP_MODE &&
799
9
      EVP_CipherUpdate(ctx_.get(),
800
                       nullptr,
801
                       &buf_len,
802
                       reinterpret_cast<const unsigned char*>(data),
803
                       len) != 1) {
804
    return kErrorState;
805
  }
806
807
  {
808
604
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
809
604
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), buf_len);
810
  }
811
812
604
  int r = EVP_CipherUpdate(ctx_.get(),
813
604
                           static_cast<unsigned char*>((*out)->Data()),
814
                           &buf_len,
815
                           reinterpret_cast<const unsigned char*>(data),
816
                           len);
817
818
604
  CHECK_LE(static_cast<size_t>(buf_len), (*out)->ByteLength());
819
604
  if (buf_len == 0)
820
67
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
821
  else
822
537
    *out = BackingStore::Reallocate(env()->isolate(), std::move(*out), buf_len);
823
824
  // When in CCM mode, EVP_CipherUpdate will fail if the authentication tag is
825
  // invalid. In that case, remember the error and throw in final().
826

604
  if (!r && kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
827
5
    pending_auth_failed_ = true;
828
5
    return kSuccess;
829
  }
830
599
  return r == 1 ? kSuccess : kErrorState;
831
}
832
833
606
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
834
606
  Decode<CipherBase>(args, [](CipherBase* cipher,
835
                              const FunctionCallbackInfo<Value>& args,
836
606
                              const char* data, size_t size) {
837
606
    std::unique_ptr<BackingStore> out;
838
606
    Environment* env = Environment::GetCurrent(args);
839
840
606
    if (UNLIKELY(size > INT_MAX))
841
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
842
843
606
    UpdateResult r = cipher->Update(data, size, &out);
844
845
606
    if (r != kSuccess) {
846
2
      if (r == kErrorState) {
847
        ThrowCryptoError(env, ERR_get_error(),
848
                         "Trying to add data in unsupported state");
849
      }
850
2
      return;
851
    }
852
853
604
    Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
854
1208
    args.GetReturnValue().Set(
855
1208
        Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
856
  });
857
606
}
858
859
18
bool CipherBase::SetAutoPadding(bool auto_padding) {
860
18
  if (!ctx_)
861
1
    return false;
862
17
  MarkPopErrorOnReturn mark_pop_error_on_return;
863
17
  return EVP_CIPHER_CTX_set_padding(ctx_.get(), auto_padding);
864
}
865
866
18
void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
867
  CipherBase* cipher;
868
18
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
869
870

36
  bool b = cipher->SetAutoPadding(args.Length() < 1 || args[0]->IsTrue());
871
36
  args.GetReturnValue().Set(b);  // Possibly report invalid state failure
872
}
873
874
292
bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
875
292
  if (!ctx_)
876
    return false;
877
878
292
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
879
880
  {
881
292
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
882
584
    *out = ArrayBuffer::NewBackingStore(env()->isolate(),
883
584
        static_cast<size_t>(EVP_CIPHER_CTX_block_size(ctx_.get())));
884
  }
885
886

292
  if (kind_ == kDecipher && IsSupportedAuthenticatedMode(ctx_.get()))
887
104
    MaybePassAuthTagToOpenSSL();
888
889
  // In CCM mode, final() only checks whether authentication failed in update().
890
  // EVP_CipherFinal_ex must not be called and will fail.
891
  bool ok;
892

292
  if (kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
893
29
    ok = !pending_auth_failed_;
894
29
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
895
  } else {
896
263
    int out_len = (*out)->ByteLength();
897
263
    ok = EVP_CipherFinal_ex(ctx_.get(),
898
263
                            static_cast<unsigned char*>((*out)->Data()),
899
                            &out_len) == 1;
900
901
263
    CHECK_LE(static_cast<size_t>(out_len), (*out)->ByteLength());
902
263
    if (out_len > 0) {
903
      *out =
904
73
        BackingStore::Reallocate(env()->isolate(), std::move(*out), out_len);
905
    } else {
906
190
      *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
907
    }
908
909


263
    if (ok && kind_ == kCipher && IsAuthenticatedMode()) {
910
      // In GCM mode, the authentication tag length can be specified in advance,
911
      // but defaults to 16 bytes when encrypting. In CCM and OCB mode, it must
912
      // always be given by the user.
913
104
      if (auth_tag_len_ == kNoAuthTagLength) {
914
30
        CHECK(mode == EVP_CIPH_GCM_MODE);
915
30
        auth_tag_len_ = sizeof(auth_tag_);
916
      }
917
104
      ok = (1 == EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_GET_TAG,
918
104
                     auth_tag_len_,
919
104
                     reinterpret_cast<unsigned char*>(auth_tag_)));
920
    }
921
  }
922
923
292
  ctx_.reset();
924
925
292
  return ok;
926
}
927
928
296
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
929
296
  Environment* env = Environment::GetCurrent(args);
930
931
  CipherBase* cipher;
932
317
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
933
296
  if (cipher->ctx_ == nullptr)
934
4
    return THROW_ERR_CRYPTO_INVALID_STATE(env);
935
936
292
  std::unique_ptr<BackingStore> out;
937
938
  // Check IsAuthenticatedMode() first, Final() destroys the EVP_CIPHER_CTX.
939
292
  const bool is_auth_mode = cipher->IsAuthenticatedMode();
940
292
  bool r = cipher->Final(&out);
941
942
292
  if (!r) {
943
17
    const char* msg = is_auth_mode
944
17
                          ? "Unsupported state or unable to authenticate data"
945
                          : "Unsupported state";
946
947
17
    return ThrowCryptoError(env, ERR_get_error(), msg);
948
  }
949
950
275
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
951
550
  args.GetReturnValue().Set(
952
550
      Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
953
}
954
955
template <PublicKeyCipher::Operation operation,
956
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
957
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
958
312
bool PublicKeyCipher::Cipher(
959
    Environment* env,
960
    const ManagedEVPPKey& pkey,
961
    int padding,
962
    const EVP_MD* digest,
963
    const ArrayBufferOrViewContents<unsigned char>& oaep_label,
964
    const ArrayBufferOrViewContents<unsigned char>& data,
965
    std::unique_ptr<BackingStore>* out) {
966
624
  EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(pkey.get(), nullptr));
967
312
  if (!ctx)
968
    return false;
969
312
  if (EVP_PKEY_cipher_init(ctx.get()) <= 0)
970
2
    return false;
971
310
  if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0)
972
    return false;
973
974
310
  if (digest != nullptr) {
975
42
    if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), digest) <= 0)
976
      return false;
977
  }
978
979
310
  if (oaep_label.size() != 0) {
980
    // OpenSSL takes ownership of the label, so we need to create a copy.
981
8
    void* label = OPENSSL_memdup(oaep_label.data(), oaep_label.size());
982
8
    CHECK_NOT_NULL(label);
983
8
    if (0 >= EVP_PKEY_CTX_set0_rsa_oaep_label(ctx.get(),
984
                     static_cast<unsigned char*>(label),
985
8
                                      oaep_label.size())) {
986
      OPENSSL_free(label);
987
      return false;
988
    }
989
  }
990
991
310
  size_t out_len = 0;
992
310
  if (EVP_PKEY_cipher(
993
          ctx.get(),
994
          nullptr,
995
          &out_len,
996
          data.data(),
997
310
          data.size()) <= 0) {
998
    return false;
999
  }
1000
1001
  {
1002
310
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1003
310
    *out = ArrayBuffer::NewBackingStore(env->isolate(), out_len);
1004
  }
1005
1006
620
  if (EVP_PKEY_cipher(
1007
          ctx.get(),
1008
310
          static_cast<unsigned char*>((*out)->Data()),
1009
          &out_len,
1010
          data.data(),
1011
310
          data.size()) <= 0) {
1012
2
    return false;
1013
  }
1014
1015
308
  CHECK_LE(out_len, (*out)->ByteLength());
1016
308
  if (out_len > 0)
1017
308
    *out = BackingStore::Reallocate(env->isolate(), std::move(*out), out_len);
1018
  else
1019
    *out = ArrayBuffer::NewBackingStore(env->isolate(), 0);
1020
1021
308
  return true;
1022
}
1023
1024
template <PublicKeyCipher::Operation operation,
1025
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
1026
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
1027
162
void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
1028
162
  MarkPopErrorOnReturn mark_pop_error_on_return;
1029
162
  Environment* env = Environment::GetCurrent(args);
1030
1031
162
  unsigned int offset = 0;
1032
162
  ManagedEVPPKey pkey =
1033
      ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
1034
162
  if (!pkey)
1035
4
    return;
1036
1037
316
  ArrayBufferOrViewContents<unsigned char> buf(args[offset]);
1038
158
  if (UNLIKELY(!buf.CheckSizeInt32()))
1039
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too long");
1040
1041
  uint32_t padding;
1042
474
  if (!args[offset + 1]->Uint32Value(env->context()).To(&padding)) return;
1043
1044
158
  const EVP_MD* digest = nullptr;
1045
474
  if (args[offset + 2]->IsString()) {
1046
46
    const Utf8Value oaep_str(env->isolate(), args[offset + 2]);
1047
23
    digest = EVP_get_digestbyname(*oaep_str);
1048
23
    if (digest == nullptr)
1049
2
      return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
1050
  }
1051
1052
156
  ArrayBufferOrViewContents<unsigned char> oaep_label;
1053
468
  if (!args[offset + 3]->IsUndefined()) {
1054
8
    oaep_label = ArrayBufferOrViewContents<unsigned char>(args[offset + 3]);
1055
4
    if (UNLIKELY(!oaep_label.CheckSizeInt32()))
1056
      return THROW_ERR_OUT_OF_RANGE(env, "oaep_label is too big");
1057
  }
1058
1059
156
  std::unique_ptr<BackingStore> out;
1060
156
  if (!Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
1061
          env, pkey, padding, digest, oaep_label, buf, &out)) {
1062
2
    return ThrowCryptoError(env, ERR_get_error());
1063
  }
1064
1065
154
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
1066
308
  args.GetReturnValue().Set(
1067
308
      Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
1068
}
1069
1070
}  // namespace crypto
1071
}  // namespace node