All files / lib/internal/crypto webcrypto.js

94.37% Statements 805/853
82.16% Branches 152/185
100% Functions 22/22
94.37% Lines 805/853

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 386x 386x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 318x 318x 5790x 247x 247x 5790x 5790x 5790x 5790x 5790x 5790x 5790x 1505x 1505x 5790x 5790x 5790x 5790x 7x 7x 5790x 1x 1x 5790x   5790x 5790x 103x 423x 423x 423x 423x 423x 40x 40x 40x 40x 319x 423x 423x 423x 81x 81x 423x 194x 194x 423x 2x 2x 423x 2x 2x 423x 8x 8x 423x 423x 423x 103x 440x 440x 440x 440x 440x 440x 266x 266x 266x 266x 440x 172x 4x 4x 1x 4x 1x 4x 1x 4x 1x 4x 4x 172x 172x 168x 168x     440x 440x 2x 440x 440x 103x 1983x 1983x 1983x 1983x 1983x 1983x 1983x 1983x 1983x 1983x 1983x 391x 391x 391x 391x 1983x 1983x 440x 440x 440x 440x 440x 440x 440x 440x 440x 1983x 51x 51x 51x 1983x 386x 386x 386x 1983x 2x 2x 2x 1983x 1x 1x 1x 1983x       1983x   1983x 1983x 1983x 1983x 103x 248x 248x 248x 248x 248x 248x 248x 175x 175x 175x 175x 175x 248x 248x 248x 248x 248x 248x 248x 69x 69x 69x 69x 69x 248x 4x 4x 4x 4x 4x 248x           248x         248x 103x 255x 255x 255x 255x 255x 255x 255x 172x 172x 172x 172x   255x 255x 255x 255x 255x 255x 255x 79x 79x 79x 79x   255x 4x 4x 4x 4x 4x 255x           255x 255x 255x 255x 255x 255x 103x 662x 662x 662x 662x 662x 14x 7x 7x 7x 7x 662x 662x 662x           662x 662x 662x 662x 662x 662x 662x 662x 662x 648x 662x 662x 662x 662x 662x 662x 103x 880x 880x 880x 880x 880x 880x 880x 115x 115x 115x 115x 880x 119x 119x 119x 119x 880x 170x 170x 170x 170x 880x 880x 880x 172x 172x 880x 880x 880x 880x 880x 880x 880x 242x 242x 242x 880x 48x 48x 48x 48x 880x 880x 880x 14x 880x 880x 880x 880x 880x 880x 103x 2221x 2221x 2221x 2221x 2221x 2221x 2221x 2221x 2189x 2189x 2221x 2221x 2221x 2221x 2221x 2221x 2221x 2221x 2221x 103x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x         37x 37x 37x                 37x 37x         37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x     37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 103x 4029x 4029x 4029x 4029x 4029x 4029x 4029x 4029x 4029x 4029x 4018x 4018x 4018x 4018x 4029x 4029x 4029x 4029x 4029x 1698x 1698x 4029x 4029x 4029x 4029x 4029x 4029x 4029x 697x 697x 4029x 326x 326x 4029x 4029x 4029x 4029x 4029x 4029x 4029x 1213x 1213x 4029x 4029x 4029x 4029x 4029x 37x 37x 37x 37x 37x 37x 4029x 44x 44x 4029x 3x 3x 4029x 4029x 4029x 4029x 103x 103x 103x 353x 353x 353x 353x 353x 159x 159x 159x 159x 159x 159x 353x 353x 353x 353x 353x 353x 353x 353x 103x 103x 103x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 233x 233x 233x 233x 233x 233x 233x     233x 401x 401x 401x 103x 1016x 1016x 1016x 1016x 1016x 1016x 1016x 662x 662x 662x 976x 1016x 1016x 340x 340x 340x 340x 636x 636x 976x 1016x 1016x 256x 256x 1016x 1016x 1016x 1016x 1016x 238x 238x 1016x 102x 102x 1016x 1016x 1016x 40x 40x 1016x 1016x 1016x 103x 314x 314x 314x 103x 702x 702x 702x 103x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 336x 336x 336x 336x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 357x 357x 1831x 1831x 1831x 1831x 1831x 1062x 1062x 1831x 76x 76x 76x 76x 1831x 1831x 1831x 103x 605x 605x 605x 103x 472x 472x 472x 103x 103x 103x 103x 103x 103x 103x 103x 103x 14299x 14299x 103x 103x 103x 70x 70x 1x 1x 70x 70x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x  
'use strict';
 
const {
  ArrayPrototypeIncludes,
  JSONParse,
  JSONStringify,
  ObjectDefineProperties,
  ReflectApply,
  SafeSet,
  SymbolToStringTag,
  StringPrototypeRepeat,
} = primordials;
 
const {
  kWebCryptoKeyFormatRaw,
  kWebCryptoKeyFormatPKCS8,
  kWebCryptoKeyFormatSPKI,
  kWebCryptoCipherEncrypt,
  kWebCryptoCipherDecrypt,
} = internalBinding('crypto');
 
const {
  validateArray,
  validateBoolean,
  validateObject,
  validateOneOf,
  validateString,
} = require('internal/validators');
 
const { TextDecoder, TextEncoder } = require('internal/encoding');
 
const {
  codes: {
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_THIS,
  }
} = require('internal/errors');
 
const {
  CryptoKey,
  InternalCryptoKey,
  createSecretKey,
  isCryptoKey,
  isKeyObject,
} = require('internal/crypto/keys');
 
const {
  asyncDigest,
} = require('internal/crypto/hash');
 
const {
  getArrayBufferOrView,
  hasAnyNotIn,
  lazyRequire,
  normalizeAlgorithm,
  normalizeHashName,
  validateMaxBufferLength,
  kExportFormats,
  kHandle,
  kKeyObject,
} = require('internal/crypto/util');
 
const {
  kEnumerableProperty,
  lazyDOMException,
} = require('internal/util');
 
const {
  getRandomValues: _getRandomValues,
  randomUUID: _randomUUID,
} = require('internal/crypto/random');
 
const randomUUID = () => _randomUUID();
 
async function generateKey(
  algorithm,
  extractable,
  keyUsages) {
  algorithm = normalizeAlgorithm(algorithm);
  validateBoolean(extractable, 'extractable');
  validateArray(keyUsages, 'keyUsages');
  switch (algorithm.name) {
    case 'RSASSA-PKCS1-v1_5':
      // Fall through
    case 'RSA-PSS':
      // Fall through
    case 'RSA-OAEP':
      return lazyRequire('internal/crypto/rsa')
        .rsaKeyGenerate(algorithm, extractable, keyUsages);
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      // Fall through
    case 'ECDSA':
      // Fall through
    case 'ECDH':
      return lazyRequire('internal/crypto/ec')
        .ecGenerateKey(algorithm, extractable, keyUsages);
    case 'HMAC':
      return lazyRequire('internal/crypto/mac')
        .hmacGenerateKey(algorithm, extractable, keyUsages);
    case 'AES-CTR':
      // Fall through
    case 'AES-CBC':
      // Fall through
    case 'AES-GCM':
      // Fall through
    case 'AES-KW':
      return lazyRequire('internal/crypto/aes')
        .aesGenerateKey(algorithm, extractable, keyUsages);
 
    // Following are Node.js specific extensions. Names must be prefixed
    // with the `NODE-`
    case 'NODE-DSA':
      return lazyRequire('internal/crypto/dsa')
        .dsaGenerateKey(algorithm, extractable, keyUsages);
    case 'NODE-DH':
      return lazyRequire('internal/crypto/diffiehellman')
        .dhGenerateKey(algorithm, extractable, keyUsages);
    default:
      throw lazyDOMException('Unrecognized name.');
  }
}
 
async function deriveBits(algorithm, baseKey, length) {
  algorithm = normalizeAlgorithm(algorithm);
  if (!isCryptoKey(baseKey))
    throw new ERR_INVALID_ARG_TYPE('baseKey', 'CryptoKey', baseKey);
  if (!ArrayPrototypeIncludes(baseKey.usages, 'deriveBits')) {
    throw lazyDOMException(
      'baseKey does not have deriveBits usage',
      'InvalidAccessError');
  }
  if (baseKey.algorithm.name !== algorithm.name)
    throw lazyDOMException('Key algorithm mismatch', 'InvalidAccessError');
  switch (algorithm.name) {
    case 'ECDH':
      return lazyRequire('internal/crypto/diffiehellman')
        .asyncDeriveBitsECDH(algorithm, baseKey, length);
    case 'HKDF':
      return lazyRequire('internal/crypto/hkdf')
        .hkdfDeriveBits(algorithm, baseKey, length);
    case 'PBKDF2':
      return lazyRequire('internal/crypto/pbkdf2')
        .pbkdf2DeriveBits(algorithm, baseKey, length);
    case 'NODE-SCRYPT':
      return lazyRequire('internal/crypto/scrypt')
        .scryptDeriveBits(algorithm, baseKey, length);
    case 'NODE-DH':
      return lazyRequire('internal/crypto/diffiehellman')
        .asyncDeriveBitsDH(algorithm, baseKey, length);
  }
  throw lazyDOMException('Unrecognized name.');
}
 
function getKeyLength({ name, length, hash }) {
  switch (name) {
    case 'AES-CTR':
    case 'AES-CBC':
    case 'AES-GCM':
    case 'AES-KW':
      if (length !== 128 && length !== 192 && length !== 256)
        throw lazyDOMException('Invalid key length', 'OperationError');
 
      return length;
    case 'HMAC':
      if (length === undefined) {
        switch (hash?.name) {
          case 'SHA-1':
            return 160;
          case 'SHA-256':
            return 256;
          case 'SHA-384':
            return 384;
          case 'SHA-512':
            return 512;
        }
      }
 
      if (typeof length === 'number' && length !== 0) {
        return length;
      }

      throw lazyDOMException('Invalid key length', 'OperationError');
    case 'HKDF':
    case 'PBKDF2':
      return null;
  }
}
 
async function deriveKey(
  algorithm,
  baseKey,
  derivedKeyAlgorithm,
  extractable,
  keyUsages) {
  algorithm = normalizeAlgorithm(algorithm);
  derivedKeyAlgorithm = normalizeAlgorithm(derivedKeyAlgorithm);
  if (!isCryptoKey(baseKey))
    throw new ERR_INVALID_ARG_TYPE('baseKey', 'CryptoKey', baseKey);
  if (!ArrayPrototypeIncludes(baseKey.usages, 'deriveKey')) {
    throw lazyDOMException(
      'baseKey does not have deriveKey usage',
      'InvalidAccessError');
  }
  if (baseKey.algorithm.name !== algorithm.name)
    throw lazyDOMException('Key algorithm mismatch', 'InvalidAccessError');
  validateObject(derivedKeyAlgorithm, 'derivedKeyAlgorithm', {
    allowArray: true, allowFunction: true,
  });
  validateBoolean(extractable, 'extractable');
  validateArray(keyUsages, 'keyUsages');
 
  const length = getKeyLength(derivedKeyAlgorithm);
  let bits;
  switch (algorithm.name) {
    case 'ECDH':
      bits = await lazyRequire('internal/crypto/diffiehellman')
        .asyncDeriveBitsECDH(algorithm, baseKey, length);
      break;
    case 'HKDF':
      bits = await lazyRequire('internal/crypto/hkdf')
        .hkdfDeriveBits(algorithm, baseKey, length);
      break;
    case 'PBKDF2':
      bits = await lazyRequire('internal/crypto/pbkdf2')
        .pbkdf2DeriveBits(algorithm, baseKey, length);
      break;
    case 'NODE-SCRYPT':
      bits = await lazyRequire('internal/crypto/scrypt')
        .scryptDeriveBits(algorithm, baseKey, length);
      break;
    case 'NODE-DH':
      bits = await lazyRequire('internal/crypto/diffiehellman')
        .asyncDeriveBitsDH(algorithm, baseKey, length);
      break;
    default:
      throw lazyDOMException('Unrecognized name.');
  }
 
  return importKey('raw', bits, derivedKeyAlgorithm, extractable, keyUsages);
}
 
async function exportKeySpki(key) {
  switch (key.algorithm.name) {
    case 'RSASSA-PKCS1-v1_5':
      // Fall through
    case 'RSA-PSS':
      // Fall through
    case 'RSA-OAEP':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/rsa')
          .rsaExportKey(key, kWebCryptoKeyFormatSPKI);
      }
      break;
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      // Fall through
    case 'ECDSA':
      // Fall through
    case 'ECDH':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/ec')
          .ecExportKey(key, kWebCryptoKeyFormatSPKI);
      }
      break;
    case 'NODE-DSA':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/dsa')
          .dsaExportKey(key, kWebCryptoKeyFormatSPKI);
      }
      break;
    case 'NODE-DH':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/diffiehellman')
          .dhExportKey(key, kWebCryptoKeyFormatSPKI);
      }
      break;
  }

  throw lazyDOMException(
    `Unable to export a raw ${key.algorithm.name} ${key.type} key`,
    'InvalidAccessError');
}
 
async function exportKeyPkcs8(key) {
  switch (key.algorithm.name) {
    case 'RSASSA-PKCS1-v1_5':
      // Fall through
    case 'RSA-PSS':
      // Fall through
    case 'RSA-OAEP':
      if (key.type === 'private') {
        return lazyRequire('internal/crypto/rsa')
          .rsaExportKey(key, kWebCryptoKeyFormatPKCS8);
      }
      break;
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      // Fall through
    case 'ECDSA':
      // Fall through
    case 'ECDH':
      if (key.type === 'private') {
        return lazyRequire('internal/crypto/ec')
          .ecExportKey(key, kWebCryptoKeyFormatPKCS8);
      }
      break;
    case 'NODE-DSA':
      if (key.type === 'private') {
        return lazyRequire('internal/crypto/dsa')
          .dsaExportKey(key, kWebCryptoKeyFormatPKCS8);
      }
      break;
    case 'NODE-DH':
      if (key.type === 'private') {
        return lazyRequire('internal/crypto/diffiehellman')
          .dhExportKey(key, kWebCryptoKeyFormatPKCS8);
      }
      break;
  }
 
  throw lazyDOMException(
    `Unable to export a pkcs8 ${key.algorithm.name} ${key.type} key`,
    'InvalidAccessError');
}
 
async function exportKeyRaw(key) {
  switch (key.algorithm.name) {
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/ec')
          .ecExportKey(key, kWebCryptoKeyFormatRaw);
      }
      break;
    case 'ECDSA':
      // Fall through
    case 'ECDH':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/ec')
          .ecExportKey(key, kWebCryptoKeyFormatRaw);
      }
      break;
    case 'AES-CTR':
      // Fall through
    case 'AES-CBC':
      // Fall through
    case 'AES-GCM':
      // Fall through
    case 'AES-KW':
      // Fall through
    case 'HMAC':
      return key[kKeyObject].export().buffer;
  }
 
  throw lazyDOMException(
    `Unable to export a raw ${key.algorithm.name} ${key.type} key`,
    'InvalidAccessError');
}
 
async function exportKeyJWK(key) {
  const jwk = key[kKeyObject][kHandle].exportJwk({
    key_ops: key.usages,
    ext: key.extractable,
  }, true);
  switch (key.algorithm.name) {
    case 'RSASSA-PKCS1-v1_5':
      jwk.alg = normalizeHashName(
        key.algorithm.hash.name,
        normalizeHashName.kContextJwkRsa);
      return jwk;
    case 'RSA-PSS':
      jwk.alg = normalizeHashName(
        key.algorithm.hash.name,
        normalizeHashName.kContextJwkRsaPss);
      return jwk;
    case 'RSA-OAEP':
      jwk.alg = normalizeHashName(
        key.algorithm.hash.name,
        normalizeHashName.kContextJwkRsaOaep);
      return jwk;
    case 'ECDSA':
      // Fall through
    case 'ECDH':
      jwk.crv ||= key.algorithm.namedCurve;
      return jwk;
    case 'AES-CTR':
      // Fall through
    case 'AES-CBC':
      // Fall through
    case 'AES-GCM':
      // Fall through
    case 'AES-KW':
      jwk.alg = lazyRequire('internal/crypto/aes')
        .getAlgorithmName(key.algorithm.name, key.algorithm.length);
      return jwk;
    case 'HMAC':
      jwk.alg = normalizeHashName(
        key.algorithm.hash.name,
        normalizeHashName.kContextJwkHmac);
      return jwk;
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      return jwk;
    default:
      // Fall through
  }
 
  throw lazyDOMException('Not yet supported', 'NotSupportedError');
}
 
async function exportKey(format, key) {
  validateString(format, 'format');
  validateOneOf(format, 'format', kExportFormats);
  if (!isCryptoKey(key))
    throw new ERR_INVALID_ARG_TYPE('key', 'CryptoKey', key);
 
  if (!key.extractable)
    throw lazyDOMException('key is not extractable', 'InvalidAccessException');
 
  switch (format) {
    case 'node.keyObject': return key[kKeyObject];
    case 'spki': return exportKeySpki(key);
    case 'pkcs8': return exportKeyPkcs8(key);
    case 'jwk': return exportKeyJWK(key);
    case 'raw': return exportKeyRaw(key);
  }
  throw lazyDOMException(
    'Export format is unsupported', 'NotSupportedError');
}
 
async function importGenericSecretKey(
  { name, length },
  format,
  keyData,
  extractable,
  keyUsages) {
  const usagesSet = new SafeSet(keyUsages);
  if (extractable)
    throw lazyDOMException(`${name} keys are not extractable`, 'SyntaxError');
 
  if (hasAnyNotIn(usagesSet, ['deriveKey', 'deriveBits'])) {
    throw lazyDOMException(
      `Unsupported key usage for a ${name} key`,
      'SyntaxError');
  }
 
  switch (format) {
    case 'node.keyObject': {
      if (!isKeyObject(keyData))
        throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData);

      if (keyData.type === 'secret')
        return new InternalCryptoKey(keyData, { name }, keyUsages, extractable);

      break;
    }
    case 'raw': {
      if (hasAnyNotIn(usagesSet, ['deriveKey', 'deriveBits'])) {
        throw lazyDOMException(
          `Unsupported key usage for a ${name} key`,
          'SyntaxError');
      }
 
      const checkLength = keyData.byteLength * 8;
 
      if (checkLength === 0 || length === 0)
        throw lazyDOMException('Zero-length key is not supported', 'DataError');
 
      // The Web Crypto spec allows for key lengths that are not multiples of
      // 8. We don't. Our check here is stricter than that defined by the spec
      // in that we require that algorithm.length match keyData.length * 8 if
      // algorithm.length is specified.
      if (length !== undefined && length !== checkLength) {
        throw lazyDOMException('Invalid key length', 'DataError');
      }
 
      const keyObject = createSecretKey(keyData);
      return new InternalCryptoKey(keyObject, { name }, keyUsages, false);
    }
  }
 
  throw lazyDOMException(
    `Unable to import ${name} key with format ${format}`,
    'NotSupportedError');
}
 
async function importKey(
  format,
  keyData,
  algorithm,
  extractable,
  keyUsages) {
  validateString(format, 'format');
  validateOneOf(format, 'format', kExportFormats);
  if (format !== 'node.keyObject' && format !== 'jwk')
    keyData = getArrayBufferOrView(keyData, 'keyData');
  algorithm = normalizeAlgorithm(algorithm);
  validateBoolean(extractable, 'extractable');
  validateArray(keyUsages, 'keyUsages');
  switch (algorithm.name) {
    case 'RSASSA-PKCS1-v1_5':
      // Fall through
    case 'RSA-PSS':
      // Fall through
    case 'RSA-OAEP':
      return lazyRequire('internal/crypto/rsa')
        .rsaImportKey(format, keyData, algorithm, extractable, keyUsages);
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      // Fall through
    case 'ECDSA':
      // Fall through
    case 'ECDH':
      return lazyRequire('internal/crypto/ec')
        .ecImportKey(format, keyData, algorithm, extractable, keyUsages);
    case 'HMAC':
      return lazyRequire('internal/crypto/mac')
        .hmacImportKey(format, keyData, algorithm, extractable, keyUsages);
    case 'AES-CTR':
      // Fall through
    case 'AES-CBC':
      // Fall through
    case 'AES-GCM':
      // Fall through
    case 'AES-KW':
      return lazyRequire('internal/crypto/aes')
        .aesImportKey(algorithm, format, keyData, extractable, keyUsages);
    case 'HKDF':
      // Fall through
    case 'NODE-SCRYPT':
      // Fall through
    case 'PBKDF2':
      return importGenericSecretKey(
        algorithm,
        format,
        keyData,
        extractable,
        keyUsages);
    case 'NODE-DSA':
      return lazyRequire('internal/crypto/dsa')
        .dsaImportKey(format, keyData, algorithm, extractable, keyUsages);
    case 'NODE-DH':
      return lazyRequire('internal/crypto/diffiehellman')
        .dhImportKey(format, keyData, algorithm, extractable, keyUsages);
  }
 
  throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
}
 
// subtle.wrapKey() is essentially a subtle.exportKey() followed
// by a subtle.encrypt().
async function wrapKey(format, key, wrappingKey, algorithm) {
  algorithm = normalizeAlgorithm(algorithm);
  let keyData = await exportKey(format, key);
 
  if (format === 'jwk') {
    if (keyData == null || typeof keyData !== 'object')
      throw lazyDOMException('Invalid exported JWK key', 'DataError');
    const ec = new TextEncoder();
    const raw = JSONStringify(keyData);
    keyData = ec.encode(raw + StringPrototypeRepeat(' ', 8 - (raw.length % 8)));
  }
 
  return cipherOrWrap(
    kWebCryptoCipherEncrypt,
    algorithm,
    wrappingKey,
    keyData,
    'wrapKey');
}
 
// subtle.unwrapKey() is essentially a subtle.decrypt() followed
// by a subtle.importKey().
async function unwrapKey(
  format,
  wrappedKey,
  unwrappingKey,
  unwrapAlgo,
  unwrappedKeyAlgo,
  extractable,
  keyUsages) {
  wrappedKey = getArrayBufferOrView(wrappedKey, 'wrappedKey');
  unwrapAlgo = normalizeAlgorithm(unwrapAlgo);
  let keyData = await cipherOrWrap(
    kWebCryptoCipherDecrypt,
    unwrapAlgo,
    unwrappingKey,
    wrappedKey,
    'unwrapKey');
 
  if (format === 'jwk') {
    // The fatal: true option is only supported in builds that have ICU.
    const options = process.versions.icu !== undefined ?
      { fatal: true } : undefined;
    const dec = new TextDecoder('utf-8', options);
    try {
      keyData = JSONParse(dec.decode(keyData));
    } catch {
      throw lazyDOMException('Invalid imported JWK key', 'DataError');
    }
  }
 
  return importKey(format, keyData, unwrappedKeyAlgo, extractable, keyUsages);
}
 
function signVerify(algorithm, key, data, signature) {
  algorithm = normalizeAlgorithm(algorithm);
  if (!isCryptoKey(key))
    throw new ERR_INVALID_ARG_TYPE('key', 'CryptoKey', key);
  data = getArrayBufferOrView(data, 'data');
  let usage = 'sign';
  if (signature !== undefined) {
    signature = getArrayBufferOrView(signature, 'signature');
    usage = 'verify';
  }
 
  if (!ArrayPrototypeIncludes(key.usages, usage) ||
      algorithm.name !== key.algorithm.name) {
    throw lazyDOMException(
      `Unable to use this key to ${usage}`,
      'InvalidAccessError');
  }
 
  switch (algorithm.name) {
    case 'RSA-PSS':
      // Fall through
    case 'RSASSA-PKCS1-v1_5':
      return lazyRequire('internal/crypto/rsa')
        .rsaSignVerify(key, data, algorithm, signature);
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      // Fall through
    case 'ECDSA':
      return lazyRequire('internal/crypto/ec')
        .ecdsaSignVerify(key, data, algorithm, signature);
    case 'HMAC':
      return lazyRequire('internal/crypto/mac')
        .hmacSignVerify(key, data, algorithm, signature);
    // The following are Node.js specific extensions. They must begin with
    // the `NODE-` prefix
    case 'NODE-DSA':
      return lazyRequire('internal/crypto/dsa')
        .dsaSignVerify(key, data, algorithm, signature);
  }
  throw lazyDOMException('Unrecognized named.', 'NotSupportedError');
}
 
async function sign(algorithm, key, data) {
  return signVerify(algorithm, key, data);
}
 
async function verify(algorithm, key, signature, data) {
  return signVerify(algorithm, key, data, signature);
}
 
async function cipherOrWrap(mode, algorithm, key, data, op) {
  algorithm = normalizeAlgorithm(algorithm);
  // We use a Node.js style error here instead of a DOMException because
  // the WebCrypto spec is not specific what kind of error is to be thrown
  // in this case. Both Firefox and Chrome throw simple TypeErrors here.
  if (!isCryptoKey(key))
    throw new ERR_INVALID_ARG_TYPE('key', 'CryptoKey', key);
  // The key algorithm and cipher algorithm must match, and the
  // key must have the proper usage.
  if (key.algorithm.name !== algorithm.name ||
      !ArrayPrototypeIncludes(key.usages, op)) {
    throw lazyDOMException(
      'The requested operation is not valid for the provided key',
      'InvalidAccessError');
  }
 
  // For the Web Crypto API, the input data can be any ArrayBuffer,
  // TypedArray, or DataView.
  data = getArrayBufferOrView(data, 'data');
 
  // While WebCrypto allows for larger input buffer sizes, we limit
  // those to sizes that can fit within uint32_t because of limitations
  // in the OpenSSL API.
  validateMaxBufferLength(data, 'data');
 
  switch (algorithm.name) {
    case 'RSA-OAEP':
      return lazyRequire('internal/crypto/rsa')
        .rsaCipher(mode, key, data, algorithm);
    case 'AES-CTR':
      // Fall through
    case 'AES-CBC':
      // Fall through
    case 'AES-GCM':
      return lazyRequire('internal/crypto/aes')
        .aesCipher(mode, key, data, algorithm);
    case 'AES-KW':
      if (op === 'wrapKey' || op === 'unwrapKey') {
        return lazyRequire('internal/crypto/aes')
          .aesCipher(mode, key, data, algorithm);
      }
  }
  throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
}
 
async function encrypt(algorithm, key, data) {
  return cipherOrWrap(kWebCryptoCipherEncrypt, algorithm, key, data, 'encrypt');
}
 
async function decrypt(algorithm, key, data) {
  return cipherOrWrap(kWebCryptoCipherDecrypt, algorithm, key, data, 'decrypt');
}
 
// The SubtleCrypto and Crypto classes are defined as part of the
// Web Crypto API standard: https://www.w3.org/TR/WebCryptoAPI/
 
class SubtleCrypto {}
const subtle = new SubtleCrypto();
 
class Crypto {
  get subtle() {
    return subtle;
  }
}
const crypto = new Crypto();
 
function getRandomValues(array) {
  if (!(this instanceof Crypto)) {
    throw new ERR_INVALID_THIS('Crypto');
  }
  return ReflectApply(_getRandomValues, this, arguments);
}
 
ObjectDefineProperties(
  Crypto.prototype, {
    [SymbolToStringTag]: {
      enumerable: false,
      configurable: true,
      writable: false,
      value: 'Crypto',
    },
    subtle: kEnumerableProperty,
    getRandomValues: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: getRandomValues,
    },
    randomUUID: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: randomUUID,
    },
    CryptoKey: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: CryptoKey,
    }
  });
 
ObjectDefineProperties(
  SubtleCrypto.prototype, {
    [SymbolToStringTag]: {
      enumerable: false,
      configurable: true,
      writable: false,
      value: 'SubtleCrypto',
    },
    encrypt: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: encrypt,
    },
    decrypt: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: decrypt,
    },
    sign: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: sign,
    },
    verify: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: verify,
    },
    digest: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: asyncDigest,
    },
    generateKey: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: generateKey,
    },
    deriveKey: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: deriveKey,
    },
    deriveBits: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: deriveBits,
    },
    importKey: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: importKey,
    },
    exportKey: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: exportKey,
    },
    wrapKey: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: wrapKey,
    },
    unwrapKey: {
      enumerable: true,
      configurable: true,
      writable: true,
      value: unwrapKey,
    }
  });
 
module.exports = {
  Crypto,
  CryptoKey,
  SubtleCrypto,
  crypto,
};