Created
March 7, 2023 19:09
-
-
Save Gu7z/a889a829efe55138ba4c97d85fdb2771 to your computer and use it in GitHub Desktop.
Generate random password in JS with webcrypto
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
async function hashPassword(password) { | |
const passwordBuffer = new TextEncoder().encode(password); | |
const hashBuffer = await crypto.subtle.digest('SHA-256', passwordBuffer); | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); | |
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); | |
return hashHex; | |
} | |
function generateRandomPassword(length) { | |
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; | |
let password = ''; | |
for (let i = 0; i < length; i++) { | |
const randomIndex = Math.floor(Math.random() * charset.length); | |
password += charset[randomIndex]; | |
} | |
return password; | |
} | |
// Exemplo de uso | |
const password = generateRandomPassword(16); | |
const hashedPassword = await hashPassword(password); | |
console.log(`Senha aleatória: ${password}`); | |
console.log(`Senha hasheada: ${hashedPassword}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment