Home > Web Front-end > JS Tutorial > Build a Secure Password Generator with Javascript

Build a Secure Password Generator with Javascript

Barbara Streisand
Release: 2025-01-15 20:40:44
Original
986 people have browsed it

Build a Secure Password Generator with Javascript

In today's digital world, having a strong password is crucial for safeguarding your online accounts. In this post, I'll walk you through creating a simple yet effective password generator using JavaScript. This generator allows users to customize their password by selecting various criteria such as length, and the inclusion of uppercase letters, lowercase letters, numbers, and symbols.

The Code Breakdown

HTML Structure
Before diving into the JavaScript code, let’s set up the HTML structure for our password generator. Here’s a basic template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Generator</title>
    <link rel="stylesheet" href="styles.css"> <!-- Add your CSS file -->
</head>
<body>
    <h1>Password Generator</h1>
    <div>
        <label for="lengthSlider">Password Length: <span>



<h2>
  
  
  JavaScript Functionality
</h2>

<p>Now, let’s dive into the JavaScript code that powers our password generator.<br>
</p><pre class="brush:php;toolbar:false">function generatePassword() {
    const length = document.getElementById('lengthSlider').value;
    const uppercase = document.getElementById('uppercase').checked;
    const lowercase = document.getElementById('lowercase').checked;
    const numbers = document.getElementById('numbers').checked;
    const symbols = document.getElementById('symbols').checked;

    let chars = '';
    if (uppercase) chars  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (lowercase) chars  = 'abcdefghijklmnopqrstuvwxyz';
    if (numbers) chars  = '0123456789';
    if (symbols) chars  = '!@#$%^&*()_ -=[]{}|;:,.<>?';

    let password = '';
    for (let i = 0; i < length; i  ) {
        password  = chars.charAt(Math.floor(secureRandom() * chars.length));
    }

    document.getElementById('passwordOutput').value = password;
}

function secureRandom() {
    try {
        const array = new Uint8Array(8);
        const buf = window.crypto.getRandomValues(array);
        const offset = Math.random() < 0.5 ? 0 : buf.length - 4;
        const dataView = new DataView(buf.buffer);
        const intVal = dataView.getUint32(offset, true); // Convert bytes to an unsigned 32-bit integer
        const normalized = intVal / (Math.pow(2, 32) - 1); // Scale to [0, 1)
        return normalized;
    } catch (error) {
        console.error("Error generating secure random number:", error);
        throw error; // Rethrow or handle as needed
    }
}

function copyPassword() {
    const passwordOutput = document.getElementById('passwordOutput');
    passwordOutput.select();
    document.execCommand('copy');

    // Add visual feedback
    const btn = document.querySelector('.fa-copy').parentElement;
    btn.innerHTML = '<i>



<h2>
  
  
  Explanation of Key Functions
</h2>

<p>generatePassword(): This function collects user preferences from the UI and constructs a character set based on the selected options. It then generates a random password by selecting characters from this set.<br>
secureRandom(): This function uses the Web Crypto API to generate secure random numbers, ensuring that the passwords generated are not only random but also secure.<br>
copyPassword(): This function allows users to easily copy the generated password to their clipboard and provides visual feedback to confirm the action.<br>
Event Listener for Length Slider: This updates the displayed password length dynamically as the user adjusts the slider.</p>

<p>The final product: https://1limx.com/password-generator</p>

<h2>
  
  
  Conclusion
</h2>

<p>With just a few lines of code, you can create a robust and customizable password generator that enhances your online security. Feel free to expand upon this project by adding more features or improving the user interface! Happy coding! If you have any questions or suggestions for improvements, feel free to leave a comment below!</p>


          

            
        
Copy after login

The above is the detailed content of Build a Secure Password Generator with Javascript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template