Last active
January 6, 2024 12:00
-
-
Save fearspear/4d757e956b0ff92ad0412691fbfc322f to your computer and use it in GitHub Desktop.
Generate a Secure Random Password Using Web Crypto API and Javascript
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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the code explanation at this Web Crypto API blog post