All files / lib/internal/crypto keys.js

95.71% Statements 736/769
93.09% Branches 202/217
100% Functions 41/41
95.71% Lines 736/769

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 770105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 4145x 4145x 4145x 2127x 2127x 2127x 2127x 2125x 2125x 2125x 2125x 2125x 2125x 2125x 2125x 2125x 2125x 2125x 2127x 4145x 4145x 1712x 1712x 4145x 4145x 1x 1x   1x 4145x 4145x 4145x 4145x 903x 903x 4145x 4145x 1x 1x 4145x 4145x 503x 4x 4x 4x 4x 1x 1x 4x 502x 503x 4145x 4145x 4145x 4145x 4145x 4145x 4145x 34x 6x 6x 6x 6x 6x 6x 28x 34x 4145x 4145x 4145x 4145x 1222x 1222x 4145x 4145x 318x 318x 318x 4145x 4145x 64x 64x 64x 64x 64x 56x 34x 34x 56x 64x 8x 64x 64x 4145x 4145x 51x 51x 51x 22x 22x 22x 22x 22x 22x 2x 2x 22x 51x 51x 51x 51x 51x 4x 51x 51x 4145x 4145x 4145x 4145x 621x 621x 4145x 4145x 80x 30x 30x 30x 50x 50x 50x 50x 50x 80x 4145x 4145x 4145x 4145x 601x 601x 4145x 4145x 61x 22x 1x 1x 1x 21x 21x 21x 39x 39x 39x 39x 39x 39x 39x 61x 4145x 4145x 4145x 105x 105x 2008x 2008x 2008x 951x 951x 780x 780x 12x 2008x 105x 1996x 1996x 1078x 1996x 93x 5x 5x 5x 88x 918x 382x 558x 415x 443x 12x 2x 2x 2x 10x 10x 16x 16x 1996x 105x 4013x 4013x 4013x 4013x 105x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 105x 4246x 4246x 4246x 4246x 4246x 105x 2013x 2013x 2013x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2008x 2013x 1874x 1874x 1874x 73x 23x 23x 23x 4x 23x 2x 2x 2x 73x 1x 1x 73x 1868x 1874x 1874x 1874x 5x 5x 5x 1874x 1962x 1962x 2013x 1962x 1962x 2013x 105x 105x 105x 105x 121x 121x 121x 105x 105x 105x 105x 90x 90x 90x 105x 238x 238x 2x 2x 2x 2x 2x 2x 236x 238x 87x 87x 87x       87x 235x 235x 238x 105x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x   21x     21x 21x 105x 32x 32x 32x 32x 32x 32x 32x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 8x 8x 8x 8x 4x     4x 8x 2x     2x 8x 2x     2x 8x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 8x 24x 32x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 32x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 16x 16x 16x 16x 32x 16x 16x 32x 105x 2430x 2430x 97x 97x 2430x   2333x 340x 340x 2333x 1983x 1983x 1983x 1983x 1983x 1842x 1842x 1842x 1842x 1810x 1983x 8x 8x 8x 8x 8x 1802x 1802x 1983x 1983x 1983x 1983x 1983x 1983x 10x 10x 10x 10x 2430x 105x 385x 385x 385x 105x 1346x 1346x 1346x 105x 2161x 2161x 1363x 14x 14x 14x 1363x         1363x 2159x 2161x 2161x 3x 3x 3x 3x 3x 2144x 2161x 105x 798x 798x 798x 798x 797x 797x 797x 798x 105x 350x 350x 350x 350x 350x 9x 350x 340x 340x 340x 349x 350x 105x 349x 349x 349x 349x 349x 9x 349x 337x 337x 337x 341x 349x 105x 6451x 6451x 6451x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 1x 1x 105x 105x                               105x 105x 1194x 1194x 105x 105x 2017x 2017x 105x 105x 6293x 6293x 105x 105x 3134x 3134x 105x 105x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 105x 105x 1x 1x 1x 1x 1x 105x 105x 105x 105x 105x 105x 105x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 105x 105x 105x 105x 105x 9503x 9503x 9503x 105x 1842x 1842x 1842x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x  
'use strict';
 
const {
  ArrayFrom,
  ArrayPrototypeSlice,
  ObjectDefineProperty,
  ObjectSetPrototypeOf,
  Symbol,
  Uint8Array,
} = primordials;
 
const {
  KeyObjectHandle,
  createNativeKeyObjectClass,
  kKeyTypeSecret,
  kKeyTypePublic,
  kKeyTypePrivate,
  kKeyFormatPEM,
  kKeyFormatDER,
  kKeyEncodingPKCS1,
  kKeyEncodingPKCS8,
  kKeyEncodingSPKI,
  kKeyEncodingSEC1,
} = internalBinding('crypto');
 
const {
  validateObject,
  validateOneOf,
  validateString,
} = require('internal/validators');
 
const {
  codes: {
    ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS,
    ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_OUT_OF_RANGE,
    ERR_OPERATION_FAILED,
    ERR_CRYPTO_JWK_UNSUPPORTED_CURVE,
    ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE,
    ERR_CRYPTO_INVALID_JWK,
  }
} = require('internal/errors');
 
const {
  kHandle,
  kKeyObject,
  getArrayBufferOrView,
  bigIntArrayToUnsignedBigInt,
} = require('internal/crypto/util');
 
const {
  isAnyArrayBuffer,
  isArrayBufferView,
} = require('internal/util/types');
 
const {
  JSTransferable,
  kClone,
  kDeserialize,
} = require('internal/worker/js_transferable');
 
const {
  customInspectSymbol: kInspect,
} = require('internal/util');
 
const { inspect } = require('internal/util/inspect');
 
const { Buffer } = require('buffer');
 
const kAlgorithm = Symbol('kAlgorithm');
const kExtractable = Symbol('kExtractable');
const kKeyType = Symbol('kKeyType');
const kKeyUsages = Symbol('kKeyUsages');
 
// Key input contexts.
const kConsumePublic = 0;
const kConsumePrivate = 1;
const kCreatePublic = 2;
const kCreatePrivate = 3;
 
const encodingNames = [];
for (const m of [[kKeyEncodingPKCS1, 'pkcs1'], [kKeyEncodingPKCS8, 'pkcs8'],
                 [kKeyEncodingSPKI, 'spki'], [kKeyEncodingSEC1, 'sec1']])
  encodingNames[m[0]] = m[1];
 
// Creating the KeyObject class is a little complicated due to inheritance
// and that fact that KeyObjects should be transferrable between threads,
// which requires the KeyObject base class to be implemented in C++.
// The creation requires a callback to make sure that the NativeKeyObject
// base class cannot exist without the other KeyObject implementations.
const {
  0: KeyObject,
  1: SecretKeyObject,
  2: PublicKeyObject,
  3: PrivateKeyObject,
} = createNativeKeyObjectClass((NativeKeyObject) => {
  // Publicly visible KeyObject class.
  class KeyObject extends NativeKeyObject {
    constructor(type, handle) {
      if (type !== 'secret' && type !== 'public' && type !== 'private')
        throw new ERR_INVALID_ARG_VALUE('type', type);
      if (typeof handle !== 'object' || !(handle instanceof KeyObjectHandle))
        throw new ERR_INVALID_ARG_TYPE('handle', 'object', handle);
 
      super(handle);
 
      this[kKeyType] = type;
 
      ObjectDefineProperty(this, kHandle, {
        value: handle,
        enumerable: false,
        configurable: false,
        writable: false
      });
    }
 
    get type() {
      return this[kKeyType];
    }
 
    static from(key) {
      if (!isCryptoKey(key))
        throw new ERR_INVALID_ARG_TYPE('key', 'CryptoKey', key);
      return key[kKeyObject];
    }
  }
 
  class SecretKeyObject extends KeyObject {
    constructor(handle) {
      super('secret', handle);
    }
 
    get symmetricKeySize() {
      return this[kHandle].getSymmetricKeySize();
    }
 
    export(options) {
      if (options !== undefined) {
        validateObject(options, 'options');
        validateOneOf(
          options.format, 'options.format', [undefined, 'buffer', 'jwk']);
        if (options.format === 'jwk') {
          return this[kHandle].exportJwk({});
        }
      }
      return this[kHandle].export();
    }
  }
 
  const kAsymmetricKeyType = Symbol('kAsymmetricKeyType');
  const kAsymmetricKeyDetails = Symbol('kAsymmetricKeyDetails');
  const kAsymmetricKeyJWKProperties = Symbol('kAsymmetricKeyJWKProperties');
 
  function normalizeKeyDetails(details = {}) {
    if (details.publicExponent !== undefined) {
      return {
        ...details,
        publicExponent:
          bigIntArrayToUnsignedBigInt(new Uint8Array(details.publicExponent))
      };
    }
    return details;
  }
 
  class AsymmetricKeyObject extends KeyObject {
    // eslint-disable-next-line no-useless-constructor
    constructor(type, handle) {
      super(type, handle);
    }
 
    get asymmetricKeyType() {
      return this[kAsymmetricKeyType] ||
             (this[kAsymmetricKeyType] = this[kHandle].getAsymmetricKeyType());
    }
 
    get asymmetricKeyDetails() {
      switch (this.asymmetricKeyType) {
        case 'rsa':
        case 'rsa-pss':
        case 'dsa':
        case 'ec':
          return this[kAsymmetricKeyDetails] ||
             (this[kAsymmetricKeyDetails] = normalizeKeyDetails(
               this[kHandle].keyDetail({})
             ));
        default:
          return {};
      }
    }
 
    [kAsymmetricKeyJWKProperties]() {
      switch (this.asymmetricKeyType) {
        case 'rsa': return {};
        case 'ec':
          switch (this.asymmetricKeyDetails.namedCurve) {
            case 'prime256v1': return { crv: 'P-256' };
            case 'secp256k1': return { crv: 'secp256k1' };
            case 'secp384r1': return { crv: 'P-384' };
            case 'secp521r1': return { crv: 'P-521' };
            default:
              throw new ERR_CRYPTO_JWK_UNSUPPORTED_CURVE(
                this.asymmetricKeyDetails.namedCurve);
          }
        case 'ed25519': return { crv: 'Ed25519' };
        case 'ed448': return { crv: 'Ed448' };
        case 'x25519': return { crv: 'X25519' };
        case 'x448': return { crv: 'X448' };
        default:
          throw new ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE();
      }
    }
  }
 
  class PublicKeyObject extends AsymmetricKeyObject {
    constructor(handle) {
      super('public', handle);
    }
 
    export(options) {
      if (options && options.format === 'jwk') {
        const properties = this[kAsymmetricKeyJWKProperties]();
        return this[kHandle].exportJwk(properties);
      }
      const {
        format,
        type
      } = parsePublicKeyEncoding(options, this.asymmetricKeyType);
      return this[kHandle].export(format, type);
    }
  }
 
  class PrivateKeyObject extends AsymmetricKeyObject {
    constructor(handle) {
      super('private', handle);
    }
 
    export(options) {
      if (options && options.format === 'jwk') {
        if (options.passphrase !== undefined) {
          throw new ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(
            'jwk', 'does not support encryption');
        }
        const properties = this[kAsymmetricKeyJWKProperties]();
        return this[kHandle].exportJwk(properties);
      }
      const {
        format,
        type,
        cipher,
        passphrase
      } = parsePrivateKeyEncoding(options, this.asymmetricKeyType);
      return this[kHandle].export(format, type, cipher, passphrase);
    }
  }
 
  return [KeyObject, SecretKeyObject, PublicKeyObject, PrivateKeyObject];
});
 
function parseKeyFormat(formatStr, defaultFormat, optionName) {
  if (formatStr === undefined && defaultFormat !== undefined)
    return defaultFormat;
  else if (formatStr === 'pem')
    return kKeyFormatPEM;
  else if (formatStr === 'der')
    return kKeyFormatDER;
  throw new ERR_INVALID_ARG_VALUE(optionName, formatStr);
}
 
function parseKeyType(typeStr, required, keyType, isPublic, optionName) {
  if (typeStr === undefined && !required) {
    return undefined;
  } else if (typeStr === 'pkcs1') {
    if (keyType !== undefined && keyType !== 'rsa') {
      throw new ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(
        typeStr, 'can only be used for RSA keys');
    }
    return kKeyEncodingPKCS1;
  } else if (typeStr === 'spki' && isPublic !== false) {
    return kKeyEncodingSPKI;
  } else if (typeStr === 'pkcs8' && isPublic !== true) {
    return kKeyEncodingPKCS8;
  } else if (typeStr === 'sec1' && isPublic !== true) {
    if (keyType !== undefined && keyType !== 'ec') {
      throw new ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(
        typeStr, 'can only be used for EC keys');
    }
    return kKeyEncodingSEC1;
  }
 
  throw new ERR_INVALID_ARG_VALUE(optionName, typeStr);
}
 
function option(name, objName) {
  return objName === undefined ?
    `options.${name}` : `options.${objName}.${name}`;
}
 
function parseKeyFormatAndType(enc, keyType, isPublic, objName) {
  const { format: formatStr, type: typeStr } = enc;
 
  const isInput = keyType === undefined;
  const format = parseKeyFormat(formatStr,
                                isInput ? kKeyFormatPEM : undefined,
                                option('format', objName));
 
  const type = parseKeyType(typeStr,
                            !isInput || format === kKeyFormatDER,
                            keyType,
                            isPublic,
                            option('type', objName));
 
  return { format, type };
}
 
function isStringOrBuffer(val) {
  return typeof val === 'string' ||
         isArrayBufferView(val) ||
         isAnyArrayBuffer(val);
}
 
function parseKeyEncoding(enc, keyType, isPublic, objName) {
  if (enc === null || typeof enc !== 'object')
    throw new ERR_INVALID_ARG_TYPE('options', 'object', enc);
 
  const isInput = keyType === undefined;
 
  const {
    format,
    type
  } = parseKeyFormatAndType(enc, keyType, isPublic, objName);
 
  let cipher, passphrase, encoding;
  if (isPublic !== true) {
    ({ cipher, passphrase, encoding } = enc);
 
    if (!isInput) {
      if (cipher != null) {
        if (typeof cipher !== 'string')
          throw new ERR_INVALID_ARG_VALUE(option('cipher', objName), cipher);
        if (format === kKeyFormatDER &&
            (type === kKeyEncodingPKCS1 ||
             type === kKeyEncodingSEC1)) {
          throw new ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(
            encodingNames[type], 'does not support encryption');
        }
      } else if (passphrase !== undefined) {
        throw new ERR_INVALID_ARG_VALUE(option('cipher', objName), cipher);
      }
    }
 
    if ((isInput && passphrase !== undefined &&
         !isStringOrBuffer(passphrase)) ||
        (!isInput && cipher != null && !isStringOrBuffer(passphrase))) {
      throw new ERR_INVALID_ARG_VALUE(option('passphrase', objName),
                                      passphrase);
    }
  }
 
  if (passphrase !== undefined)
    passphrase = getArrayBufferOrView(passphrase, 'key.passphrase', encoding);
 
  return { format, type, cipher, passphrase };
}
 
// Parses the public key encoding based on an object. keyType must be undefined
// when this is used to parse an input encoding and must be a valid key type if
// used to parse an output encoding.
function parsePublicKeyEncoding(enc, keyType, objName) {
  return parseKeyEncoding(enc, keyType, keyType ? true : undefined, objName);
}
 
// Parses the private key encoding based on an object. keyType must be undefined
// when this is used to parse an input encoding and must be a valid key type if
// used to parse an output encoding.
function parsePrivateKeyEncoding(enc, keyType, objName) {
  return parseKeyEncoding(enc, keyType, false, objName);
}
 
