All files / lib/internal/crypto rsa.js

94.87% Statements 352/371
82.6% Branches 57/69
100% Functions 6/6
94.87% Lines 352/371

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 37223x 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 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 1682x 1682x 1682x 1682x 852x 852x 421x 421x 852x 431x 431x 852x 852x 1682x 830x 830x 412x 412x 830x 418x 418x 830x 1682x 1682x         1682x 23x 357x 357x 357x         357x 293x 293x 293x 357x 357x 357x 357x 357x 357x 357x 357x 357x 357x 23x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 639x 642x 21x 21x 21x 21x 21x 606x 606x 606x 606x 642x         606x 606x 642x 341x 341x 116x 116x 116x 116x 225x 642x 265x 108x 108x 108x 108x 642x 382x 382x 382x 382x 382x 94x 94x 94x 382x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 474x 167x 167x 167x 167x 642x 121x 121x 121x 121x 642x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 642x 23x 347x 347x 347x 347x 347x 347x 347x 23x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 592x 592x 592x 592x 592x 592x 592x 592x 1682x 595x 595x 595x 595x 595x 595x 595x 595x 1682x 495x 495x 495x 495x 495x 495x 495x 495x 495x 495x 495x 495x         495x 495x 495x 495x 495x 495x 9x 9x 486x 486x 246x 246x 246x 246x 246x 246x 246x 486x 486x 486x 486x 495x 486x 495x 495x 495x 495x 495x 495x 1682x       1682x 1673x 1682x 6x 6x 1667x 1667x 1667x 1667x 1667x 1667x 1667x 1667x 1667x 1667x 1667x 1667x 1682x 23x 256x 256x 256x 164x 164x 164x 164x 164x 164x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 23x 23x 23x 23x 23x 23x 23x 23x 23x  
'use strict';
 
const {
  SafeSet,
  Uint8Array,
} = primordials;
 
const {
  KeyObjectHandle,
  RSACipherJob,
  RSAKeyExportJob,
  SignJob,
  kCryptoJobAsync,
  kSignJobModeSign,
  kSignJobModeVerify,
  kKeyVariantRSA_SSA_PKCS1_v1_5,
  kKeyVariantRSA_PSS,
  kKeyVariantRSA_OAEP,
  kKeyTypePrivate,
  kWebCryptoCipherEncrypt,
  RSA_PKCS1_PSS_PADDING,
} = internalBinding('crypto');
 
const {
  codes: {
    ERR_INVALID_ARG_TYPE,
    ERR_MISSING_OPTION,
  }
} = require('internal/errors');
 
const {
  validateInt32,
  validateUint32,
} = require('internal/validators');
 
const {
  bigIntArrayToUnsignedInt,
  getArrayBufferOrView,
  getUsagesUnion,
  hasAnyNotIn,
  jobPromise,
  normalizeHashName,
  validateKeyOps,
  validateMaxBufferLength,
  kHandle,
  kKeyObject,
} = require('internal/crypto/util');
 
const {
  lazyDOMException,
  promisify,
} = require('internal/util');
 
const {
  isUint8Array,
} = require('internal/util/types');
 
const {
  InternalCryptoKey,
  PrivateKeyObject,
  PublicKeyObject,
  createPublicKey,
  createPrivateKey,
} = require('internal/crypto/keys');
 
const {
  generateKeyPair: _generateKeyPair,
} = require('internal/crypto/keygen');
 
const kRsaVariants = {
  'RSASSA-PKCS1-v1_5': kKeyVariantRSA_SSA_PKCS1_v1_5,
  'RSA-PSS': kKeyVariantRSA_PSS,
  'RSA-OAEP': kKeyVariantRSA_OAEP,
};
const generateKeyPair = promisify(_generateKeyPair);
 
function verifyAcceptableRsaKeyUse(name, type, usages) {
  let checkSet;
  switch (name) {
    case 'RSA-OAEP':
      switch (type) {
        case 'private':
          checkSet = ['decrypt', 'unwrapKey'];
          break;
        case 'public':
          checkSet = ['encrypt', 'wrapKey'];
          break;
      }
      break;
    default:
      switch (type) {
        case 'private':
          checkSet = ['sign'];
          break;
        case 'public':
          checkSet = ['verify'];
          break;
      }
  }
  if (hasAnyNotIn(usages, checkSet)) {
    throw lazyDOMException(
      `Unsupported key usage for an ${name} key`,
      'SyntaxError');
  }
}
 
function rsaOaepCipher(mode, key, data, { label }) {
  const type = mode === kWebCryptoCipherEncrypt ? 'public' : 'private';
  if (key.type !== type) {
    throw lazyDOMException(
      'The requested operation is not valid for the provided key',
      'InvalidAccessError');
  }
  if (label !== undefined) {
    label = getArrayBufferOrView(label, 'algorithm.label');
    validateMaxBufferLength(label, 'algorithm.label');
  }
 
  return jobPromise(new RSACipherJob(
    kCryptoJobAsync,
    mode,
    key[kKeyObject][kHandle],
    data,
    kKeyVariantRSA_OAEP,
    normalizeHashName(key.algorithm.hash.name),
    label));
}
 
async function rsaKeyGenerate(
  algorithm,
  extractable,
  keyUsages) {
 
  const {
    name,
    modulusLength,
    publicExponent,
    hash
  } = algorithm;
 
  if (hash === undefined)
    throw new ERR_MISSING_OPTION('algorithm.hash');
  validateUint32(modulusLength, 'algorithm.modulusLength');
  if (!isUint8Array(publicExponent)) {
    throw new ERR_INVALID_ARG_TYPE(
      'algorithm.publicExponent',
      'Uint8Array',
      publicExponent);
  }
 
  const usageSet = new SafeSet(keyUsages);
 
  const publicExponentConverted = bigIntArrayToUnsignedInt(publicExponent);
  if (publicExponentConverted === undefined) {
    throw lazyDOMException(
      'The publicExponent must be equivalent to an unsigned 32-bit value',
      'OperationError');
  }
 
  switch (name) {
    case 'RSA-OAEP':
      if (hasAnyNotIn(usageSet,
                      ['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'])) {
        throw lazyDOMException(
          'Unsupported key usage for a RSA key',
          'SyntaxError');
      }
      break;
    default:
      if (hasAnyNotIn(usageSet, ['sign', 'verify'])) {
        throw lazyDOMException(
          'Unsupported key usage for a RSA key',
          'SyntaxError');
      }
  }
 
  const keypair = await generateKeyPair('rsa', {
    modulusLength,
    publicExponent: publicExponentConverted,
  }).catch((err) => {
    throw lazyDOMException(
      'The operation failed for an operation-specific reason',
      { name: 'OperationError', cause: err });
  });
 
  const keyAlgorithm = {
    name,
    modulusLength,
    publicExponent,
    hash: { name: hash.name }
  };
 
  let publicUsages;
  let privateUsages;
  switch (name) {
    case 'RSA-OAEP': {
      publicUsages = getUsagesUnion(usageSet, 'encrypt', 'wrapKey');
      privateUsages = getUsagesUnion(usageSet, 'decrypt', 'unwrapKey');
      break;
    }
    default: {
      publicUsages = getUsagesUnion(usageSet, 'verify');
      privateUsages = getUsagesUnion(usageSet, 'sign');
      break;
    }
  }
 
  const publicKey =
    new InternalCryptoKey(
      keypair.publicKey,
      keyAlgorithm,
      publicUsages,
      true);
 
  const privateKey =
    new InternalCryptoKey(
      keypair.privateKey,
      keyAlgorithm,
      privateUsages,
      extractable);
 
  return { publicKey, privateKey };
}
 
function rsaExportKey(key, format) {
  return jobPromise(new RSAKeyExportJob(
    kCryptoJobAsync,
    format,
    key[kKeyObject][kHandle],
    kRsaVariants[key.algorithm.name]));
}
 
async function rsaImportKey(
  format,
  keyData,
  algorithm,
  extractable,
  keyUsages) {
  const { hash } = algorithm;
  if (hash === undefined)
    throw new ERR_MISSING_OPTION('algorithm.hash');
 
  const usagesSet = new SafeSet(keyUsages);
  let keyObject;
  switch (format) {
    case 'spki': {
      verifyAcceptableRsaKeyUse(algorithm.name, 'public', usagesSet);
      keyObject = createPublicKey({
        key: keyData,
        format: 'der',
        type: 'spki'
      });
      break;
    }
    case 'pkcs8': {
      verifyAcceptableRsaKeyUse(algorithm.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');
 
      verifyAcceptableRsaKeyUse(
        algorithm.name,
        keyData.d !== undefined ? 'private' : 'public',
        usagesSet);
 
      if (keyData.kty !== 'RSA')
        throw lazyDOMException('Invalid key type', 'DataError');
 
      if (usagesSet.size > 0 && keyData.use !== undefined) {
        const checkUse = algorithm.name === 'RSA-OAEP' ? 'enc' : 'sig';
        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');
        const hash =
          normalizeHashName(keyData.alg, normalizeHashName.kContextWebCrypto);
        if (hash !== algorithm.hash.name)
          throw lazyDOMException('Hash mismatch', 'DataError');
      }
 
      const handle = new KeyObjectHandle();
      const type = handle.initJwk(keyData);
      if (type === undefined)
        throw lazyDOMException('Invalid JWK keyData', 'DataError');
 
      keyObject = type === kKeyTypePrivate ?
        new PrivateKeyObject(handle) :
        new PublicKeyObject(handle);
 
      break;
    }
    default:
      throw lazyDOMException(
        `Unable to import RSA key with format ${format}`,
        'NotSupportedError');
  }
 
  if (keyObject.asymmetricKeyType !== 'rsa') {
    throw lazyDOMException('Invalid key type', 'DataError');
  }
 
  const {
    modulusLength,
    publicExponent,
  } = keyObject[kHandle].keyDetail({});
 
  return new InternalCryptoKey(keyObject, {
    name: algorithm.name,
    modulusLength,
    publicExponent: new Uint8Array(publicExponent),
    hash: algorithm.hash
  }, keyUsages, extractable);
}
 
function rsaSignVerify(key, data, { saltLength }, signature) {
  let padding;
  if (key.algorithm.name === 'RSA-PSS') {
    padding = RSA_PKCS1_PSS_PADDING;
    // TODO(@jasnell): Validate maximum size of saltLength
    // based on the key size:
    //   Math.ceil((keySizeInBits - 1)/8) - digestSizeInBytes - 2
    validateInt32(saltLength, 'algorithm.saltLength', -2);
  }
 
  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');
 
  return jobPromise(new SignJob(
    kCryptoJobAsync,
    signature === undefined ? kSignJobModeSign : kSignJobModeVerify,
    key[kKeyObject][kHandle],
    undefined,
    undefined,
    undefined,
    data,
    normalizeHashName(key.algorithm.hash.name),
    saltLength,
    padding,
    undefined,
    signature));
}
 
 
module.exports = {
  rsaCipher: rsaOaepCipher,
  rsaExportKey,
  rsaImportKey,
  rsaKeyGenerate,
  rsaSignVerify,
};