Skip to content

Instantly share code, notes, and snippets.

@michaelficarra
Created June 17, 2011 17:13
Show Gist options
  • Select an option

  • Save michaelficarra/1031820 to your computer and use it in GitHub Desktop.

Select an option

Save michaelficarra/1031820 to your computer and use it in GitHub Desktop.
HMAC function in ruby
require 'openssl'
def hmac key, message
sha = OpenSSL::Digest::SHA256.new
blocksize = 64 # SHA256 uses a 64 byte (512 bit) block size
def xor str0, str1 # assuming strings are of equal length
b0 = str0.bytes.to_a
b1 = str1.bytes.to_a
result = []
b0.each_with_index do |b, i|
result << (b ^ b1[i]).chr
end
result.join ''
end
if key.length > blocksize
key = sha.update(key).to_s
sha.reset
end
if key.length < blocksize
key += 0.chr * (blocksize - key.length)
end
o_key_pad = xor key, (92.chr * blocksize)
i_key_pad = xor key, (54.chr * blocksize)
hash = sha.update(i_key_pad).update(message).to_s
sha.reset
sha.update(o_key_pad).update(hash).to_s
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment