I recently came across a requirement to dynamically generate a password on a Linux system.

Being a password, it implied that the text had to be truly random, which is a tough order of requirement for any home-brew algorithm, once you really get an idea of  on why its hard to generate randomness

Radom is hard

Radom is hard

The solution = /dev/random .

In theory /dev/random is a file you can read infinitely. However in practise you would find that reading this file would block every now and then until it has contents in it, generated randomly from device driver noise bits. So you might have to move your mouse or spin the disk etc to get some random bits into the /dev/random file.

A More practical solution = /dev/urandom

urandom can get random iput from from /dev/random, else it generates fairly randomized bytes for you, using a Random Number Generator Cryptographic algorithm, provided by a kernel module of the same name. AND, its never guaranteed to block. Talk about best of both worlds !!!

My random Text Command

Bytes read from random or urandom are not likely to be all ASCII and therefore requires to be filtered for ASCII, for which this was the chosen solution -

tr -dc A-Za-z0-9 </dev/urandom |  head -c 14

The problem in the solution

The only doubt that this simple solution envisaged in my rustic Unix mind was if this command line would exit after head had received the 14 characters it required.

If you do not know the answer, it is contained in my previous post on Unix shell pipes.

Happy hacking !!!

About these ads