How to create your own password generator in under 10 lines of code using NodeJs
Tags: password, node, crypto, shell
Published: 2022-06-23 15:50:16

## Why are we doing this

As we've all noticed lately, websites and apps have become stricter about your account password, which must meet the following minimum requirements: 8 characters long and be a mixture of alpha-numeric characters. Moreover, with latest versions of IOS and Android, they created a whole system where you can find all passwords considered as 'weak' and if one of your password has appeared in a data leak they'll alert you. 
I have a saying: 

> If something already exists but you feel capable of doing it yourself then do it ! 

What I really mean behind this statement is that it doesn't matter that it already exists because the version you have in mind (with all its complexity) doesn't exist, and that's the point: by turning the idea into an application you'll get a better understanding of how things actually work, which will give you not only technical skills but also conversational skills hence giving you the opportunity to teach someone else (which is for me, the most valuable asset in life). 

## Requirements

- `NodeJs` installed on your computer, if it's not already done, here are the ways to set it up:
  - **Simplest solution**: Using **[nvm](https://github.com/nvm-sh/nvm#installing-and-updating)**
  - **From official source**: You can download it from **[here](https://nodejs.org/en/)**
  - **Using a packet manager**: 

Using apt-get
```bash
# The first step is to update your system
$ sudo apt-get update

# Then run
$ sudo apt install nodejs
$ sudo apt install npm

# Finally test installation using
# It should output the currently installed version of node & npm
$ node -v 
$ npm -v
```

Using Homebrew
```bash
# The first step is to update your brew local cache
$ brew update

# Then run, it will install both nodejs and npm at the same time
$ brew install node 

# Finally test installation using
# It should output the currently installed version of node & npm
$ node -v
$ npm -v
```

## Getting started

First things first we are going to create a new file in our `bin` folder, I decided to use the one located at `~/.bin`, doing so will let you call our password generator script from anywhere you want. 

I am assuming that the `~/.bin/` is already registered and exported in your global environment variable `$PATH`. If not, then heads up to your terminal, `mkdir ~/.bin`, then edit your shell configuration file ( egc: `~/.bashrc`, `~/.bash_profile`, `~/.zshrc`, `~/.zsh_profile`...) by happening at the end of it `export PATH=$PATH:~/.bin`.

Once this is done, heads up to our `~/.bin/` folder and create a file using `touch` command, let's call it `createPassword`.
Now, open the file in your favorite code editor, I'll personally use `VsCode` by doing `code ./createPassword`. If everything is set up correctly you should have a blank page by now named after the file you created earlier, now let's dive in the code for our password generator.

## The script

As you may know, NodeJs has a powerful builtin cryptographic library called crypto, let's import it:

```javascript
const crypto = require('crypto');
```

> To make sure your installation of node is working I suggest you to run `node NAME_OF_THE_SCRIPT`, if it doesn't throw any error then you are all settle.

Now, what we are looking for in a password generator is its strength and robustness. We can simplify that concept by assuming that the longer it is the better. We then need a way to tell the generator how long we want the output password to be ? In our case we will use arguments. Now add this line:

```javascript
let args = process.argv.slice(2);
```

> We slice the arguments received in order to extract the custom 'parameters' (in our case, a number that we will call 'length')

Now we can create a variable in our script, called `length`. Its value will be equal to the Number we pass to our script.

```javascript
const length = Number(args[0]);
```

> Note that we cast our argument to `Number` because when we receive it from the terminal it's of type `String`


Next and last step is to check if our parsed number return a number and not an error (or NaN). If so, we simply call the crypto library and generate a random password else we alert the user that he didn't pass a correct parameter to the script. The condition looks like this:

```javascript
if (typeof(length) === 'number' && !isNaN(length)) {
   const pass = crypto.randomBytes(length).toString("hex");
   console.log(pass);
   process.exit(0); // No errors
} else {
   console.log('Error: Param must be of type number');
   process.exit(1); // Error
}
```

If we put everything together, our script should look like this:
![Script content](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4o1kmy8k54fwnrkupkny.png)

Well, that's it, hope you'll enjoy this small tutorial on how to create a password generator in under 10 lines of code using NodeJs.
'Till next time 😉.

### A little bit more about me:

I'm Lenny, senior software engineer, Founder of **[ZCorp](https://www.linkedin.com/company/zeitouncorporate/)** focused on Consulting for helping people to develop and grow their ideas into a reliable, rewarding and profitable business. 
Here are some links to my networks:
- **[GitHub](https://github.com/ZeitounCorp)**
- **[Linkedin](https://www.linkedin.com/in/lenny-zeitoun/)**
- **[Dev.to](https://dev.to/zeitouncorp)**