Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Created October 11, 2021 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/c8ed082eb249649128cd12828fdfaec5 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/c8ed082eb249649128cd12828fdfaec5 to your computer and use it in GitHub Desktop.
Random bytes and bits for Node.js #javascript #typescript
import crypto from 'crypto';
/**
* Gets random bytes as Uint8Array
*/
function randomBytes(size: number): Uint8Array {
return crypto.randomBytes(size);
}
/**
* Gets random bit string
*/
function randomBits(size: number): string {
const bytes = randomBytes(Math.ceil(size / 8));
const bits = [...bytes].map((n) => dec2bin(n, 8)).join('');
return bits.substr(0, size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment