Skip to content

Instantly share code, notes, and snippets.

@abeland
Created May 31, 2018 17:12
Show Gist options
  • Save abeland/e09a559e243f70670f2f4da3fd0fdabd to your computer and use it in GitHub Desktop.
Save abeland/e09a559e243f70670f2f4da3fd0fdabd to your computer and use it in GitHub Desktop.
HMAC something in Ruby/Rails
# ruby 2.5.0, rails 5.1.4
key = SecureRandom.hex(32) # Need 256 bits = 32 bytes of entropy. Since in hex it will be 64 characters long.
data = 'example data that I want to hmac could be json string of a big Hash for example'
hmac_bytes = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, data) # raw bytes (in string representation)
hmac_base64 = Base64.urlsafe_encode64(hmac_bytes) # often sending in a link so I use urlsafe version
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment