79
votes

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

1
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-password - Mike Buckbee
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. - Confusion

1 Answers

181
votes

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.