Digest Ruby (MD5, SHA) in Ruby

I don’t know how many times I’ve gone to the stdlib documentation for usage information concerning digest. Unfortunately, there’s nothing to see there, move along. Documentation is provided in the src distribution [src]/ext/digest/digest.txt. The abridged version:

require 'digest/[md5|sha1|sha2|rmd160]'    
digest = Digest::[MD5|SHA1|SHA256|SHA384|SHA512|RMD160].new   
while #some loop     
  digest.update(bytes)
end
digest.digest #raw bytes
digest.hexdigest #hex

alternatively, the short form:

require 'digest/MD5'
d = Digest::MD5.new
d.hexdigest('whatever you're digesting')

sha2 contains implementations for the digest classes SHA256,SHA384,SHA512

Finally the lengths of the returned hex strings:

len bytes len hex
MD5 16 32
SHA1 20 40
RMD160 20 40
SHA256 32 64
SHA384 48 96
SHA512 64 128

3 Responses to “Digest Ruby (MD5, SHA) in Ruby”

  1. […] TINFM meaning “there is no fine manual”, of course. Just as with digest, Ruby’s openssl documentation is missing just the bits you’ll need to get started. In order to encrypt or decrypt something, you’ll first need to instantiate the approriate cipher: […]

  2. Soleone sagt:

    Danke, genau das was ich gesucht habe!!

  3. Thanks for that. I was having some problems trying to read the official documentation.