All files / lib/internal/crypto ec.js

95.9% Statements 492/513
83.87% Branches 130/155
85.71% Functions 6/7
95.9% Lines 492/513

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 51427x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 693x 693x 693x 693x 193x 193x 693x 693x 693x 693x 693x 500x 500x 247x 247x 500x 253x 253x 500x 693x 693x 12x 12x 12x 12x 693x 27x             27x 28x 28x 28x 28x 28x 28x 28x 16x 2x 2x 2x 14x 28x 7x 1x 1x 1x 6x 28x 5x 1x 1x 1x 4x 28x 24x 28x 28x     24x 28x 28x 27x 318x 318x 318x 318x 318x 318x 318x 318x 318x 318x 318x 138x 138x 138x 138x 4x 4x 318x 318x 318x 318x 140x 73x 73x 73x 73x 67x 318x 114x 91x 91x 91x 91x 114x 2x 2x 318x 318x 88x 88x 88x 88x 88x 3x 3x 88x 3x 3x 88x 2x 2x 88x 2x 2x 88x 78x 78x 78x 88x 88x 88x         88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 67x 67x 67x 88x 21x 21x 21x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 318x 27x 155x 155x 155x 155x 155x 155x 27x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 701x 21x 21x 21x 21x 21x 21x 21x 21x 21x 4x 4x 4x 21x 21x 21x 12x 12x 4x 21x 13x 13x 13x 13x 13x 701x 243x 243x 243x 243x 243x 243x 243x 243x 701x 253x 253x 253x 253x 253x 253x 253x 253x 701x 158x 158x 158x 158x 158x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 158x 156x 156x 156x 156x 89x 131x 67x 67x 156x 156x           156x 156x 156x 156x 156x 156x 8x 8x 148x 156x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 148x 148x 148x 148x 156x 156x 156x 156x 156x 158x 150x 150x 701x 26x 26x 26x 26x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 26x 26x 26x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 26x     26x 22x 26x 22x 22x 701x 669x 669x 701x 466x 466x 462x 701x 181x 10x 10x 10x 181x 8x 8x 8x 171x 4x 4x 177x 701x 12x 12x 12x 12x 701x 10x 10x 10x 10x 701x 661x 673x 621x 621x 621x 621x 621x 621x 661x 661x 661x 661x 661x 661x 701x 27x 242x 242x 242x 242x 242x 242x 242x 242x 242x 242x 242x 242x 24x 24x 20x 242x 218x 218x 218x 242x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 242x 27x 27x 27x 27x 27x 27x 27x  
'use strict';
 
const {
  ObjectKeys,
  Promise,
  SafeSet,
} = primordials;
 
const { Buffer } = require('buffer');
 
const {
  ECKeyExportJob,
  KeyObjectHandle,
  SignJob,
  kCryptoJobAsync,
  kKeyTypePrivate,
  kKeyTypePublic,
  kSignJobModeSign,
  kSignJobModeVerify,
  kSigEncP1363,
} = internalBinding('crypto');
 
const {
  validateBoolean,
  validateOneOf,
  validateString,
} = require('internal/validators');
 
const {
  codes: {
    ERR_INVALID_ARG_TYPE,
    ERR_MISSING_OPTION,
  }
} = require('internal/errors');
 
const {
  getArrayBufferOrView,
  getUsagesUnion,
  hasAnyNotIn,
  jobPromise,
  normalizeHashName,
  validateKeyOps,
  kHandle,
  kKeyObject,
  kNamedCurveAliases,
} = require('internal/crypto/util');
 
const {
  lazyDOMException,
} = require('internal/util');
 
const {
  generateKeyPair,
} = require('internal/crypto/keygen');
 
const {
  InternalCryptoKey,
  PrivateKeyObject,
  PublicKeyObject,
  createPrivateKey,
  createPublicKey,
  isKeyObject,
} = require('internal/crypto/keys');
 
function verifyAcceptableEcKeyUse(name, type, usages) {
  let checkSet;
  switch (name) {
    case 'ECDH':
      checkSet = ['deriveKey', 'deriveBits'];
      break;
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      // Fall through
    case 'ECDSA':
      switch (type) {
        case 'private':
          checkSet = ['sign'];
          break;
        case 'public':
          checkSet = ['verify'];
          break;
      }
  }
  if (hasAnyNotIn(usages, checkSet)) {
    throw lazyDOMException(
      `Unsupported key usage for a ${name} key`,
      'SyntaxError');
  }
}
 
function createECPublicKeyRaw(namedCurve, keyData) {
  const handle = new KeyObjectHandle();
  keyData = getArrayBufferOrView(keyData, 'keyData');
  if (handle.initECRaw(kNamedCurveAliases[namedCurve], keyData))
    return new PublicKeyObject(handle);
}
 
function createECRawKey(namedCurve, keyData, isPublic) {
  const handle = new KeyObjectHandle();
  keyData = getArrayBufferOrView(keyData, 'keyData');
 
  switch (namedCurve) {
    case 'NODE-ED25519':
    case 'NODE-X25519':
      if (keyData.byteLength !== 32) {
        throw lazyDOMException(
          `${namedCurve} raw keys must be exactly 32-bytes`);
      }
      break;
    case 'NODE-ED448':
      if (keyData.byteLength !== 57) {
        throw lazyDOMException(
          `${namedCurve} raw keys must be exactly 57-bytes`);
      }
      break;
    case 'NODE-X448':
      if (keyData.byteLength !== 56) {
        throw lazyDOMException(
          `${namedCurve} raw keys must be exactly 56-bytes`);
      }
      break;
  }
 
  const keyType = isPublic ? kKeyTypePublic : kKeyTypePrivate;
  if (!handle.initEDRaw(namedCurve, keyData, keyType)) {
    throw lazyDOMException('Failure to generate key object');
  }
 
  return isPublic ? new PublicKeyObject(handle) : new PrivateKeyObject(handle);
}
 
async function ecGenerateKey(algorithm, extractable, keyUsages) {
  const { name, namedCurve } = algorithm;
  validateString(namedCurve, 'algorithm.namedCurve');
  validateOneOf(
    namedCurve,
    'algorithm.namedCurve',
    ObjectKeys(kNamedCurveAliases));
 
  const usageSet = new SafeSet(keyUsages);
  switch (name) {
    case 'ECDSA':
      if (namedCurve === 'NODE-ED25519' ||
          namedCurve === 'NODE-ED448' ||
          namedCurve === 'NODE-X25519' ||
          namedCurve === 'NODE-X448') {
        throw lazyDOMException('Unsupported named curves for ECDSA');
      }
      // Fall through
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      if (hasAnyNotIn(usageSet, ['sign', 'verify'])) {
        throw lazyDOMException(
          'Unsupported key usage for an ECDSA key',
          'SyntaxError');
      }
      break;
    case 'ECDH':
      if (hasAnyNotIn(usageSet, ['deriveKey', 'deriveBits'])) {
        throw lazyDOMException(
          'Unsupported key usage for an ECDH key',
          'SyntaxError');
      }
      if (namedCurve === 'NODE-ED25519' || namedCurve === 'NODE-ED448') {
        throw lazyDOMException('Unsupported named curves for ECDH');
      }
      // Fall through
  }
  return new Promise((resolve, reject) => {
    let genKeyType;
    let genOpts;
    switch (namedCurve) {
      case 'NODE-ED25519':
        genKeyType = 'ed25519';
        break;
      case 'NODE-ED448':
        genKeyType = 'ed448';
        break;
      case 'NODE-X25519':
        genKeyType = 'x25519';
        break;
      case 'NODE-X448':
        genKeyType = 'x448';
        break;
      default:
        genKeyType = 'ec';
        genOpts = { namedCurve };
        break;
    }
    generateKeyPair(genKeyType, genOpts, (err, pubKey, privKey) => {
      if (err) {
        return reject(lazyDOMException(
          'The operation failed for an operation-specific reason',
          'OperationError'));
      }
 
      const algorithm = { name, namedCurve };
 
      let publicUsages;
      let privateUsages;
      switch (name) {
        case 'NODE-ED25519':
          // Fall through
        case 'NODE-ED448':
          // Fall through
        case 'ECDSA':
          publicUsages = getUsagesUnion(usageSet, 'verify');
          privateUsages = getUsagesUnion(usageSet, 'sign');
          break;
        case 'ECDH':
          publicUsages = [];
          privateUsages = getUsagesUnion(usageSet, 'deriveKey', 'deriveBits');
          break;
      }
 
      const publicKey =
        new InternalCryptoKey(
          pubKey,
          algorithm,
          publicUsages,
          true);
 
      const privateKey =
        new InternalCryptoKey(
          privKey,
          algorithm,
          privateUsages,
          extractable);
 
      resolve({ publicKey, privateKey });
    });
  });
}
 
function ecExportKey(key, format) {
  return jobPromise(new ECKeyExportJob(
    kCryptoJobAsync,
    format,
    key[kKeyObject][kHandle]));
}
 
async function ecImportKey(
  format,
  keyData,
  algorithm,
  extractable,
  keyUsages) {
 
  const { name, namedCurve } = algorithm;
  validateString(namedCurve, 'algorithm.namedCurve');
  validateOneOf(
    namedCurve,
    'algorithm.namedCurve',
    ObjectKeys(kNamedCurveAliases));
  let keyObject;
  const usagesSet = new SafeSet(keyUsages);
  let checkNamedCurve = true;
  switch (format) {
    case 'node.keyObject': {
      if (!isKeyObject(keyData))
        throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData);
      if (keyData.type === 'secret')
        throw lazyDOMException('Invalid key type', 'InvalidAccessException');
 
      switch (namedCurve) {
        case 'NODE-X25519':
          // Fall through
        case 'NODE-X448':
          if (algorithm.name !== 'ECDH')
            throw lazyDOMException('Invalid algorithm name.', 'DataError');
          break;
        case 'NODE-ED25519':
          // Fall through
        case 'NODE-ED448':
          if (algorithm.name !== namedCurve)
            throw lazyDOMException('Invalid algorithm name.', 'DataError');
          break;
      }
 
      verifyAcceptableEcKeyUse(name, keyData.type, usagesSet);
      keyObject = keyData;
      break;
    }
    case 'spki': {
      verifyAcceptableEcKeyUse(name, 'public', usagesSet);
      keyObject = createPublicKey({
        key: keyData,
        format: 'der',
        type: 'spki'
      });
      break;
    }
    case 'pkcs8': {
      verifyAcceptableEcKeyUse(name, 'private', usagesSet);
      keyObject = createPrivateKey({
        key: keyData,
        format: 'der',
        type: 'pkcs8'
      });
      break;
    }
    case 'jwk': {
      let curve;
      if (keyData == null || typeof keyData !== 'object')
        throw lazyDOMException('Invalid JWK keyData', 'DataError');
      switch (keyData.kty) {
        case 'OKP': {
          const isPublic = keyData.d === undefined;
 
          let type;
          switch (namedCurve) {
            case 'NODE-ED25519':
              // Fall through
            case 'NODE-ED448':
              type = `NODE-${keyData.crv.toUpperCase()}`;
              break;
            case 'NODE-X25519':
              // Fall through
            case 'NODE-X448':
              type = 'ECDH';
              break;
          }
 
          if (algorithm.name !== type)
            throw lazyDOMException('Invalid algorithm name.', 'DataError');
 
          verifyAcceptableEcKeyUse(
            type,
            isPublic ? 'public' : 'private',
            usagesSet);
          keyObject = createECRawKey(
            namedCurve,
            Buffer.from(
              isPublic ? keyData.x : keyData.d,
              'base64'),
            isPublic);
          break;
        }
        default: {
          if (keyData.kty !== 'EC')
            throw lazyDOMException('Invalid key type', 'DataError');
 
          if (keyData.d !== undefined) {
            verifyAcceptableEcKeyUse(name, 'private', usagesSet);
          } else {
            verifyAcceptableEcKeyUse(name, 'public', usagesSet);
          }
 
          if (usagesSet.size > 0 && keyData.use !== undefined) {
            if (algorithm.name === 'ECDSA' && keyData.use !== 'sig')
              throw lazyDOMException('Invalid use type', 'DataError');
            if (algorithm.name === 'ECDH' && keyData.use !== 'enc')
              throw lazyDOMException('Invalid use type', 'DataError');
          }
 
          validateKeyOps(keyData.key_ops, usagesSet);
 
          if (keyData.ext !== undefined &&
              keyData.ext === false &&
              extractable === true) {
            throw lazyDOMException('JWK is not extractable', 'DataError');
          }
 
          if (algorithm.name === 'ECDSA' && keyData.alg !== undefined) {
            if (typeof keyData.alg !== 'string')
              throw lazyDOMException('Invalid alg', 'DataError');
            switch (keyData.alg) {
              case 'ES256': curve = 'P-256'; break;
              case 'ES384': curve = 'P-384'; break;
              case 'ES512': curve = 'P-521'; break;
            }
            if (curve !== namedCurve)
              throw lazyDOMException('Named curve mismatch', 'DataError');
          }
 
          const handle = new KeyObjectHandle();
          const type = handle.initJwk(keyData, namedCurve);
          if (type === undefined)
            throw lazyDOMException('Invalid JWK keyData', 'DataError');
          keyObject = type === kKeyTypePrivate ?
            new PrivateKeyObject(handle) :
            new PublicKeyObject(handle);
        }
      }
      break;
    }
    case 'raw': {
      switch (namedCurve) {
        case 'NODE-X25519':
          // Fall through
        case 'NODE-X448':
          if (algorithm.public !== undefined)
            validateBoolean(algorithm.public, 'algorithm.public');
          if (algorithm.name !== 'ECDH')
            throw lazyDOMException('Invalid algorithm name.', 'DataError');
          verifyAcceptableEcKeyUse(
            algorithm.name,
            algorithm.public === true ? 'public' : 'private',
            usagesSet);
          keyObject = createECRawKey(namedCurve, keyData, algorithm.public);
          break;
        case 'NODE-ED25519':
          // Fall through
        case 'NODE-ED448':
          if (algorithm.public !== undefined)
            validateBoolean(algorithm.public, 'algorithm.public');
          if (algorithm.name !== namedCurve)
            throw lazyDOMException('Invalid algorithm name.', 'DataError');
          verifyAcceptableEcKeyUse(
            algorithm.name,
            algorithm.public === true ? 'public' : 'private',
            usagesSet);
          keyObject = createECRawKey(namedCurve, keyData, algorithm.public);
          break;
        default:
          verifyAcceptableEcKeyUse(name, 'public', usagesSet);
          keyObject = createECPublicKeyRaw(namedCurve, keyData);
      }
      if (keyObject === undefined)
        throw lazyDOMException('Unable to import EC key', 'OperationError');
      break;
    }
  }
 
  switch (algorithm.name) {
    case 'ECDSA':
      if (keyObject.asymmetricKeyType !== 'ec')
        throw lazyDOMException('Invalid key type', 'DataError');
      break;
    case 'ECDH':
      if (algorithm.namedCurve === 'NODE-X25519') {
        if (keyObject.asymmetricKeyType !== 'x25519')
          throw lazyDOMException('Invalid key type', 'DataError');
        checkNamedCurve = false;
      } else if (algorithm.namedCurve === 'NODE-X448') {
        if (keyObject.asymmetricKeyType !== 'x448')
          throw lazyDOMException('Invalid key type', 'DataError');
        checkNamedCurve = false;
      } else if (keyObject.asymmetricKeyType !== 'ec') {
        throw lazyDOMException('Invalid key type', 'DataError');
      }
      break;
    case 'NODE-ED25519':
      if (keyObject.asymmetricKeyType !== 'ed25519')
        throw lazyDOMException('Invalid key type', 'DataError');
      checkNamedCurve = false;
      break;
    case 'NODE-ED448':
      if (keyObject.asymmetricKeyType !== 'ed448')
        throw lazyDOMException('Invalid key type', 'DataError');
      checkNamedCurve = false;
      break;
  }
 
  if (checkNamedCurve) {
    const {
      namedCurve: checkNamedCurve
    } = keyObject[kHandle].keyDetail({});
    if (kNamedCurveAliases[namedCurve] !== checkNamedCurve)
      throw lazyDOMException('Named curve mismatch', 'DataError');
  }
 
  return new InternalCryptoKey(
    keyObject,
    { name, namedCurve },
    keyUsages,
    extractable);
}
 
function ecdsaSignVerify(key, data, { name, hash }, signature) {
  const mode = signature === undefined ? kSignJobModeSign : kSignJobModeVerify;
  const type = mode === kSignJobModeSign ? 'private' : 'public';
 
  if (key.type !== type)
    throw lazyDOMException(`Key must be a ${type} key`, 'InvalidAccessError');
 
  let hashname;
  switch (name) {
    case 'NODE-ED25519':
      // Fall through
    case 'NODE-ED448':
      if (hash !== undefined)
        throw lazyDOMException(`Hash is not permitted for ${name}`);
      break;
    default:
      if (hash === undefined)
        throw new ERR_MISSING_OPTION('algorithm.hash');
      hashname = normalizeHashName(hash.name);
  }
 
  return jobPromise(new SignJob(
    kCryptoJobAsync,
    mode,
    key[kKeyObject][kHandle],
    undefined,
    undefined,
    undefined,
    data,
    hashname,
    undefined,  // Salt length, not used with ECDSA
    undefined,  // PSS Padding, not used with ECDSA
    kSigEncP1363,
    signature));
}
 
module.exports = {
  ecExportKey,
  ecImportKey,
  ecGenerateKey,
  ecdsaSignVerify,
};