Skip to content

Instantly share code, notes, and snippets.

@diazoxide
Created March 22, 2023 07:30
Show Gist options
  • Save diazoxide/750ede901962f59f965370edd2bc9de6 to your computer and use it in GitHub Desktop.
Save diazoxide/750ede901962f59f965370edd2bc9de6 to your computer and use it in GitHub Desktop.
TypeScript generate strong password
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