DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Password Generator with js

Using JavaScript, let's create a Password Generator

Code

HTML

<h2>Password Generator</h2>
<fieldset>
  <legend>Password</legend>
  <div id="resultEl"></div>
  <button id="generateEl">Generate password</button>
</fieldset>
<fieldset>
  <legend>Length</legend>
  <label>Length</label>
  <input type="number" id="lengthEl" min="1" />
</fieldset>
<fieldset>
  <legend>Include</legend>
  <div>
    <label>uppercase</label>
    <input type="checkbox" id="uppercaseEl" checked />
  </div>
  <div>
    <label>lowercase</label>
    <input type="checkbox" id="lowercaseEl" checked />
  </div>
  <div>
    <label>numbers</label>
    <input type="checkbox" id="numberEl" checked />
  </div>
  <div>
    <label>symbols</label>
    <input type="checkbox" id="symbolEl" checked />
  </div>
</fieldset>
Enter fullscreen mode Exit fullscreen mode

The user can define the length of the password to be generated using a numerical input field. It is also possible to select which types of characters should be included in the password: uppercase letters, lowercase letters, numbers and symbols. The "Generate Password" button is used to start the password generation process. The result of generating the password is displayed in a div with the ID "resultEl".

JS

The following code is a password generator that allows users to specify the length and character types of the password.

Function: generatePassword

generateEl.addEventListener('click', generatePassword);
Enter fullscreen mode Exit fullscreen mode

This function is triggered when the user clicks the "Generate password" button. It starts by defining an object called randomFunc:

let randomFunc = {
    randomLower: () => tableASCII(26, 97),
    randomUpper: () => tableASCII(26, 65),
    randomNumber: () => tableASCII(10, 48),
    randomSymbol: () => randomSymbol(),
  };
Enter fullscreen mode Exit fullscreen mode

randomFunc has four properties, each of which refers to a function that returns a random character:

  • randomLower returns a random lowercase letter
  • randomUpper returns a random uppercase letter
  • randomNumber returns a random number
  • randomSymbol returns a random symbol

The function then checks if the user has selected each of these options by checking the state of the corresponding checkboxes:

!lowercaseEl.checked && delete randomFunc.randomLower;
!uppercaseEl.checked && delete randomFunc.randomUpper;
!numberEl.checked && delete randomFunc.randomNumber;
!symbolEl.checked && delete randomFunc.randomSymbol;
Enter fullscreen mode Exit fullscreen mode

If the user has not selected a certain option, the corresponding property is deleted from the randomFunc object. This ensures that the password only contains the characters that the user has selected.

Finally, the function calls the randomPassword function and passes the length of the password and the randomFunc object as arguments:

resultEl.innerText = randomPassword(lengthEl.value, randomFunc);
Enter fullscreen mode Exit fullscreen mode

Function: randomPassword

The randomPassword function generates the password by looping through the desired length and concatenating a random character generated by the randomObject function.

function randomPassword(length, randomFunc) {
  try {
    let generatedPassword = '';
    for (let i = 0; i < length; i++) {
      generatedPassword += randomObject(randomFunc)();
    }
    return generatedPassword;
  } catch (e) {
    console.warn(e);
    return 'Marque pelo menos um item';
  }
}
Enter fullscreen mode Exit fullscreen mode

Function: randomObject

The randomObject function takes an object as an argument and returns a random property from that object.

const randomObject = (obj) =>
obj[Object.keys(obj)[Math.floor(Math.random() * Object.keys(obj).length)]];
Enter fullscreen mode Exit fullscreen mode

Function: tableASCII

The tableASCII function is used to generate random characters from the ASCII table. It takes two arguments: the number of characters in the table and the starting character code.

const tableASCII = (ini, start) =>
String.fromCharCode(Math.floor(Math.random() * ini) + start);
Enter fullscreen mode Exit fullscreen mode

Function: randomSymbol

The randomSymbol function returns a random symbol from a predefined string of symbols.

function randomSymbol() {
  const symbols = '
Enter fullscreen mode Exit fullscreen mode

Demo

See below for the complete working project.

💡 NOTE: If you can't see it click here and see the final result


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (10)

Collapse
 
lexlohr profile image
Alex Lohr

Please do not use Math.random() for security-related applications. Instead, use the Web Cryptography API:

// ❌ Don't
Math.random()
// ✅ Do
const values = new Uint8Array(chars);
Crypto.getRandomValues(values);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
walternascimentobarroso profile image
Walter Nascimento

cool, but why not use random?

Collapse
 
lexlohr profile image
Alex Lohr

It's not nearly as random as the name implies, so the resulting passwords will be a lot more predictable, making them significantly easier targets.

Thread Thread
 
walternascimentobarroso profile image
Walter Nascimento

ah got it, thanks

Thread Thread
 
htmnk profile image
Erik Petrinec

Good point, but it is crucial to emphasize on the entropy (length) of a password in addition to complexity when designing password generators for security purposes.

Image description

Thread Thread
 
walternascimentobarroso profile image
Walter Nascimento

very nice (comic strip) picture

Collapse
 
xinnks profile image
James Sinkala

This comment section right here is the reason I love the DEV platform. Fellow devs readily present you useful information that help you advance your knowledge, rather than tear you down. I'm proud of you guys.

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

yes, I really like it, several articles that I publish here, most of the time I have some feedback that helps me to improve, it's excellent

Collapse
 
xinnks profile image
James Sinkala

It's a very good culture, especially for budding writers trying to build up confidence in it, who'd otherwise be discouraged from writing.

Keep on the good work!

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

cool ;)