function getKeyObjectHandle(key, ctx) {
  if (ctx === kCreatePrivate) {
    throw new ERR_INVALID_ARG_TYPE(
      'key',
      ['string', 'ArrayBuffer', 'Buffer', 'TypedArray', 'DataView'],
      key
    );
  }
 
  if (key.type !== 'private') {
    if (ctx === kConsumePrivate || ctx === kCreatePublic)
      throw new ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE(key.type, 'private');
    if (key.type !== 'public') {
      throw new ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE(key.type,
                                                   'private or public');
    }
  }
 
  return key[kHandle];
}
 
function getKeyTypes(allowKeyObject, bufferOnly = false) {
  const types = [
    'ArrayBuffer',
    'Buffer',
    'TypedArray',
    'DataView',
    'string', // Only if bufferOnly == false
    'KeyObject', // Only if allowKeyObject == true && bufferOnly == false
    'CryptoKey', // Only if allowKeyObject == true && bufferOnly == false
  ];
  if (bufferOnly) {
    return ArrayPrototypeSlice(types, 0, 4);
  } else if (!allowKeyObject) {
    return ArrayPrototypeSlice(types, 0, 5);
  }
  return types;
}
 
function getKeyObjectHandleFromJwk(key, ctx) {
  validateObject(key, 'key');
  validateOneOf(
    key.kty, 'key.kty', ['RSA', 'EC', 'OKP']);
  const isPublic = ctx === kConsumePublic || ctx === kCreatePublic;
 
  if (key.kty === 'OKP') {
    validateString(key.crv, 'key.crv');
    validateOneOf(
      key.crv, 'key.crv', ['Ed25519', 'Ed448', 'X25519', 'X448']);
    validateString(key.x, 'key.x');
 
    if (!isPublic)
      validateString(key.d, 'key.d');
 
    let keyData;
    if (isPublic)
      keyData = Buffer.from(key.x, 'base64');
    else
      keyData = Buffer.from(key.d, 'base64');
 
    switch (key.crv) {
      case 'Ed25519':
      case 'X25519':
        if (keyData.byteLength !== 32) {
          throw new ERR_CRYPTO_INVALID_JWK();
        }
        break;
      case 'Ed448':
        if (keyData.byteLength !== 57) {
          throw new ERR_CRYPTO_INVALID_JWK();
        }
        break;
      case 'X448':
        if (keyData.byteLength !== 56) {
          throw new ERR_CRYPTO_INVALID_JWK();
        }
        break;
    }
 
    const handle = new KeyObjectHandle();
    if (isPublic) {
      handle.initEDRaw(
        `NODE-${key.crv.toUpperCase()}`,
        keyData,
        kKeyTypePublic);
    } else {
      handle.initEDRaw(
        `NODE-${key.crv.toUpperCase()}`,
        keyData,
        kKeyTypePrivate);
    }
 
    return handle;
  }
 
  if (key.kty === 'EC') {
    validateString(key.crv, 'key.crv');
    validateOneOf(
      key.crv, 'key.crv', ['P-256', 'secp256k1', 'P-384', 'P-521']);
    validateString(key.x, 'key.x');
    validateString(key.y, 'key.y');
 
    const jwk = {
      kty: key.kty,
      crv: key.crv,
      x: key.x,
      y: key.y
    };
 
    if (!isPublic) {
      validateString(key.d, 'key.d');
      jwk.d = key.d;
    }
 
    const handle = new KeyObjectHandle();
    const type = handle.initJwk(jwk, jwk.crv);
    if (type === undefined)
      throw new ERR_CRYPTO_INVALID_JWK();
 
    return handle;
  }
 
  // RSA
  validateString(key.n, 'key.n');
  validateString(key.e, 'key.e');
 
  const jwk = {
    kty: key.kty,
    n: key.n,
    e: key.e
  };
 
  if (!isPublic) {
    validateString(key.d, 'key.d');
    validateString(key.p, 'key.p');
    validateString(key.q, 'key.q');
    validateString(key.dp, 'key.dp');
    validateString(key.dq, 'key.dq');
    validateString(key.qi, 'key.qi');
    jwk.d = key.d;
    jwk.p = key.p;
    jwk.q = key.q;
    jwk.dp = key.dp;
    jwk.dq = key.dq;
    jwk.qi = key.qi;
  }
 
  const handle = new KeyObjectHandle();
  const type = handle.initJwk(jwk);
  if (type === undefined)
    throw new ERR_CRYPTO_INVALID_JWK();
 
  return handle;
}
 
