Home > Articles > Programming > Ruby

📄 Contents

  • Print
  • + Share This
This chapter is from the book

2.35 Calculating the MD5 Hash of a String

The MD5 message-digest algorithm produces a 128-bit fingerprint or message digest of a message of arbitrary length. This is in the form of a hash, so the encryption is one-way and does not allow for the discovery of the original message from the digest. Ruby has an extension for a class to implement MD5; for those interested in the source code, it's in the ext/md5 directory of the standard Ruby distribution.

There are two class methods, new and md5, to create a new MD5 object. There is really no difference in them:

require 'md5'
hash = MD5.md5
hash = MD5.new

There are four instance methods: clone, digest, hexdigest, and update. The clone method simply copies the object; update is used to add content to the object as follows:

hash.update("More information...")

You can also create the object and add to the message at the same time:

secret = MD5.new("Sensitive data")

If a string argument is given, it is added to the object using update. Repeated calls are equivalent to a single call with concatenated arguments:

# These two statements...
cryptic.update(" and more data.")

# ...are equivalent to this one.
cryptic.update("Data... and more data.")

The digest method provides a 16-byte binary string containing the 128-bit digest.

The hexdigest method is actually the most useful. It provides the digest as an ASCII string of 32 hex characters representing the 16 bytes. This method is equivalent to the following:

def hexdigest
  ret = ''
  digest.each_byte {|i| ret << sprintf('%02x', i) }

secret.hexdigest  #  "b30e77a94604b78bd7a7e64ad500f3c2"

In short, you can get an MD5 hash as follows:

require 'md5'
m = MD5.new("Sensitive data").hexdigest
  • + Share This
  • 🔖 Save To Your Account