Archive for Februar, 2008

ruby main idiom

Mittwoch, Februar 20th, 2008

Because I keep forgetting, it’s


if $0 == __FILE__
  puts "main"
end

where __FILE__ contains the name of the file that the currently executing code is located in and $0 is the name of the currently executing program.

Digest Ruby (MD5, SHA) in Ruby

Sonntag, Februar 10th, 2008

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