Last active
May 12, 2020 19:04
-
-
Save iameli/96f41107ca6cdfb66e8b88fe86831d69 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { randomBytes } from 'crypto' | |
| import anyBase from 'any-base' | |
| const BASE_36 = 'abcdefghijklmnopqrstuvwxyz0123456789' | |
| const SEGMENT_COUNT = 3 | |
| const SEGMENT_LENGTH = 4 | |
| const hexToBase36 = anyBase(anyBase.HEX, BASE_36) | |
| /** | |
| * Securely generate a stream key of a given length. Goals for stream keys: be reasonably secure | |
| * but also easy to type if necessary. Base36 facilitates this. | |
| * | |
| * Returns stream keys of the form XXXX-XXXX-XXXX in Base36. 62-ish bits of entropy. | |
| */ | |
| export async function generateStreamKey() { | |
| return new Promise((resolve, reject) => { | |
| randomBytes(128, (err, buf) => { | |
| if (err) { | |
| return reject(err) | |
| } | |
| const raw = hexToBase36(buf.toString('hex')) | |
| let result = '' | |
| const TOTAL_LENGTH = SEGMENT_COUNT * SEGMENT_LENGTH | |
| for (let i = 0; i < TOTAL_LENGTH; i += 1) { | |
| // Pull from the end of the raw string, the start has least siginificant bits | |
| // and isn't likely to be fully random. | |
| result += raw[raw.length - 1 - i] | |
| if ((i + 1) % SEGMENT_LENGTH === 0 && i < TOTAL_LENGTH - 1) { | |
| result += '-' | |
| } | |
| } | |
| resolve(result) | |
| }) | |
| }) | |
| } | |
| if (!module.parent) { | |
| generateStreamKey().then(x => console.log(x)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment