read

Nowadays you often need to come up with new passwords. Maybe you want to sign up for a service, maybe a server password needs to be changed, there are many reasons.

You also know that you should not reuse your passwords so you need to come up with a new one every time.

In this post I'm going to show you how to generate very secure passwords on your command line using OpenSSL.

What is OpenSSL?

OpenSSL is an open source toolkit for the TLS and SSL protocols. It covers many use-cases, is very complicated at times, but today we'll just use one simple feature.

Installing it should be simple, depending on your operating system.

  • Mac OS X: brew install openssl (via Homebrew)
  • Ubuntu / Debian: apt-get install openssl
  • Fedora: yum install openssl

If you have a different OS or would like to know more about installing, the OpenSSL wiki is a great place to look.

Generate a Password

To actually generate a secure password we use the OpenSSL rand command which generates pseudo-random bytes - the raw material for our new secure password.

The rand command allows us to encode the produced random bytes in base64. This encoding converts bytes to alphanumeric characters, including the characters =, +, and /. We can filter out these characters when we would like to have passwords without special characters. It reduces the random character of the password a little bit, but is not a concern when the password is more than 10 characters.

The Script

Putting it all together, here is the script with which we can create pseudo-random passwords.

openssl rand -base64 29 | tr -d "=+/" | cut -c1-25

The length of the password is 25 characters, which should be more than enough. Of course you can change the 25 to some other number, just make sure to adjust the 29 (which is the number of random bytes OpenSSL generates - this should be a bit more than your desired password length to account for special characters) to something appropriate as well.

For your convenience, you can store the following script in e.g. /usr/local/bin/genpw (don't forget to chown +x /usr/local/bin/genpw):

#!/bin/bash

LENGTH=25
if [ ! -z "$1" ] && [ $1 -gt 1 ]; then
  LENGTH=$1
fi
NUMBYTES=`echo $LENGTH | awk '{print int($1*1.16)+1}'`

openssl rand -base64 $NUMBYTES | tr -d "=+/" | cut -c1-$LENGTH

If you like this post, please share it so other people can benefit from it as well!

Blog Logo

Johann Füchsl

Co-founder and programming geek. Loves to read books.


Published

Image

Red Lever Solutions Blog

A blog on technology and business from the Red Lever Solutions team

Back to Overview