views:

38

answers:

1

Hey everyone,

in PHP there is the hash() function that can return raw binary data.

http://de2.php.net/manual/en/function.hash.php

I want to do the same in Ruby. How do I do that?

I generate the hash with:

h = Digest::SHA2.new(512) << "hashme"

PHP generates 32 byte of "raw binary output".

+2  A: 

If you need the output to be a length of 32, you just need to call Digest::SHA2.new with a bit length of 256 (which is the default):

irb> require 'digest/sha2'
=> true
irb> h = Digest::SHA2.new(256) << "hashme"
=> #<Digest::SHA2:256 02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86>
irb> puts h.length
32
=> nil
irb> puts h
02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86
=> nil

Or just:

irb> h = Digest::SHA2.new << "hashme"
=> #<Digest::SHA2:256 02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86>
irb> puts h.length
32
=> nil
irb> puts h
02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86
=> nil

Hope this helps!

Brian
thank you very much but this does not solve my problem. PHP has a third parameter in hash() that triggers "raw binary" output. i want to convert h to be the exact same "raw binary" output. see http://de2.php.net/manual/en/function.hash.php
Lennart
okay i solved it by just calling h.digest :) thank you very much!
Lennart