Skip to content

Instantly share code, notes, and snippets.

@sstur
Created March 11, 2020 19:17
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 sstur/2d8bf38e0d6b33df9e054fc5a2fa4e1e to your computer and use it in GitHub Desktop.
Save sstur/2d8bf38e0d6b33df9e054fc5a2fa4e1e to your computer and use it in GitHub Desktop.
import crypto from 'crypto';
export function getRandomBytes(numBytes: number): Promise<Buffer> {
return new Promise((resolve, reject) => {
crypto.randomBytes(numBytes, (error, result) => {
error ? reject(error) : resolve(result);
});
});
}
export async function getRandomBase36(numChars: number): Promise<string> {
let result = '';
while (result.length < numChars) {
let num = Math.pow(256, 2);
while (num > Math.pow(36, 3)) {
let [a, b] = await getRandomBytes(2);
num = a * 256 + b;
}
result += num.toString(36);
}
return result.slice(0, numChars);
}
export async function getRandomBase64(
numChars: number,
urlSafe = false,
): Promise<string> {
let result = '';
while (result.length < numChars) {
let buffer = await getRandomBytes(3);
result += buffer.toString('base64');
}
result = result.slice(0, numChars);
if (urlSafe) {
result = result.split('+').join('-');
result = result.split('/').join('_');
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment