Logo

dev-resources.site

for different kinds of informations.

Build a Secure Password Generator with Javascript

Published at
1/15/2025
Categories
javascript
webdev
beginners
programming
Author
hayrhotoca
Author
10 person written this
hayrhotoca
open
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 id="lengthValue">12</span></label>
        <input type="range" id="lengthSlider" min="8" max="20" value="12">
    </div>
    <div>
        <input type="checkbox" id="uppercase" checked> Include Uppercase Letters
        <input type="checkbox" id="lowercase" checked> Include Lowercase Letters
        <input type="checkbox" id="numbers" checked> Include Numbers
        <input type="checkbox" id="symbols"> Include Symbols
    </div>
    <button onclick="generatePassword()">Generate Password</button>
    <input type="text" id="passwordOutput" readonly>
    <button class="fa-copy" onclick="copyPassword()">Copy</button>

    <script src="script.js"></script> <!-- Link to your JavaScript file -->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

JavaScript Functionality

Now, let’s dive into the JavaScript code that powers our password generator.

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 class="fas fa-check"></i>';
    setTimeout(() => {
        btn.innerHTML = '<i class="fas fa-copy"></i>';
    }, 1000);
}

// Update length value display
document.getElementById('lengthSlider').addEventListener('input', function () {
    document.getElementById('lengthValue').textContent = this.value;
});

// Generate initial password
generatePassword();
Enter fullscreen mode Exit fullscreen mode

Explanation of Key Functions

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.
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.
copyPassword(): This function allows users to easily copy the generated password to their clipboard and provides visual feedback to confirm the action.
Event Listener for Length Slider: This updates the displayed password length dynamically as the user adjusts the slider.

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

Conclusion

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!

programming Article's
30 articles in total
Programming is the process of writing, testing, and maintaining code to create software applications for various purposes and platforms.
Favicon
7 Developer Tools That Will Boost Your Workflow in 2025
Favicon
What ((programming) language) should I learn this year, 2025 ?
Favicon
Lessons from A Philosophy of Software Design
Favicon
🕒 What’s your most productive time of the day?
Favicon
Designing for developers means designing for LLMs too
Favicon
Unique Symbols: How to Use Symbols for Type Safety
Favicon
Filling a 10 Million Image Grid with PHP for Internet History
Favicon
When AI Fails, Good Documentation Saves the Day 🤖📚
Favicon
The Language Server Protocol - Building DBChat (Part 5)
Favicon
Основы изучения Python: Руководство для начинающих
Favicon
GraphQL Transforming API Development
Favicon
Easy Discount Calculation: Tax, Fees & Discount Percentage Explained
Favicon
Example of using Late Static Binding in PHP.
Favicon
Top 5 Python Scripts to Automate Your Daily Tasks: Boost Productivity with Automation
Favicon
How to Resolve the 'Permission Denied' Error in PHP File Handling
Favicon
7 Mistakes Developers Make When Learning a New Framework (and How to Avoid Them)
Favicon
Why Is Everyone Unhappy With JavaScript? | State of Javascript 2024 Survey
Favicon
Python в 2025: стоит ли начинать с нуля? Личный опыт и рекомендации
Favicon
Cómo gestionar tus proyectos de software con Github
Favicon
Decreasing server load by using debouncing/throttle technique in reactjs
Favicon
2429. Minimize XOR
Favicon
➡️💡Guide, Innovate, Succeed: Becoming a Software Development Leader 🚀
Favicon
Debugging Adventure Day 1: What to Do When Your Code Doesn’t Work
Favicon
🚀 New Book Release: "Navigate the Automation Seas" – A Practical Guide to Building Automation Frameworks
Favicon
Булеві типи і вирази
Favicon
Build a Secure Password Generator with Javascript
Favicon
join my project semester simulator
Favicon
Как создать свой VPN и получить доступ ко всему?
Favicon
Revolutionary AI Model Self-Adapts Like Human Brain: Transformer Shows 15% Better Performance in Complex Tasks
Favicon
Flow Networks Breakthrough: New Theory Shows Promise for Machine Learning Structure Discovery

Featured ones: