Created
June 12, 2025 03:08
-
-
Save wlib/3808b775bcfd7871cc9bcf25b64ccb8a to your computer and use it in GitHub Desktop.
Uniform secure random javascript password generation
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
const basicLatin = String.fromCharCode(...range(32, 127)) | |
const makeRandomPassword = ({ | |
length = 32, | |
characters = basicLatin | |
}: { | |
/** Max 256 */ | |
length?: number, | |
characters?: string | ReadonlyArray<string> | |
} = {}) => { | |
const entropyPerCharacter = 8 | |
const statesPerCharacter = 2 ** entropyPerCharacter | |
if (characters.length > statesPerCharacter) | |
throw new Error(`Character count (${characters.length}) must not exceed 2^8 (256)`) | |
const limit = statesPerCharacter - (statesPerCharacter % characters.length) | |
const randomValuesUnderLimit: number[] = [] | |
while (randomValuesUnderLimit.length < length) { | |
const randomValues = crypto.getRandomValues( | |
new Uint8Array(length - randomValuesUnderLimit.length) | |
) | |
for (const randomValue of randomValues) | |
if (randomValue < limit) | |
randomValuesUnderLimit.push(randomValue) | |
} | |
let result = "" | |
for (const n of randomValuesUnderLimit) | |
result += characters[n % characters.length] | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment