2009/03/07

How to generate password on linux system


Every user eventually will need to create secure password (alphanumeric, not a common word, etc).
On linux, you can easily generate it without additional software

To generate eight characters long alphanumeric password use following line:

tr -dc '0-9a-zA-Z' </dev/urandom |head -c 8;echo


You can put this into shell script, if you are going to need it often.

In case you are a newbie and don't understand what this line does, explanation is below.

Explanation

/dev/urandom is one of a few special files on linux/unix systems (other files are /dev/zero, /dev/null and /dev/random).
/dev/urandom provides endless stream of pseaudo-random data, but even if you paste data from that file into text file, you won't be able to use it as password, because it will containt a lot of characters that doesn't fit into ASCII charset.
So that's why "tr" comand is used. "tr -dc '0-9a-zA-Z'" reads data from /dev/urandom and then prints to output only characters that fit into given character set (which is '0-9a-zA-Z'). See "man tr" for more details.
This means that if you want use another set of characters in password, you will need change character set to something else.
For example, '0-9' means only numeric characters, '0-9a-z' - numeric or lowercase latin letters, and '0-9a-zA-Z!@#$%^&*()_+-' will include extra characters to make your password more secure.

Because /dev/urandom is "endless", "head -c 8" is used to copy first 8 characters (see "man head" for explanation).
If you need more or less characters, change number accordingly.

"echo" command without arguments simply prints a newline. It is only useful if you want to print password into terminal (because without "echo" next shell prompt will be printed right after password - on the same line).

Possible problems
On system with UTF-8 locale, you won't be able to generate password with non-ASCII letters using this method. This is because tr handles only one character("byte") at the time, and UTF8-encoded non-ASCII character will use more than one byte.

1 comment:

  1. You may want to look into using a password generator like 'apg', as it does not only generate a random password, it also ensures they're strong, and can also produce pronounceable passwords that are easier to remember than purely random letters and numbers.

    ReplyDelete