Skip to content

Instantly share code, notes, and snippets.

@turret-io
Last active December 1, 2020 09:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turret-io/21664a2323fd4fc84978 to your computer and use it in GitHub Desktop.
Save turret-io/21664a2323fd4fc84978 to your computer and use it in GitHub Desktop.
Verify HMAC in Ruby
require 'digest'
require 'base64'
require 'cgi'
require 'uri'
require 'time'
require 'openssl'
require 'json'
require 'active_support/security_utils'
SHARED_SECRET = 'sup3rs3cr3t!!'
def verifySignature(string_to_verify, signature, shared_secret)
return ActiveSupport::SecurityUtils::secure_compare(
OpenSSL::HMAC.digest('sha512', shared_secret, string_to_verify), signature)
end
def verifyTimestamp(decoded_json)
j = JSON.parse(decoded_json)
if Time.now.to_i - j["timestamp"].to_i > 30
raise 'Timestamp too far in the past'
end
return j
end
url = '[QUERYSTRING]'
query = CGI::parse(URI(url).query)
decoded_signature = Base64.urlsafe_decode64(query["signature"][0])
decoded_json = Base64.urlsafe_decode64(query["data"][0])
if verifySignature(decoded_json, decoded_signature, SHARED_SECRET)
puts "Valid signature"
# Verify timestamp
payload = verifyTimestamp(decoded_json)
puts "Timestamp verified"
puts payload
else
puts "Invalid signature"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment