All files / lib/internal/crypto keygen.js

99.26% Statements 407/410
94.87% Branches 111/117
100% Functions 12/12
99.26% Lines 407/410

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 41134x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 524x 524x 524x 524x 524x 473x 524x 34x 333x 333x 6x 6x 6x 333x 333x 333x 333x 333x 259x 175x 175x 175x 175x 175x 333x 333x 333x 333x 34x 34x 34x 34x 34x 34x 34x 100x 100x 100x 34x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 34x 425x 425x 425x 425x 425x 338x 425x 84x 84x 84x 84x 84x 87x 3x 3x 3x 406x 406x 425x 340x 425x 63x 63x 63x 63x 63x 63x 63x 66x 3x 3x 3x 376x 376x 376x 376x 376x 376x 376x 376x 376x 425x 34x 428x 428x 428x 428x 428x 428x 428x 375x 375x 428x 428x 190x 190x 190x 190x 190x 190x 190x 32x 190x 143x 143x 164x 190x 144x 144x 144x 144x 144x 144x 144x 20x 20x 20x 20x 20x 20x 20x 20x 61x 18x 61x 14x 61x 61x 3x 1x 1x 1x 3x 3x 3x 1x 1x 3x 61x 3x 1x 1x 1x 3x 3x 3x 1x 1x 3x 7x 7x 7x 7x 7x 7x 190x 190x 190x 190x 190x 428x 28x 28x 28x 28x 28x 28x 28x 1x 28x 13x 3x 3x 3x 3x 3x 3x 3x 428x 90x 90x 90x 90x 90x 90x 90x 4x 4x 1x 1x 85x 85x 85x 85x 85x 85x 85x 428x 428x 428x 428x 48x 48x 48x 48x 23x 23x 48x 5x 5x 48x 10x 10x 48x 10x 10x 48x 48x 48x 428x 18x 18x 18x 18x 9x 9x 8x 9x 7x 9x 6x 6x 6x 6x 6x 8x 13x 2x 2x 1x 1x 18x 5x 6x 1x 1x 1x 4x 18x 2x 2x 2x 2x 18x 18x 18x 18x 428x 428x 428x 1x 428x 34x 34x 34x 165x 165x 165x 165x 165x 165x 102x 102x 165x 37x 37x 165x 2x 2x 2x 2x 165x 118x 118x 165x 34x 118x 118x 118x 4x 4x 4x 118x 4x 4x 118x 34x 138x 138x       138x 138x 138x 138x 138x 138x 114x 114x 138x 138x 138x 138x 34x 28x 28x 28x 28x 34x 34x 34x 34x 34x 34x 34x  
'use strict';
 
const {
  FunctionPrototypeCall,
  ObjectDefineProperty,
  SafeArrayIterator,
} = primordials;
 
const {
  DhKeyPairGenJob,
  DsaKeyPairGenJob,
  EcKeyPairGenJob,
  NidKeyPairGenJob,
  RsaKeyPairGenJob,
  SecretKeyGenJob,
  kCryptoJobAsync,
  kCryptoJobSync,
  kKeyVariantRSA_PSS,
  kKeyVariantRSA_SSA_PKCS1_v1_5,
  EVP_PKEY_ED25519,
  EVP_PKEY_ED448,
  EVP_PKEY_X25519,
  EVP_PKEY_X448,
  OPENSSL_EC_NAMED_CURVE,
  OPENSSL_EC_EXPLICIT_CURVE,
} = internalBinding('crypto');
 
const {
  PublicKeyObject,
  PrivateKeyObject,
  SecretKeyObject,
  parsePublicKeyEncoding,
  parsePrivateKeyEncoding,
  isJwk
} = require('internal/crypto/keys');
 
const {
  kAesKeyLengths,
} = require('internal/crypto/util');
 
const {
  customPromisifyArgs,
  kEmptyObject,
} = require('internal/util');
 
const {
  validateFunction,
  validateBuffer,
  validateString,
  validateInteger,
  validateObject,
  validateOneOf,
  validateInt32,
  validateUint32,
} = require('internal/validators');
 
const {
  codes: {
    ERR_INCOMPATIBLE_OPTION_PAIR,
    ERR_INVALID_ARG_VALUE,
    ERR_MISSING_OPTION,
  }
} = require('internal/errors');
 
const { isArrayBufferView } = require('internal/util/types');
 
const { getOptionValue } = require('internal/options');
 
function wrapKey(key, ctor) {
  if (typeof key === 'string' ||
      isArrayBufferView(key) ||
      isJwk(key))
    return key;
  return new ctor(key);
}
 
function generateKeyPair(type, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = undefined;
  }
  validateFunction(callback, 'callback');
 
  const job = createJob(kCryptoJobAsync, type, options);
 
  job.ondone = (error, result) => {
    if (error) return FunctionPrototypeCall(callback, job, error);
    // If no encoding was chosen, return key objects instead.
    let { 0: pubkey, 1: privkey } = result;
    pubkey = wrapKey(pubkey, PublicKeyObject);
    privkey = wrapKey(privkey, PrivateKeyObject);
    FunctionPrototypeCall(callback, job, null, pubkey, privkey);
  };
 
  job.run();
}
 
ObjectDefineProperty(generateKeyPair, customPromisifyArgs, {
  __proto__: null,
  value: ['publicKey', 'privateKey'],
  enumerable: false
});
 
function generateKeyPairSync(type, options) {
  return handleError(createJob(kCryptoJobSync, type, options).run());
}
 
function handleError(ret) {
  if (ret == null)
    return; // async
 
  const { 0: err, 1: keys } = ret;
  if (err !== undefined)
    throw err;
 
  const { 0: publicKey, 1: privateKey } = keys;
 
  // If no encoding was chosen, return key objects instead.
  return {
    publicKey: wrapKey(publicKey, PublicKeyObject),
    privateKey: wrapKey(privateKey, PrivateKeyObject)
  };
}
 
function parseKeyEncoding(keyType, options = kEmptyObject) {
  const { publicKeyEncoding, privateKeyEncoding } = options;
 
  let publicFormat, publicType;
  if (publicKeyEncoding == null) {
    publicFormat = publicType = undefined;
  } else if (typeof publicKeyEncoding === 'object') {
    ({
      format: publicFormat,
      type: publicType
    } = parsePublicKeyEncoding(publicKeyEncoding, keyType,
                               'publicKeyEncoding'));
  } else {
    throw new ERR_INVALID_ARG_VALUE('options.publicKeyEncoding',
                                    publicKeyEncoding);
  }
 
  let privateFormat, privateType, cipher, passphrase;
  if (privateKeyEncoding == null) {
    privateFormat = privateType = undefined;
  } else if (typeof privateKeyEncoding === 'object') {
    ({
      format: privateFormat,
      type: privateType,
      cipher,
      passphrase
    } = parsePrivateKeyEncoding(privateKeyEncoding, keyType,
                                'privateKeyEncoding'));
  } else {
    throw new ERR_INVALID_ARG_VALUE('options.privateKeyEncoding',
                                    privateKeyEncoding);
  }
 
  return [
    publicFormat,
    publicType,
    privateFormat,
    privateType,
    cipher,
    passphrase,
  ];
}
 
function createJob(mode, type, options) {
  validateString(type, 'type');
 
  const encoding = new SafeArrayIterator(parseKeyEncoding(type, options));
 
  if (options !== undefined)
    validateObject(options, 'options');
 
  switch (type) {
    case 'rsa':
    case 'rsa-pss':
    {
      validateObject(options, 'options');
      const { modulusLength } = options;
      validateUint32(modulusLength, 'options.modulusLength');
 
      let { publicExponent } = options;
      if (publicExponent == null) {
        publicExponent = 0x10001;
      } else {
        validateUint32(publicExponent, 'options.publicExponent');
      }
 
      if (type === 'rsa') {
        return new RsaKeyPairGenJob(
          mode,
          kKeyVariantRSA_SSA_PKCS1_v1_5,  // Used also for RSA-OAEP
          modulusLength,
          publicExponent,
          ...encoding);
      }
 
      const {
        hash, mgf1Hash, hashAlgorithm, mgf1HashAlgorithm, saltLength
      } = options;
 
      const pendingDeprecation = getOptionValue('--pending-deprecation');
 
      if (saltLength !== undefined)
        validateInt32(saltLength, 'options.saltLength', 0);
      if (hashAlgorithm !== undefined)
        validateString(hashAlgorithm, 'options.hashAlgorithm');
      if (mgf1HashAlgorithm !== undefined)
        validateString(mgf1HashAlgorithm, 'options.mgf1HashAlgorithm');
      if (hash !== undefined) {
        pendingDeprecation && process.emitWarning(
          '"options.hash" is deprecated, ' +
          'use "options.hashAlgorithm" instead.',
          'DeprecationWarning',
          'DEP0154');
        validateString(hash, 'options.hash');
        if (hashAlgorithm && hash !== hashAlgorithm) {
          throw new ERR_INVALID_ARG_VALUE('options.hash', hash);
        }
      }
      if (mgf1Hash !== undefined) {
        pendingDeprecation && process.emitWarning(
          '"options.mgf1Hash" is deprecated, ' +
          'use "options.mgf1HashAlgorithm" instead.',
          'DeprecationWarning',
          'DEP0154');
        validateString(mgf1Hash, 'options.mgf1Hash');
        if (mgf1HashAlgorithm && mgf1Hash !== mgf1HashAlgorithm) {
          throw new ERR_INVALID_ARG_VALUE('options.mgf1Hash', mgf1Hash);
        }
      }
 
      return new RsaKeyPairGenJob(
        mode,
        kKeyVariantRSA_PSS,
        modulusLength,
        publicExponent,
        hashAlgorithm || hash,
        mgf1HashAlgorithm || mgf1Hash,
        saltLength,
        ...encoding);
    }
    case 'dsa':
    {
      validateObject(options, 'options');
      const { modulusLength } = options;
      validateUint32(modulusLength, 'options.modulusLength');
 
      let { divisorLength } = options;
      if (divisorLength == null) {
        divisorLength = -1;
      } else
        validateInt32(divisorLength, 'options.divisorLength', 0);
 
      return new DsaKeyPairGenJob(
        mode,
        modulusLength,
        divisorLength,
        ...encoding);
    }
    case 'ec':
    {
      validateObject(options, 'options');
      const { namedCurve } = options;
      validateString(namedCurve, 'options.namedCurve');
      let { paramEncoding } = options;
      if (paramEncoding == null || paramEncoding === 'named')
        paramEncoding = OPENSSL_EC_NAMED_CURVE;
      else if (paramEncoding === 'explicit')
        paramEncoding = OPENSSL_EC_EXPLICIT_CURVE;
      else
        throw new ERR_INVALID_ARG_VALUE('options.paramEncoding', paramEncoding);
 
      return new EcKeyPairGenJob(
        mode,
        namedCurve,
        paramEncoding,
        ...encoding);
    }
    case 'ed25519':
    case 'ed448':
    case 'x25519':
    case 'x448':
    {
      let id;
      switch (type) {
        case 'ed25519':
          id = EVP_PKEY_ED25519;
          break;
        case 'ed448':
          id = EVP_PKEY_ED448;
          break;
        case 'x25519':
          id = EVP_PKEY_X25519;
          break;
        case 'x448':
          id = EVP_PKEY_X448;
          break;
      }
      return new NidKeyPairGenJob(mode, id, ...encoding);
    }
    case 'dh':
    {
      validateObject(options, 'options');
      const { group, primeLength, prime, generator } = options;
      if (group != null) {
        if (prime != null)
          throw new ERR_INCOMPATIBLE_OPTION_PAIR('group', 'prime');
        if (primeLength != null)
          throw new ERR_INCOMPATIBLE_OPTION_PAIR('group', 'primeLength');
        if (generator != null)
          throw new ERR_INCOMPATIBLE_OPTION_PAIR('group', 'generator');
 
        validateString(group, 'options.group');
 
        return new DhKeyPairGenJob(mode, group, ...encoding);
      }
 
      if (prime != null) {
        if (primeLength != null)
          throw new ERR_INCOMPATIBLE_OPTION_PAIR('prime', 'primeLength');
 
        validateBuffer(prime, 'options.prime');
      } else if (primeLength != null) {
        validateInt32(primeLength, 'options.primeLength', 0);
      } else {
        throw new ERR_MISSING_OPTION(
          'At least one of the group, prime, or primeLength options');
      }
 
      if (generator != null) {
        validateInt32(generator, 'options.generator', 0);
      }
      return new DhKeyPairGenJob(
        mode,
        prime != null ? prime : primeLength,
        generator == null ? 2 : generator,
        ...encoding);
    }
    default:
      // Fall through
  }
  throw new ERR_INVALID_ARG_VALUE('type', type, 'must be a supported key type');
}
 
// Symmetric Key Generation
 
function generateKeyJob(mode, keyType, options) {
  validateString(keyType, 'type');
  validateObject(options, 'options');
  const { length } = options;
  switch (keyType) {
    case 'hmac':
      validateInteger(length, 'options.length', 8, 2 ** 31 - 1);
      break;
    case 'aes':
      validateOneOf(length, 'options.length', kAesKeyLengths);
      break;
    default:
      throw new ERR_INVALID_ARG_VALUE(
        'type',
        keyType,
        'must be a supported key type');
  }
 
  return new SecretKeyGenJob(mode, length);
}
 
function handleGenerateKeyError(ret) {
  if (ret === undefined)
    return; // async
 
  const { 0: err, 1: key } = ret;
  if (err !== undefined)
    throw err;
 
  return wrapKey(key, SecretKeyObject);
}
 
function generateKey(type, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = undefined;
  }
 
  validateFunction(callback, 'callback');
 
  const job = generateKeyJob(kCryptoJobAsync, type, options);
 
  job.ondone = (error, key) => {
    if (error) return FunctionPrototypeCall(callback, job, error);
    FunctionPrototypeCall(callback, job, null, wrapKey(key, SecretKeyObject));
  };
 
  handleGenerateKeyError(job.run());
}
 
function generateKeySync(type, options) {
  return handleGenerateKeyError(
    generateKeyJob(kCryptoJobSync, type, options).run());
}
 
module.exports = {
  generateKeyPair,
  generateKeyPairSync,
  generateKey,
  generateKeySync,
};