こちらのページに記載した MD5 と SHA-1 を ruby で扱うサンプルコードを記載します。
MD5: Message Digest 5 (16進数 32桁で表現可能)
SHA-1: シャーワン (16進数 40桁で表現可能)
require 'digest/md5'
require 'digest/sha1'
#
# 文字列のハッシュ値を (16 進数 ASCII 文字列で) 取得
#
src = "abc"
# 方法1: クラスメソッド
md5_str = Digest::MD5.hexdigest(src)
sha1_str = Digest::SHA1.hexdigest(src)
p md5_str #=> 900150983cd24fb0d6963f7d28e17f72 (32文字, 16バイト)
p sha1_str #=> a9993e364706816aba3e25717850c26c9cd0d89d (40文字, 20バイト)
# 方法2: インスタンスメソッド
md5 = Digest::MD5.new
sha1 = Digest::SHA1.new
md5.update(src)
sha1.update(src)
md5_str = md5.hexdigest(src)
sha1_str = sha1.hexdigest(src)
p md5_str #=> 900150983cd24fb0d6963f7d28e17f72
p sha1_str #=> a9993e364706816aba3e25717850c26c9cd0d89d
#
# 文字列のハッシュ値をバイト列で取得 (バイト列は左側から。数値と混乱しない)
#
md5_byte_str = Digest::MD5.digest(src)
sha1_byte_str = Digest::SHA1.digest(src)
p md5_byte_str #=> "\x90\x01P\x98<\xD2O\xB0\xD6\x96?}(\xE1\x7Fr"
p md5_byte_str.size #=> 16
p sha1_byte_str #=> "\xA9\x99>6G\x06\x81j\xBA>%qxP\xC2l\x9C\xD0\xD8\x9D"
p sha1_byte_str.size #=> 20
md5_byte_str.each_byte do |byte|
p byte # 144,1,80,152,60,210,79,176,214,150,63,125,40,225,127,114
p byte.chr # "\x90","\x01","P","\x98","<","\xD2","O","\xB0","\xD6","\x96","?","}","(","\xE1","\x7F","r"
end
md5_byte_str.each_char do |char|
p char # "\x90","\x01","P","\x98","<","\xD2","O","\xB0","\xD6","\x96","?","}","(","\xE1","\x7F","r"
end
#
# 数値のハッシュ値を取得
#
src = 1234567890
# 符号なし 4 バイト数値 (として扱う)
unsigned_int_4_bytes = [
(src & 0xFF) >> 0,
(src & 0xFF00) >> 8,
(src & 0xFF0000) >> 16,
(src & 0xFF000000) >> 24,
]
md5 = Digest::MD5.new
unsigned_int_4_bytes.each do |byte|
char = byte.chr
md5.update(char)
end
md5_byte_str = md5.digest
md5_byte_str.each_byte do |byte|
p byte # 187,177,240,74,206,179,182,144,63,127,54,74,37,80,18,32
end
p md5.hexdigest # bbb1f04aceb3b6903f7f364a25501220 (32文字, 16バイト)
$ echo "abc" | md5sum
900150983cd24fb0d6963f7d28e17f72 -
$ echo "abc" | sha1sum
a9993e364706816aba3e25717850c26c9cd0d89d -
$ perl -e "print pack('L', 1234567890)" | md5sum
bbb1f04aceb3b6903f7f364a25501220 -