18 Apr 2007 johnnyb   » (Journeyer)

Converting a Base64-encoded SHA1 hash to a hex (hexadecimal) encoded SHA1 hash

We are getting user accounts from a new company. Thankfully, they do SHA1 encoding on their passwords like we do. However, depending on which subsystem they are in, some of them are encoded in BASE64 and some are encoded as HEX. Ruby, as far as I'm aware, only handles hex digests for SHA1. Therefore, I had to figure out a way to convert these two formats. I'm sure someone else has already figured this out and there's an easy tool for this. But, if not, here's my ruby code:


sha1_hash_base64 = "nSOeWicjE1xBYo9b7fB3e9XLYhQ="
sha1_hash_hex = 
   sha1_hash_base64.
   unpack("m")[0].
   unpack("aaaaaaaaaaaaaaaaaaaa").
   map {|x| sprintf("%x", x[0])}.
   join

The output is 9d239e5a2723135c41628f5bedf0777bd5cb6214 which I believe to be correct (I don't have my data in front of me, so I can't be sure). At minimum, it is the right length :)

So now, I can use this value to compare against the output of Digest::SHA1.hexdigest.

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!