RoR - MD5 generation
Asked Answered
A

1

84

How can I encrypt a string with MD5 in Rails 3.0 ? pass = MD5.hexdigest(pass) in a model yields uninitialized constant MyModel::MD5

Arsphenamine answered 22/11, 2010 at 7:10 Comment(2)
You might want to check out this post on why using MD5/SHA as part of your authentication scheme is a poor choice: codahale.com/how-to-safely-store-a-passwordStepdaughter
A point of terminology: hashing, using e.g. the MD5 algorithm, is not encryption. You encrypt something when you can also want to be able to decrypt it. You usually cannot determine the original message from a hash and often that is exactly the point of using a hashing algorithm.Filip
L
190

You can use Digest::MD5 from the Ruby standard library for this.

irb(main):001:0> require 'digest/md5'
=> true
irb(main):002:0> Digest::MD5.hexdigest('foobar')
=> "3858f62230ac3c915f300c664312c63f"

And one more thing: MD5 is a hash algorithm. You don't "encrypt" anything with a hash algorithm.

Lightproof answered 22/11, 2010 at 7:16 Comment(4)
One more thing: MD5 has basically been broken (in the cryptographic sense) and shouldn't be used any more. If you start a new software project, use a stronger hash algorithm like SHA512 or bcrypt and don't forget to add a salt to your passwords before hashing them.Lightproof
MD5 is broken for cryptographic purposes, but can still be used to compare files. Git still uses it after all. BUT DON"T HASH PASSWORDS WITH MD5Ballplayer
Git is using SHA1 for almost all its hashing needs.Lightproof
If you are hashing password for storage into the database, use bcrypt, not MD5. Both are available as Ruby libraries and from an implementation perspective both are equally easy, but in the unlikely event that your database is compromised (which is the whole point of hashing password before storage), bcrypt will be harder to crack than md5 and so is always a better choice. Don't forget to add a salt.Homey

© 2022 - 2024 — McMap. All rights reserved.