Created
June 17, 2011 17:13
-
-
Save michaelficarra/1031820 to your computer and use it in GitHub Desktop.
HMAC function in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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