Skip to content

Instantly share code, notes, and snippets.

@hannahwhy
Created December 15, 2012 02:53
Show Gist options
  • Save hannahwhy/4290927 to your computer and use it in GitHub Desktop.
Save hannahwhy/4290927 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'securerandom'
require 'base64'
HM_KEY = "5\xC1\x16\x80\xA2HS\xC2\xFBX\x15\x9D\x1Dp\x9Dj\x11h\xDD\x9B\xF4|Q4\xFB\xEE7\xEE\x1E@\xFD\xFC"
MK_KEY = "\xBC\x7F?\x96w\xD7RM|\v%\xB3\x93\x95\xD8\xDD\xC6\xFB\xD1\xA9=\xAF\x7F\xD5\b\x1AU4\xC1\x05t\x89"
def issue(user, time_delta)
mac_key, enc_mac_key, iv = gen_mac_key
mac_key_identifier = "#{user}:#{Time.now.to_i}:#{time_delta}:#{iv}#{enc_mac_key}"
mk64 = Base64.strict_encode64(mac_key_identifier)
maced = append_hmac(mk64)
{ :mac_key => mac_key,
:mac_key_identifier => maced,
:hmac => 'hmac-sha-256'
}.map { |k, v| "#{k}=#{v}" }.join('&')
end
def gen_mac_key
key = Base64.strict_encode64(SecureRandom.random_bytes(32))
cipher = OpenSSL::Cipher::AES256.new(:CTR)
cipher.encrypt
cipher.key = MK_KEY
iv = cipher.random_iv
enc_key = cipher.update(key) + cipher.final
[key, enc_key, iv]
end
def append_hmac(input)
hmac = OpenSSL::HMAC.new(HM_KEY, 'sha256')
hmac << input
"#{input}:#{hmac}"
end
puts issue('nakoudo@ninjawedding.org', 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment