All files / lib/internal/crypto random.js

99.49% Statements 581/584
92.86% Branches 130/140
100% Functions 23/23
99.49% Lines 581/584

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 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 194x 194x 194x 194x 194x 194x 16x 16x 174x 174x 194x 104x 269x 269x 269x 269x 269x 33x 33x 33x 208x 269x 4x 4x 204x 204x 269x 104x 139x 139x 139x 29x 29x 92x 92x 92x 139x 69x 69x 69x 23x 23x 23x 23x 23x 23x 139x 104x 141x 141x 7x 7x 7x 7x 7x 134x 141x 141x 141x 141x 141x 41x 141x 83x 83x 112x 112x 141x 111x 111x 111x 111x 111x 111x 111x 111x 111x 141x 111x 111x 141x 104x 74x 74x 7x 7x 7x 7x 7x 67x 74x 74x 74x 10x 10x 10x 10x 74x 12x 12x 57x 45x 45x 60x 60x 60x 74x 3x 74x 47x 47x 38x 74x 2x 2x 2x 36x 36x 36x 36x 36x 36x 36x 36x 74x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 557x 557x 557x 557x 557x 557x 557x 557x 217x 217x 217x 217x 557x 557x 557x 439x 439x 557x 13x 13x 557x 25x 25x 557x 5x 5x 5x 5x 508x 508x 508x 508x 557x 2x 2x 2x 506x 506x 506x 506x 506x 506x 506x 506x 557x 406x 1x 1x 1x 1x 406x 406x 406x 406x 406x 406x 406x 306x 306x 306x 406x 100x 100x 100x 100x 100x 100x 100x 557x 104x 100x 100x 100x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 100x 1x 1x 1x 1x 1x 1x 100x 104x 104x 36x 36x 36x 36x 104x 104x 104x 104x 104x 104x 29x 29x 29x 29x 29x 6x 6x 6x 6x 6x 6x 6x 29x 1x 1x 1x 1x 22x 22x 29x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 134x 134x 1x 1x 256x 256x 256x 1x 134x 134x 104x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 134x 104x 130x 130x 130x 130x 130x 130x 130x 130x 130x 104x 4x 4x 4x 4x 4x 4x 4x 104x 136x 136x 136x 135x 135x 136x 136x 136x 136x 136x 136x 104x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 21x 11x 21x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 21x 30x 55x 17x 7x 17x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 17x 21x 21x 55x 55x 55x 104x 35x 35x 35x 2x 2x 2x 29x 29x 29x 29x 8x       8x 8x 8x 8x 29x 29x 35x 104x 35x 35x 35x 35x 35x 35x 35x 7x 35x 104x 5x 5x 5x 104x 25x 25x 3x 3x 22x 22x 22x 22x 25x 104x 12x 12x 12x 12x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x 104x 23x 23x 23x 23x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 23x 20x 20x 23x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x  
'use strict';
 
const {
  Array,
  ArrayPrototypeForEach,
  ArrayPrototypePush,
  ArrayPrototypeShift,
  ArrayPrototypeSplice,
  BigInt,
  FunctionPrototypeBind,
  FunctionPrototypeCall,
  MathMin,
  NumberIsNaN,
  NumberIsSafeInteger,
  NumberPrototypeToString,
  StringPrototypePadStart,
} = primordials;
 
const {
  RandomBytesJob,
  RandomPrimeJob,
  CheckPrimeJob,
  kCryptoJobAsync,
  kCryptoJobSync,
  secureBuffer,
} = internalBinding('crypto');
 
const {
  lazyDOMException,
} = require('internal/crypto/util');
 
const { Buffer, kMaxLength } = require('buffer');
 
const {
  codes: {
    ERR_INVALID_ARG_TYPE,
    ERR_OUT_OF_RANGE,
    ERR_OPERATION_FAILED,
  }
} = require('internal/errors');
 
const {
  validateNumber,
  validateBoolean,
  validateCallback,
  validateObject,
  validateUint32,
} = require('internal/validators');
 
const {
  isArrayBufferView,
  isAnyArrayBuffer,
  isBigInt64Array,
  isFloat32Array,
  isFloat64Array,
} = require('internal/util/types');
 
const { FastBuffer } = require('internal/buffer');
 
const kMaxInt32 = 2 ** 31 - 1;
const kMaxPossibleLength = MathMin(kMaxLength, kMaxInt32);
 
function assertOffset(offset, elementSize, length) {
  validateNumber(offset, 'offset');
  offset *= elementSize;
 
  const maxLength = MathMin(length, kMaxPossibleLength);
  if (NumberIsNaN(offset) || offset > maxLength || offset < 0) {
    throw new ERR_OUT_OF_RANGE('offset', `>= 0 && <= ${maxLength}`, offset);
  }
 
  return offset >>> 0;  // Convert to uint32.
}
 
function assertSize(size, elementSize, offset, length) {
  validateNumber(size, 'size');
  size *= elementSize;
 
  if (NumberIsNaN(size) || size > kMaxPossibleLength || size < 0) {
    throw new ERR_OUT_OF_RANGE('size',
                               `>= 0 && <= ${kMaxPossibleLength}`, size);
  }
 
  if (size + offset > length) {
    throw new ERR_OUT_OF_RANGE('size + offset', `<= ${length}`, size + offset);
  }
 
  return size >>> 0;  // Convert to uint32.
}
 
function randomBytes(size, callback) {
  size = assertSize(size, 1, 0, Infinity);
  if (callback !== undefined) {
    validateCallback(callback);
  }
 
  const buf = new FastBuffer(size);
 
  if (callback === undefined) {
    randomFillSync(buf.buffer, 0, size);
    return buf;
  }
 
  // Keep the callback as a regular function so this is propagated.
  randomFill(buf.buffer, 0, size, function(error) {
    if (error) FunctionPrototypeCall(callback, this, error);
    FunctionPrototypeCall(callback, this, null, buf);
  });
}
 
function randomFillSync(buf, offset = 0, size) {
  if (!isAnyArrayBuffer(buf) && !isArrayBufferView(buf)) {
    throw new ERR_INVALID_ARG_TYPE(
      'buf',
      ['ArrayBuffer', 'ArrayBufferView'],
      buf);
  }
 
  const elementSize = buf.BYTES_PER_ELEMENT || 1;
 
  offset = assertOffset(offset, elementSize, buf.byteLength);
 
  if (size === undefined) {
    size = buf.byteLength - offset;
  } else {
    size = assertSize(size, elementSize, offset, buf.byteLength);
  }
 
  if (size === 0)
    return buf;
 
  const job = new RandomBytesJob(
    kCryptoJobSync,
    buf,
    offset,
    size);
 
  const err = job.run()[0];
  if (err)
    throw err;
 
  return buf;
}
 
function randomFill(buf, offset, size, callback) {
  if (!isAnyArrayBuffer(buf) && !isArrayBufferView(buf)) {
    throw new ERR_INVALID_ARG_TYPE(
      'buf',
      ['ArrayBuffer', 'ArrayBufferView'],
      buf);
  }
 
  const elementSize = buf.BYTES_PER_ELEMENT || 1;
 
  if (typeof offset === 'function') {
    callback = offset;
    offset = 0;
    // Size is a length here, assertSize() call turns it into a number of bytes
    size = buf.length;
  } else if (typeof size === 'function') {
    callback = size;
    size = buf.length - offset;
  } else {
    validateCallback(callback);
  }
 
  offset = assertOffset(offset, elementSize, buf.byteLength);
 
  if (size === undefined) {
    size = buf.byteLength - offset;
  } else {
    size = assertSize(size, elementSize, offset, buf.byteLength);
  }
 
  if (size === 0) {
    callback(null, buf);
    return;
  }
 
  const job = new RandomBytesJob(
    kCryptoJobAsync,
    buf,
    offset,
    size);
  job.ondone = FunctionPrototypeBind(onJobDone, job, buf, callback);
  job.run();
}
 
// Largest integer we can read from a buffer.
// e.g.: Buffer.from("ff".repeat(6), "hex").readUIntBE(0, 6);
const RAND_MAX = 0xFFFF_FFFF_FFFF;
 
// Cache random data to use in randomInt. The cache size must be evenly
// divisible by 6 because each attempt to obtain a random int uses 6 bytes.
const randomCache = new FastBuffer(6 * 1024);
let randomCacheOffset = randomCache.length;
let asyncCacheFillInProgress = false;
const asyncCachePendingTasks = [];
 
// Generates an integer in [min, max) range where min is inclusive and max is
// exclusive.
function randomInt(min, max, callback) {
  // Detect optional min syntax
  // randomInt(max)
  // randomInt(max, callback)
  const minNotSpecified = typeof max === 'undefined' ||
    typeof max === 'function';
 
  if (minNotSpecified) {
    callback = max;
    max = min;
    min = 0;
  }
 
  const isSync = typeof callback === 'undefined';
  if (!isSync) {
    validateCallback(callback);
  }
  if (!NumberIsSafeInteger(min)) {
    throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min);
  }
  if (!NumberIsSafeInteger(max)) {
    throw new ERR_INVALID_ARG_TYPE('max', 'a safe integer', max);
  }
  if (max <= min) {
    throw new ERR_OUT_OF_RANGE(
      'max', `greater than the value of "min" (${min})`, max
    );
  }
 
  // First we generate a random int between [0..range)
  const range = max - min;
 
  if (!(range <= RAND_MAX)) {
    throw new ERR_OUT_OF_RANGE(`max${minNotSpecified ? '' : ' - min'}`,
                               `<= ${RAND_MAX}`, range);
  }
 
  // For (x % range) to produce an unbiased value greater than or equal to 0 and
  // less than range, x must be drawn randomly from the set of integers greater
  // than or equal to 0 and less than randLimit.
  const randLimit = RAND_MAX - (RAND_MAX % range);
 
  // If we don't have a callback, or if there is still data in the cache, we can
  // do this synchronously, which is super fast.
  while (isSync || (randomCacheOffset < randomCache.length)) {
    if (randomCacheOffset === randomCache.length) {
      // This might block the thread for a bit, but we are in sync mode.
      randomFillSync(randomCache);
      randomCacheOffset = 0;
    }
 
    const x = randomCache.readUIntBE(randomCacheOffset, 6);
    randomCacheOffset += 6;
 
    if (x < randLimit) {
      const n = (x % range) + min;
      if (isSync) return n;
      process.nextTick(callback, undefined, n);
      return;
    }
  }
 
  // At this point, we are in async mode with no data in the cache. We cannot
  // simply refill the cache, because another async call to randomInt might
  // already be doing that. Instead, queue this call for when the cache has
  // been refilled.
  ArrayPrototypePush(asyncCachePendingTasks, { min, max, callback });
  asyncRefillRandomIntCache();
}
 
function asyncRefillRandomIntCache() {
  if (asyncCacheFillInProgress)
    return;
 
  asyncCacheFillInProgress = true;
  randomFill(randomCache, (err) => {
    asyncCacheFillInProgress = false;
 
    const tasks = asyncCachePendingTasks;
    const errorReceiver = err && ArrayPrototypeShift(tasks);
    if (!err)
      randomCacheOffset = 0;
 
    // Restart all pending tasks. If an error occurred, we only notify a single
    // callback (errorReceiver) about it. This way, every async call to
    // randomInt has a chance of being successful, and it avoids complex
    // exception handling here.
    ArrayPrototypeForEach(ArrayPrototypeSplice(tasks, 0), (task) => {
      randomInt(task.min, task.max, task.callback);
    });
 
    // This is the only call that might throw, and is therefore done at the end.
    if (errorReceiver)
      errorReceiver.callback(err);
  });
}
 
 
function onJobDone(buf, callback, error) {
  if (error) return FunctionPrototypeCall(callback, this, error);
  FunctionPrototypeCall(callback, this, null, buf);
}
 
// Really just the Web Crypto API alternative
// to require('crypto').randomFillSync() with an
// additional limitation that the input buffer is
// not allowed to exceed 65536 bytes, and can only
// be an integer-type TypedArray.
function getRandomValues(data) {
  if (!isArrayBufferView(data) ||
      isBigInt64Array(data) ||
      isFloat32Array(data) ||
      isFloat64Array(data)) {
    // Ordinarily this would be an ERR_INVALID_ARG_TYPE. However,
    // the Web Crypto API and web platform tests expect this to
    // be a DOMException with type TypeMismatchError.
    throw lazyDOMException(
      'The data argument must be an integer-type TypedArray',
      'TypeMismatchError');
  }
  if (data.byteLength > 65536) {
    throw lazyDOMException(
      'The requested length exceeds 65,536 bytes',
      'QuotaExceededError');
  }
  randomFillSync(data, 0);
  return data;
}
 
// Implements an RFC 4122 version 4 random UUID.
// To improve performance, random data is generated in batches
// large enough to cover kBatchSize UUID's at a time. The uuidData
// buffer is reused. Each call to randomUUID() consumes 16 bytes
// from the buffer.
 
const kBatchSize = 128;
let uuidData;
let uuidNotBuffered;
let uuidBatch = 0;
 
let hexBytesCache;
function getHexBytes() {
  if (hexBytesCache === undefined) {
    hexBytesCache = new Array(256);
    for (let i = 0; i < hexBytesCache.length; i++) {
      const hex = NumberPrototypeToString(i, 16);
      hexBytesCache[i] = StringPrototypePadStart(hex, 2, '0');
    }
  }
  return hexBytesCache;
}
 
function serializeUUID(buf, offset = 0) {
  const kHexBytes = getHexBytes();
  // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  return kHexBytes[buf[offset]] +
    kHexBytes[buf[offset + 1]] +
    kHexBytes[buf[offset + 2]] +
    kHexBytes[buf[offset + 3]] +
    '-' +
    kHexBytes[buf[offset + 4]] +
    kHexBytes[buf[offset + 5]] +
    '-' +
    kHexBytes[(buf[offset + 6] & 0x0f) | 0x40] +
    kHexBytes[buf[offset + 7]] +
    '-' +
    kHexBytes[(buf[offset + 8] & 0x3f) | 0x80] +
    kHexBytes[buf[offset + 9]] +
    '-' +
    kHexBytes[buf[offset + 10]] +
    kHexBytes[buf[offset + 11]] +
    kHexBytes[buf[offset + 12]] +
    kHexBytes[buf[offset + 13]] +
    kHexBytes[buf[offset + 14]] +
    kHexBytes[buf[offset + 15]];
}
 
function getBufferedUUID() {
  uuidData ??= secureBuffer(16 * kBatchSize);
  if (uuidData === undefined)
    throw new ERR_OPERATION_FAILED('Out of memory');
 
  if (uuidBatch === 0) randomFillSync(uuidData);
  uuidBatch = (uuidBatch + 1) % kBatchSize;
  return serializeUUID(uuidData, uuidBatch * 16);
}
 
function getUnbufferedUUID() {
  uuidNotBuffered ??= secureBuffer(16);
  if (uuidNotBuffered === undefined)
    throw new ERR_OPERATION_FAILED('Out of memory');
  randomFillSync(uuidNotBuffered);
  return serializeUUID(uuidNotBuffered);
}
 
function randomUUID(options) {
  if (options !== undefined)
    validateObject(options, 'options');
  const {
    disableEntropyCache = false,
  } = options || {};
 
  validateBoolean(disableEntropyCache, 'options.disableEntropyCache');
 
  return disableEntropyCache ? getUnbufferedUUID() : getBufferedUUID();
}
 
function createRandomPrimeJob(type, size, options) {
  validateObject(options, 'options');
 
  const {
    safe = false,
    bigint = false,
  } = options;
  let {
    add,
    rem,
  } = options;
 
  validateBoolean(safe, 'options.safe');
  validateBoolean(bigint, 'options.bigint');
 
  if (add !== undefined) {
    if (typeof add === 'bigint') {
      add = unsignedBigIntToBuffer(add, 'options.add');
    } else if (!isAnyArrayBuffer(add) && !isArrayBufferView(add)) {
      throw new ERR_INVALID_ARG_TYPE(
        'options.add',
        [
          'ArrayBuffer',
          'TypedArray',
          'Buffer',
          'DataView',
          'bigint',
        ],
        add);
    }
  }
 
  if (rem !== undefined) {
    if (typeof rem === 'bigint') {
      rem = unsignedBigIntToBuffer(rem, 'options.rem');
    } else if (!isAnyArrayBuffer(rem) && !isArrayBufferView(rem)) {
      throw new ERR_INVALID_ARG_TYPE(
        'options.rem',
        [
          'ArrayBuffer',
          'TypedArray',
          'Buffer',
          'DataView',
          'bigint',
        ],
        rem);
    }
  }
 
  const job = new RandomPrimeJob(type, size, safe, add, rem);
  job.result = bigint ? arrayBufferToUnsignedBigInt : (p) => p;
  return job;
}
 
function generatePrime(size, options, callback) {
  validateUint32(size, 'size', true);
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }
  validateCallback(callback);
 
  const job = createRandomPrimeJob(kCryptoJobAsync, size, options);
  job.ondone = (err, prime) => {
    if (err) {
      callback(err);
      return;
    }
 
    callback(
      undefined,
      job.result(prime));
  };
  job.run();
}
 
function generatePrimeSync(size, options = {}) {
  validateUint32(size, 'size', true);
 
  const job = createRandomPrimeJob(kCryptoJobSync, size, options);
  const { 0: err, 1: prime } = job.run();
  if (err)
    throw err;
  return job.result(prime);
}
 
function arrayBufferToUnsignedBigInt(arrayBuffer) {
  return BigInt(`0x${Buffer.from(arrayBuffer).toString('hex')}`);
}
 
function unsignedBigIntToBuffer(bigint, name) {
  if (bigint < 0) {
    throw new ERR_OUT_OF_RANGE(name, '>= 0', bigint);
  }
 
  const hex = bigint.toString(16);
  const padded = hex.padStart(hex.length + (hex.length % 2), 0);
  return Buffer.from(padded, 'hex');
}
 
function checkPrime(candidate, options = {}, callback) {
  if (typeof candidate === 'bigint')
    candidate = unsignedBigIntToBuffer(candidate, 'candidate');
  if (!isAnyArrayBuffer(candidate) && !isArrayBufferView(candidate)) {
    throw new ERR_INVALID_ARG_TYPE(
      'candidate',
      [
        'ArrayBuffer',
        'TypedArray',
        'Buffer',
        'DataView',
        'bigint',
      ],
      candidate
    );
  }
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }
  validateCallback(callback);
  validateObject(options, 'options');
  const {
    checks = 0,
  } = options;
 
  validateUint32(checks, 'options.checks');
 
  const job = new CheckPrimeJob(kCryptoJobAsync, candidate, checks);
  job.ondone = callback;
  job.run();
}
 
function checkPrimeSync(candidate, options = {}) {
  if (typeof candidate === 'bigint')
    candidate = unsignedBigIntToBuffer(candidate, 'candidate');
  if (!isAnyArrayBuffer(candidate) && !isArrayBufferView(candidate)) {
    throw new ERR_INVALID_ARG_TYPE(
      'candidate',
      [
        'ArrayBuffer',
        'TypedArray',
        'Buffer',
        'DataView',
        'bigint',
      ],
      candidate
    );
  }
  validateObject(options, 'options');
  const {
    checks = 0,
  } = options;
 
  validateUint32(checks, 'options.checks');
 
  const job = new CheckPrimeJob(kCryptoJobSync, candidate, checks);
  const { 0: err, 1: result } = job.run();
  if (err)
    throw err;
 
  return result;
}
 
module.exports = {
  checkPrime,
  checkPrimeSync,
  randomBytes,
  randomFill,
  randomFillSync,
  randomInt,
  getRandomValues,
  randomUUID,
  generatePrime,
  generatePrimeSync,
};