DEV Community

Marius
Marius

Posted on • Edited on

JS practice: day1 password generator

There are plenty of ways to generate secure passwords, but why not use your own password-generating algorithm? It will be better than using the same password everywhere, and you'll have some fun in the process. Let's get to coding!

First some html

<h1>password generator</h1>
<label>write a word</label>
<input type="text" id="word" value="">
<input type="button" value="generate"><br>
<strong>generated password:</strong>
<input type="text" id="pw" value="">
Enter fullscreen mode Exit fullscreen mode

next let's write a function that takes in a priming word and returns a password.

let vowels = 'aeiouyw';
let vowelRegex = new RegExp(`[${vowels}]`,'gi'); // List of vowels (Global and Insensitive)
let consonantRegex = new RegExp(`(?![${vowels}])[a-z]`, 'gi'); // List of consonants (Global and Insensitive)
let allRegex = new RegExp(`[a-z]`, 'gi'); // List of consonants (Global and Insensitive)


const encodePW = (c) => {

  // turn the string into an array
  arrayed = c.match(allRegex)
  // create an empty array that will hold your strings
  newArr = []
  // add the index next to each el
  arrayed.map((a, index)  => { newArr.push(a + index); });

  // create two empty arrays
  g1 = []; g2 = []

  // add elements inside this empty array
  newArr.map(el => {
    el.match(vowelRegex) ? g1.push(el) : g2.push(el)
  })

  let vowelStr = g1.join('').toUpperCase(),
      consonantStr = g2.join('').toLowerCase();
      // the compose algo
      pwCompose = '#' + c.length + vowelStr + g1.length + g2.length + consonantStr + (c.length * g1.length + g2.length + '1903')

  console.log(pwCompose)

  let vowels = c.match(vowelRegex).join('').toUpperCase();
  let consonant = c.match(consonantRegex).join('').toLowerCase();
  let pw = '#' + c.length + vowels + vowels.length + consonant.length + consonant + (vowels.length + consonant.length + c.length) + '5475'

  return pw;
};

Enter fullscreen mode Exit fullscreen mode

Now let's hook all this up with the HTML

const primedInput = document.getElementById('word')
const genBtn = document.querySelector('[type="button"]');
const primedWord = primedInput.value || ''
const pwField = document.getElementById('pw');

genBtn.addEventListener("click", e => {
  pwField.value = encodePW(primedWord);
});
Enter fullscreen mode Exit fullscreen mode

And voila, you have your own password generator with a badass encryption algorithm. The next step will be to write a script that decrypts the password.

what do you think ?

The decoder script is in the next post.

Top comments (0)