Friday, August 26, 2011

Generate a SHA1 hash from the command-line in Linux

Update: See this post for an example of generating a SHA-256 hash. Or this one for MD5.

The following is how you generate a SHA1 cryptographic hash from a text value, like a password, from the command line in Linux.

echo -n password | sha1sum | awk '{print $1}'


The above command was run under Ubuntu, but it's a pretty standard utility, and I'd hazard a guess that all the important Linux distros have it by default.

The command chain above has three distinct parts, connected by the all important Unix pipe. The echo -n password portion simply echos password without the newline. If you don't use -n you'll get a different hash. The sha1sum command takes the input and generates the hash, but it adds some extra output, a dash, of which we want to be rid. This is where awk '{print $1}' comes in. It takes the output of sha1sum and returns the first field, omitting the rest, i.e. the unwanted dash.

And here's how to get the same hash in uppercase:

echo -n password | sha1sum | awk '{print toupper($1)}'


Note the addition of the awk funcion toupper() above.

1 comment:

  1. Thank you - just what I have been looking for :-)

    I was using:

    mysql somedatabase -e "SELECT SHA1('username2014-03-26secret')"