random.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * A **Cryptographically Secure Random Value** is one that has been
  3. * generated with additional care take to prevent side-channels
  4. * from allowing others to detect it and prevent others from through
  5. * coincidence generate the same values.
  6. *
  7. * @_subsection: api/crypto:Random Values [about-crypto-random]
  8. */
  9. import { randomBytes as crypto_random } from "./crypto.js";
  10. let locked = false;
  11. const _randomBytes = function(length: number): Uint8Array {
  12. return new Uint8Array(crypto_random(length));
  13. }
  14. let __randomBytes = _randomBytes;
  15. /**
  16. * Return %%length%% bytes of cryptographically secure random data.
  17. *
  18. * @example:
  19. * randomBytes(8)
  20. * //_result:
  21. */
  22. export function randomBytes(length: number): Uint8Array {
  23. return __randomBytes(length);
  24. }
  25. randomBytes._ = _randomBytes;
  26. randomBytes.lock = function(): void { locked = true; }
  27. randomBytes.register = function(func: (length: number) => Uint8Array) {
  28. if (locked) { throw new Error("randomBytes is locked"); }
  29. __randomBytes = func;
  30. }
  31. Object.freeze(randomBytes);