generateSecureRandomString.js 567 B

123456789101112131415161718
  1. export default () => {
  2. // Human readable alphabet (a-z, 0-9 without l, o, 0, 1 to avoid confusion)
  3. const alphabet = "abcdefghijkmnpqrstuvwxyz23456789";
  4. // Generate 24 bytes = 192 bits of entropy.
  5. // We're only going to use 5 bits per byte so the total entropy will be 192 * 5 / 8 = 120 bits
  6. const bytes = new Uint8Array(24);
  7. crypto.getRandomValues(bytes);
  8. let id = "";
  9. for (let i = 0; i < bytes.length; i++) {
  10. // >> 3 "removes" the right-most 3 bits of the byte
  11. id += alphabet[bytes[i] >> 3];
  12. }
  13. return id;
  14. }