Skip to content

Instantly share code, notes, and snippets.

@Skhmt
Last active December 20, 2024 19:56
Show Gist options
  • Select an option

  • Save Skhmt/5870d0eb3d23d3c7a6ab91e7a2e7442e to your computer and use it in GitHub Desktop.

Select an option

Save Skhmt/5870d0eb3d23d3c7a6ab91e7a2e7442e to your computer and use it in GitHub Desktop.
generates a pw
import * as crypto from 'node:crypto';
const charactersUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const charactersLower = 'abcdefghijklmnopqrstuvwxyz';
const symbols = '!@#$%&?^*.:,;_-';
const decimalNumbers = '0123456789';
console.log(createRandomString(16, true, 'pw', true));
function createRandomString(length = 8, useSymbols = false, prefix = '', useNumbers = false) {
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));
const randLength = length - requiredChars.length - prefix.length;
const unshuffled = requiredChars.concat(rand(possibleChars, (randLength > 0) ? randLength : 0));
const shuffled = shuffleArray(unshuffled);
return prefix + shuffled.join('');
}
function shuffleArray(arr) {
const randArr = new Uint32Array(arr.length + 1);
crypto.getRandomValues(randArr);
const randRangeArr = randArr.map(x => x % arr.length);
for (let i = arr.length - 1; i >= 0; i--) {
const j = randRangeArr[i];
[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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment