Skip to content

Instantly share code, notes, and snippets.

@Gu7z
Created March 7, 2023 19:09
Show Gist options
  • Save Gu7z/a889a829efe55138ba4c97d85fdb2771 to your computer and use it in GitHub Desktop.
Save Gu7z/a889a829efe55138ba4c97d85fdb2771 to your computer and use it in GitHub Desktop.
Generate random password in JS with webcrypto
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