Created
October 11, 2021 03:47
-
-
Save CMCDragonkai/c8ed082eb249649128cd12828fdfaec5 to your computer and use it in GitHub Desktop.
Random bytes and bits for Node.js #javascript #typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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