Friday, August 26, 2011

Generate a SHA1 hash from the command-line in Linux

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}'

5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

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)}'

5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8

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

2 comments:

  1. This comment has been removed by the author.

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

    I was using:

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

    ReplyDelete