(Updated due to some confusion over my question) We use this method to generate a digested_password, which is saved to our database for later lookup. When we authenticate a user to our application, this method is again ran against their input and if the digested_password output matches the digested_password we saved in the database we authenticate them. I need to reproduce this function in PHP for another application that shares the database.
def self.hash_password( password, salt )
salted_password = password.insert 4, salt
digested_password = Digest::SHA512.hexdigest("#{salted_password}")
return digested_password
end
I really have no experience with Ruby so please forgive my lack of understanding.
Thanks!
Because you can’t "retrieve" a password from a one-way hash like SHA-512, the closest we can get is being able to generate the same hash from the same password and salt. Let’s look at the Ruby code:
The only thing a bit "weird" here is the call to the
.insertmethod on the password string. It’s basically splicing the salt right into the password, starting at the fourth character index. Normally salts are simply concatenated with the password.We can replicate this using
substr:I’m using the now-default hash extension here, as it’s pretty much the most reliable way to generate a SHA-512 hash.
Using this code, you should be able to generate identical hashes for a given identical password and salt combination. I’m not sure what the behavior would be when the password is less than five characters long.
Yup, looks like it should work: