Skip to content

Instantly share code, notes, and snippets.

@fearspear
Last active January 6, 2024 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fearspear/4d757e956b0ff92ad0412691fbfc322f to your computer and use it in GitHub Desktop.
Save fearspear/4d757e956b0ff92ad0412691fbfc322f to your computer and use it in GitHub Desktop.
Generate a Secure Random Password Using Web Crypto API and Javascript
// Check if the Crypto API is available
if (window.crypto && window.crypto.getRandomValues) {
// Crypto API is available
} else {
// Crypto API is not supported, provide alternative method
console.error("Crypto API not supported in this browser.");
}
// Function to generate a secure random password
function generateRandomPassword(length, includeUppercase, includeLowercase, includeNumbers, includeSpecialChars) {
const uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
const numberChars = '0123456789';
const specialChars = '!@#$%^&*()-=_+[]{}|;:,.<>?/';
let allChars = '';
let password = '';
if (includeUppercase) allChars += uppercaseChars;
if (includeLowercase) allChars += lowercaseChars;
if (includeNumbers) allChars += numberChars;
if (includeSpecialChars) allChars += specialChars;
const allCharsLength = allChars.length;
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(window.crypto.getRandomValues(new Uint32Array(1))[0] / (0xFFFFFFFF + 1) * allCharsLength);
password += allChars.charAt(randomIndex);
}
return password;
}
// Define password criteria
const passwordLength = 12;
const includeUppercase = true;
const includeLowercase = true;
const includeNumbers = true;
const includeSpecialChars = true;
// Generate a random password using the defined criteria
const generatedPassword = generateRandomPassword(passwordLength, includeUppercase, includeLowercase, includeNumbers, includeSpecialChars);
// Use the generated password
console.log('Generated Password:', generatedPassword);
@fearspear
Copy link
Author

Read the code explanation at this Web Crypto API blog post

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment