OT (sorry) base64 conversion in ruby

Rob Park
Thu, 05 May 2005 05:59:24 -0000

Hi everybody. I''m trying to convert a hex value into base64, but
I''m
having some problems. The problem is that Base64.encode64 is doing a
conversion based on the string representation of the hex value (eg, I
have a number represented in base 16 that I would like to be
represented in base 64, to do the conversion mathematically, not based
on the string representation of the base 16 number).

It''s kind of a long story but basically I am hashing some data to
create a password (eg, the hash IS the password, it''s not a hash of a
password), and the hash is SHA1, so it''s a number represented by a 40
character string of hex. The problem is, I''d prefer a password that
uses upper and lower case letters, not just 0-9, a-f. So converting
this hex value into base64 will make the password shorter, but opens
it up to many more possible letters.

I''ve found that Bignum#to_s brings me close to what I want:

Digest::SHA1.hexdigest(some text).hex.to_s(36)

This changes eg, "60d06a02dc53d67b123647f12a0d896d5d839294", into
"bb4f93cgwkckm9gl8g90n3zsp2zvwr8", which is a few chars shorter and is
using 0-9, a-z instead of just 0-9, a-f, so it''s a step in the right
direction. But it''d be really nice if I could do this:

Digest::SHA1.hexdigest(some text).hex.to_s(64)

to get a string that''s even shorter and using uppercase and lowercase
letters as well as numbers, plus a couple symbols or whatever.

Anybody have any ideas? The obvious:

Base64.encode64("60d06a02dc53d67b123647f12a0d896d5d839294")

just produces:

NjBkMDZhMDJkYzUzZDY3YjEyMzY0N2YxMmEwZDg5NmQ1ZDgzOTI5NA=
which is not what I''m looking for. encode64 just pukes if I feed it a
Bignum as well.

Thanks.