Re: OT (sorry) base64 conversion in ruby

Florian Groß
Thu, 05 May 2005 23:02:43 -0000

Rob Park wrote:

> 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.

What about this?

irb(main):001:0> Base64.encode64(Digest::SHA1.digest("foo")).chomp
=> "C+7Hteo/D9vJXQ3UfzxbwnXaijM="
irb(main):018:0> Digest::SHA1.hexdigest("foo").to_i(16).to_s(36)
=> "1e6gpc3ehk0mu2jqu8cg42g009s796b"
irb(main):003:0> Digest::SHA1.hexdigest("foo")
=> "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"