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: Password Generator Password Generator Password Length: 12 Include Uppercase Letters Include Lowercase Letters Include Numbers Include Symbols Generate Password Copy 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 = ''; setTimeout(() => { btn.innerHTML = ''; }, 1000); } // Update length value display document.getElementById('lengthSlider').addEventListener('input', function () { document.getElementById('lengthValue').textContent = this.value; }); // Generate initial password generatePassword(); 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!

Jan 15, 2025 - 12:53
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:




    
    
    Password Generator
     


    

Password Generator

Include Uppercase Letters Include Lowercase Letters Include Numbers Include Symbols

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 = '';
    setTimeout(() => {
        btn.innerHTML = '';
    }, 1000);
}

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

// Generate initial password
generatePassword();

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!