Frage

what is the equivalent in Rails of this (PHP):

 hash_hmac('sha512', $password . $salt, $siteSalt);

I got as far as this:

Digest::SHA512.hexdigest(password + salt)

But have no idea how to incorporate the site salt into the equation, all online examples I've seen do not pass the salt to the hexdigest method. When I've tried it I get an error for too many arguments.

And this notation with a colon (which I saw somewhere):

salted = password + salt
Digest::SHA512.hexdigest("#{salted}:site_salt")

Doesn't produce the same hash.

Thanks

Edit I stumbled upon this that looks closer to what I need (sorry, I'm very new to the whole hashing thing):

OpenSSL::HMAC.hexdigest('sha512', site_salt, salted)

But it still produces a different hash than the one stored in the database.

War es hilfreich?

Lösung

I think this will do what you want:

HMAC::SHA512.hexdigest(site_salt, password + salt)

It looks like the PHP code you're referencing is using the siteSalt as the key for the HMAC function, with the password and salt concatenated specified as the value to be hashed.

I checked this by running this code in PHP:

% php -r 'print hash_hmac("sha512", "password" . "salt", "siteSalt") . "\n";'
15b45385a00b10eb25c3aa8198d747862575a796a89a6c79b5a0b8ea332a8d75b1ec0dc1f0c9f7930d30c9359279e86df29067bbbc5d9bcf87839f855ac7a677

And then in the Rails shell:

>> HMAC::SHA512.hexdigest('siteSalt', 'password' + 'salt')
=> "15b45385a00b10eb25c3aa8198d747862575a796a89a6c79b5a0b8ea332a8d75b1ec0dc1f0c9f7930d30c9359279e86df29067bbbc5d9bcf87839f855ac7a677"

Andere Tipps

I'm using Rails 4 and @brian's rails code didn't compile for me.

Here is what worked for me.

Rails shell:

2.1.2 :001 > Digest::HMAC.hexdigest("password"+"salt","siteSalt",Digest::SHA512)
 => "15b45385a00b10eb25c3aa8198d747862575a796a89a6c79b5a0b8ea332a8d75b1ec0dc1f0c9f7930d30c9359279e86df29067bbbc5d9bcf87839f855ac7a677"

PHP (from command line)

 $ php -r 'print hash_hmac("sha512", "password" . "salt", "siteSalt") . "\n";'
15b45385a00b10eb25c3aa8198d747862575a796a89a6c79b5a0b8ea332a8d75b1ec0dc1f0c9f7930d30c9359279e86df29067bbbc5d9bcf87839f855ac7a677

It turns out the salt was empty in the PHP code, hence the discrepancy. But now both methods return the same.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top