function prepareAsymmetricKey(key, ctx) {
  if (isKeyObject(key)) {
    // Best case: A key object, as simple as that.
    return { data: getKeyObjectHandle(key, ctx) };
  } else if (isCryptoKey(key)) {
    return { data: getKeyObjectHandle(key[kKeyObject], ctx) };
  } else if (isStringOrBuffer(key)) {
    // Expect PEM by default, mostly for backward compatibility.
    return { format: kKeyFormatPEM, data: getArrayBufferOrView(key, 'key') };
  } else if (typeof key === 'object') {
    const { key: data, encoding, format } = key;
    // The 'key' property can be a KeyObject as well to allow specifying
    // additional options such as padding along with the key.
    if (isKeyObject(data))
      return { data: getKeyObjectHandle(data, ctx) };
    else if (isCryptoKey(data))
      return { data: getKeyObjectHandle(data[kKeyObject], ctx) };
    else if (isJwk(data) && format === 'jwk')
      return { data: getKeyObjectHandleFromJwk(data, ctx), format: 'jwk' };
    // Either PEM or DER using PKCS#1 or SPKI.
    if (!isStringOrBuffer(data)) {
      throw new ERR_INVALID_ARG_TYPE(
        'key.key',
        getKeyTypes(ctx !== kCreatePrivate),
        data);
    }
 
    const isPublic =
      (ctx === kConsumePrivate || ctx === kCreatePrivate) ? false : undefined;
    return {
      data: getArrayBufferOrView(data, 'key', encoding),
      ...parseKeyEncoding(key, undefined, isPublic)
    };
  }
  throw new ERR_INVALID_ARG_TYPE(
    'key',
    getKeyTypes(ctx !== kCreatePrivate),
    key);
}
 
function preparePrivateKey(key) {
  return prepareAsymmetricKey(key, kConsumePrivate);
}
 
function preparePublicOrPrivateKey(key) {
  return prepareAsymmetricKey(key, kConsumePublic);
}
 
function prepareSecretKey(key, encoding, bufferOnly = false) {
  if (!bufferOnly) {
    if (isKeyObject(key)) {
      if (key.type !== 'secret')
        throw new ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE(key.type, 'secret');
      return key[kHandle];
    } else if (isCryptoKey(key)) {
      if (key.type !== 'secret')
        throw new ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE(key.type, 'secret');
      return key[kKeyObject][kHandle];
    }
  }
  if (typeof key !== 'string' &&
      !isArrayBufferView(key) &&
      !isAnyArrayBuffer(key)) {
    throw new ERR_INVALID_ARG_TYPE(
      'key',
      getKeyTypes(!bufferOnly, bufferOnly),
      key);
  }
  return getArrayBufferOrView(key, 'key', encoding);
}
 
function createSecretKey(key, encoding) {
  key = prepareSecretKey(key, encoding, true);
  if (key.byteLength === 0)
    throw new ERR_OUT_OF_RANGE('key.byteLength', '> 0', key.byteLength);
  const handle = new KeyObjectHandle();
  handle.init(kKeyTypeSecret, key);
  return new SecretKeyObject(handle);
}
 
function createPublicKey(key) {
  const { format, type, data, passphrase } =
    prepareAsymmetricKey(key, kCreatePublic);
  let handle;
  if (format === 'jwk') {
    handle = data;
  } else {
    handle = new KeyObjectHandle();
    handle.init(kKeyTypePublic, data, format, type, passphrase);
  }
  return new PublicKeyObject(handle);
}
 
function createPrivateKey(key) {
  const { format, type, data, passphrase } =
    prepareAsymmetricKey(key, kCreatePrivate);
  let handle;
  if (format === 'jwk') {
    handle = data;
  } else {
    handle = new KeyObjectHandle();
    handle.init(kKeyTypePrivate, data, format, type, passphrase);
  }
  return new PrivateKeyObject(handle);
}
 
function isKeyObject(obj) {
  return obj != null && obj[kKeyType] !== undefined;
}
 
// Our implementation of CryptoKey is a simple wrapper around a KeyObject
// that adapts it to the standard interface. This implementation also
// extends the JSTransferable class, allowing the CryptoKey to be cloned
// to Workers.
// TODO(@jasnell): Embedder environments like electron may have issues
// here similar to other things like URL. A chromium provided CryptoKey
// will not be recognized as a Node.js CryptoKey, and vice versa. It
// would be fantastic if we could find a way of making those interop.
class CryptoKey extends JSTransferable {
  constructor() {
    throw new ERR_OPERATION_FAILED('Illegal constructor');
  }
 
  [kInspect](depth, options) {
    if (depth < 0)
      return this;

    const opts = {
      ...options,
      depth: options.depth == null ? null : options.depth - 1
    };

    return `CryptoKey ${inspect({
      type: this.type,
      extractable: this.extractable,
      algorithm: this.algorithm,
      usages: this.usages
    }, opts)}`;
  }
 
  get type() {
    return this[kKeyObject].type;
  }
 
  get extractable() {
    return this[kExtractable];
  }
 
  get algorithm() {
    return this[kAlgorithm];
  }
 
  get usages() {
    return ArrayFrom(this[kKeyUsages]);
  }
 
  [kClone]() {
    const keyObject = this[kKeyObject];
    const algorithm = this.algorithm;
    const extractable = this.extractable;
    const usages = this.usages;
 
    return {
      data: {
        keyObject,
        algorithm,
        usages,
        extractable,
      },
      deserializeInfo: 'internal/crypto/keys:InternalCryptoKey'
    };
  }
 
  [kDeserialize]({ keyObject, algorithm, usages, extractable }) {
    this[kKeyObject] = keyObject;
    this[kAlgorithm] = algorithm;
    this[kKeyUsages] = usages;
    this[kExtractable] = extractable;
  }
}
 
// All internal code must use new InternalCryptoKey to create
// CryptoKey instances. The CryptoKey class is exposed to end
// user code but is not permitted to be constructed directly.
class InternalCryptoKey extends JSTransferable {
  constructor(
    keyObject,
    algorithm,
    keyUsages,
    extractable) {
    super();
    // Using symbol properties here currently instead of private
    // properties because (for now) the performance penalty of
    // private fields is still too high.
    this[kKeyObject] = keyObject;
    this[kAlgorithm] = algorithm;
    this[kExtractable] = extractable;
    this[kKeyUsages] = keyUsages;
  }
}
 
InternalCryptoKey.prototype.constructor = CryptoKey;
ObjectSetPrototypeOf(InternalCryptoKey.prototype, CryptoKey.prototype);
 
function isCryptoKey(obj) {
  return obj != null && obj[kKeyObject] !== undefined;
}
 
function isJwk(obj) {
  return obj != null && obj.kty !== undefined;
}
 
module.exports = {
  // Public API.
  createSecretKey,
  createPublicKey,
  createPrivateKey,
  KeyObject,
  CryptoKey,
  InternalCryptoKey,
 
  // These are designed for internal use only and should not be exposed.
  parsePublicKeyEncoding,
  parsePrivateKeyEncoding,
  parseKeyEncoding,
  preparePrivateKey,
  preparePublicOrPrivateKey,
  prepareSecretKey,
  SecretKeyObject,
  PublicKeyObject,
  PrivateKeyObject,
  isKeyObject,
  isCryptoKey,
};