All files / lib/internal/crypto ec.js

93.18% Statements 287/308
82.53% Branches 52/63
83.33% Functions 5/6
93.18% Lines 287/308

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 30923x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 644x 644x 644x 644x 170x 170x 644x 474x 474x 233x 233x 474x 241x 241x 474x 644x 644x 12x 12x 12x 12x 644x 23x             23x 297x 297x 297x 297x 297x 297x 297x 297x 297x 297x 297x 129x 73x 73x 73x 73x 56x 297x 108x 91x 91x 91x 91x 297x 297x 73x 73x 73x         73x 73x 73x 73x 73x 73x 73x 56x 56x 56x 73x 17x 17x 17x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 297x 23x 148x 148x 148x 148x 148x 148x 23x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 644x 239x 239x 239x 239x 239x 239x 239x 239x 644x 249x 249x 249x 249x 249x 249x 249x 249x 644x 156x 156x 156x 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 156x 644x             644x 624x 624x 644x 644x 644x 624x 624x 620x 644x 620x 620x 620x 620x 620x 644x 620x 620x 620x 620x 620x 620x 644x 23x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 218x 23x 23x 23x 23x 23x 23x 23x  
'use strict';
 
const {
  ObjectKeys,
  Promise,
  SafeSet,
} = primordials;
 
const {
  ECKeyExportJob,
  KeyObjectHandle,
  SignJob,
  kCryptoJobAsync,
  kKeyTypePrivate,
  kSignJobModeSign,
  kSignJobModeVerify,
  kSigEncP1363,
} = internalBinding('crypto');
 
const {
  validateOneOf,
  validateString,
} = require('internal/validators');
 
const {
  codes: {
    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,
} = require('internal/crypto/keys');
 
function verifyAcceptableEcKeyUse(name, type, usages) {
  let checkSet;
  switch (name) {
    case 'ECDH':
      checkSet = ['deriveKey', 'deriveBits'];
      break;
    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);
}
 
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 (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');
      }
      // Fall through
  }
  return new Promise((resolve, reject) => {
    generateKeyPair('ec', { namedCurve }, (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 '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);
  switch (format) {
    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');
      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': {
      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':
      // Fall through
    case 'ECDH':
      if (keyObject.asymmetricKeyType !== 'ec')
        throw lazyDOMException('Invalid key type', 'DataError');
      break;
  }
 
  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');
 
  if (hash === undefined)
    throw new ERR_MISSING_OPTION('algorithm.hash');
  const 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,
};