All files / lib/internal/crypto cfrg.js

86.68% Statements 306/353
80.76% Branches 63/78
85.71% Functions 6/7
86.68% Lines 306/353

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 35410x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 82x 82x 82x 82x 82x 82x 38x 38x 82x 82x 82x 44x 44x 20x 20x 44x 24x 24x 44x 82x 82x 8x 8x 8x 8x 82x 10x             10x 32x 32x 32x 32x 32x 32x 32x 16x       16x 32x 8x       8x 32x 8x       8x 32x 32x 32x 32x     32x 32x 32x 10x 34x 34x 34x 34x 34x 34x 34x 34x 34x 22x 2x 2x 2x 2x 20x 34x 34x 34x 12x 2x 2x 2x 2x 10x 34x 30x 30x 30x 30x 18x 18x 30x 2x 2x 30x 5x 5x 30x 5x 5x 30x 30x 30x         30x 30x 30x 30x 30x 30x 30x 30x 30x 20x 20x 20x 30x 30x 30x 10x 10x 10x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 34x 10x 8x 8x 8x 8x 8x 8x 8x 10x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 29x 29x 29x 29x 29x 29x 29x 29x 82x 21x 21x 21x 21x 21x 21x 21x 21x 82x 32x 32x 32x 32x 32x 32x 32x                                 32x 32x 32x 32x 32x 32x     32x 32x 16x 16x 16x 16x 8x 16x     16x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 82x             82x 74x 82x 4x 4x 70x 70x 70x 70x 70x 70x 82x 10x 26x 26x 26x 26x 26x 26x 26x 26x 26x 4x 4x 4x 2x 2x 2x 4x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 26x 10x 10x 10x 10x 10x 10x 10x  
'use strict';
 
const {
  Promise,
  SafeSet,
} = primordials;
 
const { Buffer } = require('buffer');
 
const {
  ECKeyExportJob,
  KeyObjectHandle,
  SignJob,
  kCryptoJobAsync,
  kKeyTypePrivate,
  kKeyTypePublic,
  kSignJobModeSign,
  kSignJobModeVerify,
} = internalBinding('crypto');
 
const {
  getArrayBufferOrView,
  getUsagesUnion,
  hasAnyNotIn,
  jobPromise,
  validateKeyOps,
  kHandle,
  kKeyObject,
} = require('internal/crypto/util');
 
const {
  emitExperimentalWarning,
  lazyDOMException,
} = require('internal/util');
 
const {
  generateKeyPair,
} = require('internal/crypto/keygen');
 
const {
  InternalCryptoKey,
  PrivateKeyObject,
  PublicKeyObject,
  createPrivateKey,
  createPublicKey,
} = require('internal/crypto/keys');
 
function verifyAcceptableCfrgKeyUse(name, type, usages) {
  let checkSet;
  switch (name) {
    case 'X25519':
      // Fall through
    case 'X448':
      checkSet = ['deriveKey', 'deriveBits'];
      break;
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      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(name, keyData) {
  const handle = new KeyObjectHandle();
  keyData = getArrayBufferOrView(keyData, 'keyData');
  if (handle.initECRaw(name.toLowerCase(), keyData))
    return new PublicKeyObject(handle);
}
 
function createCFRGRawKey(name, keyData, isPublic) {
  const handle = new KeyObjectHandle();
  keyData = getArrayBufferOrView(keyData, 'keyData');
 
  switch (name) {
    case 'Ed25519':
    case 'X25519':
      if (keyData.byteLength !== 32) {
        throw lazyDOMException(
          `${name} raw keys must be exactly 32-bytes`);
      }
      break;
    case 'Ed448':
      if (keyData.byteLength !== 57) {
        throw lazyDOMException(
          `${name} raw keys must be exactly 57-bytes`);
      }
      break;
    case 'X448':
      if (keyData.byteLength !== 56) {
        throw lazyDOMException(
          `${name} raw keys must be exactly 56-bytes`);
      }
      break;
  }
 
  const keyType = isPublic ? kKeyTypePublic : kKeyTypePrivate;
  if (!handle.initEDRaw(name, keyData, keyType)) {
    throw lazyDOMException('Failure to generate key object');
  }
 
  return isPublic ? new PublicKeyObject(handle) : new PrivateKeyObject(handle);
}
 
async function cfrgGenerateKey(algorithm, extractable, keyUsages) {
  const { name } = algorithm;
  emitExperimentalWarning(`The ${name} Web Crypto API algorithm`);
 
  const usageSet = new SafeSet(keyUsages);
  switch (name) {
    case 'Ed25519':
      // Fall through
    case 'Ed448':
      if (hasAnyNotIn(usageSet, ['sign', 'verify'])) {
        throw lazyDOMException(
          `Unsupported key usage for an ${name} key`,
          'SyntaxError');
      }
      break;
    case 'X25519':
      // Fall through
    case 'X448':
      if (hasAnyNotIn(usageSet, ['deriveKey', 'deriveBits'])) {
        throw lazyDOMException(
          `Unsupported key usage for an ${name} key`,
          'SyntaxError');
      }
      break;
  }
  return new Promise((resolve, reject) => {
    let genKeyType;
    switch (name) {
      case 'Ed25519':
        genKeyType = 'ed25519';
        break;
      case 'Ed448':
        genKeyType = 'ed448';
        break;
      case 'X25519':
        genKeyType = 'x25519';
        break;
      case 'X448':
        genKeyType = 'x448';
        break;
    }
    generateKeyPair(genKeyType, undefined, (err, pubKey, privKey) => {
      if (err) {
        return reject(lazyDOMException(
          'The operation failed for an operation-specific reason',
          'OperationError'));
      }
 
      const algorithm = { name };
 
      let publicUsages;
      let privateUsages;
      switch (name) {
        case 'Ed25519':
          // Fall through
        case 'Ed448':
          publicUsages = getUsagesUnion(usageSet, 'verify');
          privateUsages = getUsagesUnion(usageSet, 'sign');
          break;
        case 'X25519':
          // Fall through
        case 'X448':
          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 cfrgExportKey(key, format) {
  emitExperimentalWarning(`The ${key.algorithm.name} Web Crypto API algorithm`);
  return jobPromise(new ECKeyExportJob(
    kCryptoJobAsync,
    format,
    key[kKeyObject][kHandle]));
}
 
async function cfrgImportKey(
  format,
  keyData,
  algorithm,
  extractable,
  keyUsages) {
 
  const { name } = algorithm;
  emitExperimentalWarning(`The ${name} Web Crypto API algorithm`);
  let keyObject;
  const usagesSet = new SafeSet(keyUsages);
  switch (format) {
    case 'spki': {
      verifyAcceptableCfrgKeyUse(name, 'public', usagesSet);
      keyObject = createPublicKey({
        key: keyData,
        format: 'der',
        type: 'spki'
      });
      break;
    }
    case 'pkcs8': {
      verifyAcceptableCfrgKeyUse(name, 'private', usagesSet);
      keyObject = createPrivateKey({
        key: keyData,
        format: 'der',
        type: 'pkcs8'
      });
      break;
    }
    case 'jwk': {
      if (keyData == null || typeof keyData !== 'object')
        throw lazyDOMException('Invalid JWK keyData', 'DataError');
      if (keyData.kty !== 'OKP')
        throw lazyDOMException('Invalid key type', 'DataError');
      const isPublic = keyData.d === undefined;
 
      if (usagesSet.size > 0 && keyData.use !== undefined) {
        let checkUse;
        switch (name) {
          case 'Ed25519':
            // Fall through
          case 'Ed448':
            checkUse = 'sig';
            break;
          case 'X25519':
            // Fall through
          case 'X448':
            checkUse = 'enc';
            break;
        }
        if (keyData.use !== checkUse)
          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 (keyData.alg !== undefined) {
        if (typeof keyData.alg !== 'string')
          throw lazyDOMException('Invalid alg', 'DataError');
        if (
          (name === 'Ed25519' || name === 'Ed448') &&
          keyData.alg !== 'EdDSA'
        ) {
          throw lazyDOMException('Invalid alg', 'DataError');
        }
      }
 
      verifyAcceptableCfrgKeyUse(
        name,
        isPublic ? 'public' : 'private',
        usagesSet);
      keyObject = createCFRGRawKey(
        name,
        Buffer.from(
          isPublic ? keyData.x : keyData.d,
          'base64'),
        isPublic);
      break;
    }
    case 'raw': {
      verifyAcceptableCfrgKeyUse(name, 'public', usagesSet);
      keyObject = createECPublicKeyRaw(name, keyData);
      if (keyObject === undefined)
        throw lazyDOMException('Unable to import CFRG key', 'OperationError');
      break;
    }
  }
 
  if (keyObject.asymmetricKeyType !== name.toLowerCase()) {
    throw lazyDOMException('Invalid key type', 'DataError');
  }
 
  return new InternalCryptoKey(
    keyObject,
    { name },
    keyUsages,
    extractable);
}
 
function eddsaSignVerify(key, data, { name, context }, signature) {
  emitExperimentalWarning(`The ${name} Web Crypto API algorithm`);
  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 (name === 'Ed448' && context !== undefined) {
    context =
      getArrayBufferOrView(context, 'algorithm.context');
    if (context.byteLength !== 0) {
      throw lazyDOMException(
        'Non zero-length context is not yet supported.', 'NotSupportedError');
    }
  }
 
  return jobPromise(new SignJob(
    kCryptoJobAsync,
    mode,
    key[kKeyObject][kHandle],
    undefined,
    undefined,
    undefined,
    data,
    undefined,
    undefined,
    undefined,
    undefined,
    signature));
}
 
module.exports = {
  cfrgExportKey,
  cfrgImportKey,
  cfrgGenerateKey,
  eddsaSignVerify,
};