All files / lib/internal/crypto cfrg.js

90.14% Statements 311/345
84.33% Branches 70/83
100% Functions 6/6
90.14% Lines 311/345

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 34621x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 138x 138x 138x 138x 138x 138x 52x 52x 138x 138x 138x 86x 86x 40x 40x 86x 46x 46x 86x 138x 138x 8x 8x 8x 8x 138x 21x 36x 36x 36x 36x 36x 36x 36x 18x       18x 36x 9x       9x 36x 9x       9x 36x 36x 36x 36x     36x 36x 36x 21x 244x 244x 244x 244x 244x 244x 244x 244x 244x 124x 60x 60x 60x 60x 64x 244x 244x 244x 120x 72x 72x 72x 72x 48x 244x 112x 112x 220x 40x 40x 244x 24x 24x 244x 24x 24x 244x 24x 24x 244x 112x 112x       112x 112x 112x 112x 112x 220x 244x 244x 64x 64x 64x 244x 244x 244x 48x 48x 48x 244x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 244x 21x 8x 8x 8x 8x 8x 8x 8x 21x 170x 170x 170x 170x 170x 170x 170x 170x 170x 170x 170x 170x 170x 53x 53x 53x 53x 53x 53x 53x 53x 170x 49x 49x 49x 49x 49x 49x 49x 49x 170x 64x 64x 64x 64x 64x 64x 32x 32x 64x                                 32x 32x 32x 64x 64x 64x     32x 64x 16x 16x 16x 16x 8x 16x     16x 32x 32x 32x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 170x 4x 4x 4x 4x 170x 130x 170x 4x 4x 126x 126x 126x 126x 126x 126x 170x 21x 42x 42x 42x 42x 42x 42x 42x 42x 42x 4x 4x 4x 2x 2x 2x 4x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 42x 21x 21x 21x 21x 21x 21x 21x  
'use strict';
 
const {
  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,
  promisify,
} = require('internal/util');
 
const {
  generateKeyPair: _generateKeyPair,
} = require('internal/crypto/keygen');
 
const {
  InternalCryptoKey,
  PrivateKeyObject,
  PublicKeyObject,
  createPrivateKey,
  createPublicKey,
} = require('internal/crypto/keys');
 
const generateKeyPair = promisify(_generateKeyPair);
 
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 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;
  }
  let genKeyType;
  switch (name) {
    case 'Ed25519':
      genKeyType = 'ed25519';
      break;
    case 'Ed448':
      genKeyType = 'ed448';
      break;
    case 'X25519':
      genKeyType = 'x25519';
      break;
    case 'X448':
      genKeyType = 'x448';
      break;
  }
 
  const keyPair = await generateKeyPair(genKeyType).catch((err) => {
    throw lazyDOMException(
      'The operation failed for an operation-specific reason',
      { name: 'OperationError', cause: err });
  });
 
  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 keyAlgorithm = { name };
 
  const publicKey =
    new InternalCryptoKey(
      keyPair.publicKey,
      keyAlgorithm,
      publicUsages,
      true);
 
  const privateKey =
    new InternalCryptoKey(
      keyPair.privateKey,
      keyAlgorithm,
      privateUsages,
      extractable);
 
  return { privateKey, publicKey };
}
 
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');
      if (keyData.crv !== name)
        throw lazyDOMException('Subtype mismatch', '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 = createCFRGRawKey(name, keyData, true);
      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,
};