Created
March 22, 2023 07:30
-
-
Save diazoxide/750ede901962f59f965370edd2bc9de6 to your computer and use it in GitHub Desktop.
TypeScript generate strong password
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
function generateRandomSecret(length = 32): string { | |
const haystacks = [ | |
"abcdefghijklmnopqrstuvwxyz", | |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ", | |
"0123456789", | |
"~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/" | |
]; | |
const randomPart = (haystack: string, length: number)=>{ | |
let retVal = ""; | |
for (let i = 0, n = haystack.length; i < length; ++i) { | |
retVal += haystack.charAt(Math.floor(Math.random() * n)); | |
} | |
return retVal; | |
} | |
let retVal = "" | |
haystacks.forEach((haystack)=>retVal+=randomPart(haystack, length/haystacks.length)) | |
const a = retVal.split(""); | |
const n = a.length; | |
for(let i = n - 1; i > 0; i--) { | |
const j = Math.floor(Math.random() * (i + 1)); | |
const tmp = a[i]; | |
a[i] = a[j]; | |
a[j] = tmp; | |
} | |
return a.join("").substring(0, length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment