Reputation: 11
I have looked for an answer in an existing question, but found nothing which covers this hashing scheme in Rails.
I am currently migrating a PHP project over to Ruby-on-Rails, which I am still learning. I am struggling to port over an MD5 (I know, it's only temporary...) hashing scheme for hashing user passwords. I have plain MD5 working, but cannot find the correct syntax for the hashing scheme I need.
The mechanics of the hashing scheme in the PHP project are:
Create MD5 hash of password. Create MD5 hash of salt. Concatenate password_hash with salt_hash. Create MD5 hash of concatenated_string. Compare stored_hash to concatenated_string
The PHP for the hash creation is:
function fn_generate_salted_password($password, $salt)
{
$_pass = '';
if (empty($salt)) {
$_pass = md5($password);
} else {
$_pass = md5(md5($password) . md5($salt));
}
return $_pass;
}
The (pathetic) attempt I have for this section in Rails so far is:
Spree::User.class_eval do
def valid_password?(password)
if self.salt.present
if ::Digest::MD5.hexdigest((::Digest::MD5.hexdigest(password)).(::Digest::MD5.hexdigest(salt))) == self.stored_hash
*# Do some stuff*
else
false
end
end
end
end
Any ideas?
Upvotes: 1
Views: 633
Reputation: 106782
I would do something like this:
def valid_password?(password)
secret = if salt.present?
[password, salt].map { |part| ::Digest::MD5.hexdigest(part) }.join
else
password
end
stored_hash == ::Digest::MD5.hexdigest(secret)
end
Upvotes: 1