Skip to content

Instantly share code, notes, and snippets.

@jaredrhine
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredrhine/d5333039bc27c89b15c6 to your computer and use it in GitHub Desktop.
Save jaredrhine/d5333039bc27c89b15c6 to your computer and use it in GitHub Desktop.
Trivial HMAC ruby pattern
#!/usr/bin/env ruby
# http://ruby-doc.org/stdlib-2.1.5/libdoc/openssl/rdoc/OpenSSL/HMAC.html#method-c-digest
require 'openssl'
secret_key = 'secret_key'
digest_algo = 'sha1'
input_data = 'The quick brown fox jumps over the lazy dog'
digest1 = OpenSSL::Digest.new(digest_algo)
hmac1 = OpenSSL::HMAC.new(secret_key, digest1)
mac_hex_1 = hmac1.update(input_data).hexdigest
puts "HMAC code is <#{mac_hex_1}>"
hmac1.reset
### ---------------------
digest2 = OpenSSL::Digest.new(digest_algo)
hmac2 = OpenSSL::HMAC.new(secret_key, digest2)
output_data = input_data
mac_hex_2 = hmac2.update(output_data).hexdigest
valid = mac_hex_1 == mac_hex_2
puts "HMAC validity is <#{valid}> for HMAC code of <#{mac_hex_1}>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment