Skip to content

Instantly share code, notes, and snippets.

@Skhmt
Last active December 20, 2024 19:56
Show Gist options
  • Save Skhmt/5870d0eb3d23d3c7a6ab91e7a2e7442e to your computer and use it in GitHub Desktop.
Save Skhmt/5870d0eb3d23d3c7a6ab91e7a2e7442e to your computer and use it in GitHub Desktop.
generates a pw
import * as crypto from 'node:crypto';
const charactersUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const charactersLower = 'abcdefghijklmnopqrstuvwxyz';
const symbols = '!@#$%&?^*.:,;_-';
const decimalNumbers = '0123456789';
console.log(createRandomString(12, true, 'password', true));
function createRandomString(length = 16, useSymbols = true, prefix = '', useNumbers = true) {
let possibleChars = charactersUpper + charactersLower + (useSymbols ? symbols : '') + (useNumbers ? decimalNumbers : '');
const requiredChars = [rand(charactersUpper, 1), rand(charactersLower, 1)];
if (useSymbols) requiredChars.push(rand(symbols, 1));
if (useNumbers) requiredChars.push(rand(decimalNumbers, 1));
if (length < requiredChars.length + prefix.length) {
throw new Error('Length must be at least ' + (requiredChars.length + prefix.length));
}
const randLength = length - requiredChars.length - prefix.length;
const unshuffled = requiredChars.concat(rand(possibleChars, randLength));
const shuffled = shuffleArray(unshuffled);
return prefix + shuffled.join('');
}
function shuffleArray(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
const j = randomInt(i + 1);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
function rand(str, num) {
const randArr = new Uint32Array(num);
crypto.getRandomValues(randArr);
let output = [];
for (let n of randArr) {
output.push(str[n % str.length]);
}
return output;
}
function randomInt(max) {
return crypto.getRandomValues(new Uint32Array(1))[0] % max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment