All files / lib/internal/crypto webcrypto.js

91.6% Statements 873/953
81.32% Branches 209/257
100% Functions 25/25
91.6% Lines 873/953

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 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 166x 166x 165x 166x 114x 769x 769x 768x 769x 114x 5821x 5821x 5821x 5821x 5821x 5820x 5820x 5820x 5820x 5820x 5821x 5821x 5821x 5821x 390x 390x 5821x 5821x 5821x 5821x 5821x 5821x 5821x 34x 34x 5821x 5821x 5821x 306x 306x 5821x 251x 251x 5821x 5821x 5821x 5821x 5821x 5821x 5821x 1505x 1505x 5821x 5821x 5821x 5821x 7x 7x 5821x 1x 1x 5821x   5821x 5821x 114x 446x 446x 445x 445x 445x 445x 40x 40x 40x 40x 341x 445x 309x 445x 446x 446x 446x 446x 103x 103x 446x 194x 194x 446x 2x 2x 446x 2x 2x 446x 8x 8x 446x   446x 114x 447x 447x 447x 447x 447x 447x 271x 271x 271x 271x 447x 174x 4x 4x 1x 4x 1x 4x 1x 4x 1x 4x 4x 170x 174x 170x 170x     447x 447x 2x 447x 447x 114x 1991x 1991x 1991x 1991x 1991x 1991x 1991x 1990x 1990x 1990x 1991x 1991x 391x 391x 391x 391x 831x 1991x 447x 447x 447x 447x 447x 447x 447x 447x 447x 1991x 1991x 1991x 1991x 1991x 57x 57x 26x 1991x 386x 386x 386x 1991x 3x 3x 3x 1991x 1x 1x 1x 1991x       1991x   1991x 416x 416x 416x 416x 416x 416x 1991x 114x 252x 252x 252x 252x 252x 252x 252x 175x 175x 175x 175x   252x 252x 252x 69x 69x 69x 69x   252x 252x 252x 252x 252x 252x 252x 4x 4x 4x 4x   252x 4x 4x 4x 4x   252x           252x         252x 114x 259x 259x 259x 259x 259x 259x 259x 172x 172x 172x 172x   259x 259x 259x 79x 79x 79x 79x   259x 259x 259x 259x 259x 259x 259x 4x 4x 4x 4x   259x 4x 4x 4x 4x   259x           259x         259x 114x 648x 648x 648x 648x 648x           648x 648x 648x 648x 648x 648x 648x           648x 648x 648x 648x 648x 648x 648x 648x 648x 648x 648x         648x 114x 868x 868x 868x 868x 868x 868x 868x 115x 115x 115x 115x 868x 117x 117x 117x 117x 868x 170x 170x 170x 170x 868x 868x 868x 168x 168x 868x 868x 868x 4x 4x 868x 868x 868x 4x 4x 4x 868x 868x 868x 868x 868x 868x 868x 242x 242x 242x 868x 48x 48x 48x 48x 868x 868x 868x     868x 114x 2220x 2220x 2219x 2219x 2219x 2219x 2219x 2219x 2219x 2027x 2027x 2219x 2220x 2220x 2220x 2220x 2220x     2220x 114x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x         38x 38x 38x                 38x 38x         38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x     38x 38x 38x 38x 38x         38x 114x 4062x 4062x 4062x 4062x 4062x 4062x 4062x 4061x 4061x 4062x 4062x 4050x 4050x 4050x 4050x 4062x 4062x 4062x 4062x 4062x 1688x 1688x 4062x 4062x 4062x 649x 649x 4062x 4062x 4062x 4062x 4062x 4062x 4062x 86x 86x 4062x 322x 322x 4062x 4062x 4062x 4062x 4062x 4062x 4062x 1220x 1220x 4062x 4062x 4062x 4062x 4062x 38x 38x 38x 38x 38x 38x 4062x 44x 44x 4062x 3x 3x 4062x     4062x 114x 114x 114x 354x 354x 353x 353x 353x 353x 159x 159x 159x 159x 159x 159x 353x 353x 353x 353x 353x 353x 353x 354x 114x 114x 114x 402x 402x 402x 402x 402x 402x 402x 402x 402x 401x 401x 401x 401x 401x 401x 401x 401x 401x 401x 233x 233x 233x 233x 233x 233x 233x     233x 401x 401x 401x 401x 401x 401x 402x 114x 1058x 1058x 1058x 1058x 1018x 1018x 1058x 691x 691x 691x 1018x 1058x 1058x 376x 376x 376x 376x 642x 642x 1058x 1058x 1058x 256x 256x 1058x 218x 218x 1058x 1058x 1058x 26x 26x 26x 1058x 102x 102x 1058x 1058x 1058x 40x 40x 1058x   1058x 114x 328x 328x 327x 328x 114x 732x 732x 731x 732x 114x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 1831x 336x 336x 336x 336x 1495x 1495x 1495x 1495x 1495x 1495x 1495x 1495x 1495x 1495x 1495x 1735x 357x 357x 1831x 1831x 1831x 1831x 1831x 1062x 1062x 1831x 76x 76x 76x 76x 1831x   1831x 114x 606x 606x 605x 606x 114x 473x 473x 472x 473x 114x 114x 114x 114x 114x 114x 1x 1x 114x 114x 114x 114x 114x 1x 1x 114x 114x 14843x 14842x 14843x 114x 114x 114x 75x 75x 73x 75x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x  
'use strict';
 
const {
  ArrayPrototypeIncludes,
  JSONParse,
  JSONStringify,
  ObjectDefineProperties,
  ReflectApply,
  ReflectConstruct,
  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_ILLEGAL_CONSTRUCTOR,
    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');
 
async function digest(algorithm, data) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  return ReflectApply(asyncDigest, this, arguments);
}
 
function randomUUID() {
  if (this !== crypto) throw new ERR_INVALID_THIS('Crypto');
  return _randomUUID();
}
 
async function generateKey(
  algorithm,
  extractable,
  keyUsages) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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 'Ed25519':
      // Fall through
    case 'Ed448':
      // Fall through
    case 'X25519':
      // Fall through
    case 'X448':
      return lazyRequire('internal/crypto/cfrg')
        .cfrgGenerateKey(algorithm, extractable, keyUsages);
    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) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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 'X25519':
      // Fall through
    case 'X448':
      // Fall through
    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) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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 'X25519':
      // Fall through
    case 'X448':
      // Fall through
    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 ReflectApply(
    importKey,
    this,
    ['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 'ECDSA':
      // Fall through
    case 'ECDH':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/ec')
          .ecExportKey(key, kWebCryptoKeyFormatSPKI);
      }
      break;
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      // Fall through
    case 'X25519':
      // Fall through
    case 'X448':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/cfrg')
          .cfrgExportKey(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 'ECDSA':
      // Fall through
    case 'ECDH':
      if (key.type === 'private') {
        return lazyRequire('internal/crypto/ec')
          .ecExportKey(key, kWebCryptoKeyFormatPKCS8);
      }
      break;
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      // Fall through
    case 'X25519':
      // Fall through
    case 'X448':
      if (key.type === 'private') {
        return lazyRequire('internal/crypto/cfrg')
          .cfrgExportKey(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 'ECDSA':
      // Fall through
    case 'ECDH':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/ec')
          .ecExportKey(key, kWebCryptoKeyFormatRaw);
      }
      break;
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      // Fall through
    case 'X25519':
      // Fall through
    case 'X448':
      if (key.type === 'public') {
        return lazyRequire('internal/crypto/cfrg')
          .cfrgExportKey(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 'X25519':
      // Fall through
    case 'X448':
      jwk.crv ||= key.algorithm.name;
      return jwk;
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      jwk.crv ||= key.algorithm.name;
      jwk.alg = 'EdDSA';
      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;
    default:
      // Fall through
  }

  throw lazyDOMException('Not yet supported', 'NotSupportedError');
}
 
async function exportKey(format, key) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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 'ECDSA':
      // Fall through
    case 'ECDH':
      return lazyRequire('internal/crypto/ec')
        .ecImportKey(format, keyData, algorithm, extractable, keyUsages);
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      // Fall through
    case 'X25519':
      // Fall through
    case 'X448':
      return lazyRequire('internal/crypto/cfrg')
        .cfrgImportKey(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) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  algorithm = normalizeAlgorithm(algorithm);
  let keyData = await ReflectApply(exportKey, this, [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) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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 ReflectApply(
    importKey,
    this,
    [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 'ECDSA':
      return lazyRequire('internal/crypto/ec')
        .ecdsaSignVerify(key, data, algorithm, signature);
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      // Fall through
      return lazyRequire('internal/crypto/cfrg')
        .eddsaSignVerify(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) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  return signVerify(algorithm, key, data);
}
 
async function verify(algorithm, key, signature, data) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  return cipherOrWrap(kWebCryptoCipherEncrypt, algorithm, key, data, 'encrypt');
}
 
async function decrypt(algorithm, key, data) {
  if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto');
  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 {
  constructor() {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }
}
const subtle = ReflectConstruct(function() {}, [], SubtleCrypto);
 
class Crypto {
  constructor() {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }
 
  get subtle() {
    if (this !== crypto) throw new ERR_INVALID_THIS('Crypto');
    return subtle;
  }
}
const crypto = ReflectConstruct(function() {}, [], Crypto);
 
function getRandomValues(array) {
  if (this !== crypto) throw new ERR_INVALID_THIS('Crypto');
  return ReflectApply(_getRandomValues, this, arguments);
}
 
ObjectDefineProperties(
  Crypto.prototype, {
    [SymbolToStringTag]: {
      __proto__: null,
      enumerable: false,
      configurable: true,
      writable: false,
      value: 'Crypto',
    },
    subtle: kEnumerableProperty,
    getRandomValues: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: getRandomValues,
    },
    randomUUID: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: randomUUID,
    },
    CryptoKey: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: CryptoKey,
    }
  });
 
ObjectDefineProperties(
  SubtleCrypto.prototype, {
    [SymbolToStringTag]: {
      __proto__: null,
      enumerable: false,
      configurable: true,
      writable: false,
      value: 'SubtleCrypto',
    },
    encrypt: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: encrypt,
    },
    decrypt: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: decrypt,
    },
    sign: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: sign,
    },
    verify: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: verify,
    },
    digest: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: digest,
    },
    generateKey: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: generateKey,
    },
    deriveKey: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: deriveKey,
    },
    deriveBits: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: deriveBits,
    },
    importKey: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: importKey,
    },
    exportKey: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: exportKey,
    },
    wrapKey: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: wrapKey,
    },
    unwrapKey: {
      __proto__: null,
      enumerable: true,
      configurable: true,
      writable: true,
      value: unwrapKey,
    }
  });
 
module.exports = {
  Crypto,
  CryptoKey,
  SubtleCrypto,
  crypto,
};