Re: OT (sorry) base64 conversion in ruby

Rob Park
Thu, 05 May 2005 18:03:32 -0000

On 5/5/05, Gavin Kistner <gavin-XtLdkLkwz3ZWk0Htik3J/w@public.gmane.org>
wrote:
> Is this really a single base-16 number?
> "60d06a02dc53d67b123647f12a0d896d5d839294".to_i( 16 )
> #=> 552710903876121934266138116081162544013019157140
>
> Or is it really a series of 40 bytes represented as hex pairs?

It is an SHA1 hash, so to answer that question I''d have to know a lot
more about what SHA1 is doing exactly when it hashes a file.

I don''t think it''s relevant to the question though, because
the
".hex.to_s(36)" is halfway to doing what I want it to do: it makes the
string shorter, and it makes it use a-z instead of just a-f. I''m
looking for some way to say ".to_s(64)" so that the string will be
even shorter still, while using [0-9a-zA-Z].

; irb
irb(main):001:0> require ''digest/sha1''
=> true

irb(main):002:0> Digest::SHA1.hexdigest("foo")
=> "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"

irb(main):003:0> Digest::SHA1.hexdigest("foo").hex
=> 68123873083688143418383284816464454849230703155

irb(main):007:0> Digest::SHA1.hexdigest("foo").hex.to_s(64)
ArgumentError: illegal radix 64
        from (irb):7:in `to_s''
        from (irb):7

irb(main):008:0> Digest::SHA1.hexdigest("foo").hex.to_s(36)
=> "1e6gpc3ehk0mu2jqu8cg42g009s796b"

> "60d06a02dc53d67b123647f12a0d896d5d839294".scan( /../ ).each do
|byte|
>    puts byte.to_i( 16 )
> end

Well, it''s not a very useful representation:

Digest::SHA1.hexdigest("foo").scan(/../).each do |byte|
  print byte.hex.chr
end

prints mostly garbage.