Last active
December 1, 2020 09:51
-
-
Save turret-io/21664a2323fd4fc84978 to your computer and use it in GitHub Desktop.
Verify HMAC in Ruby
This file contains 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 '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