Skip to content

Instantly share code, notes, and snippets.

@j05h
Created November 4, 2010 18:11
Show Gist options
  • Save j05h/662881 to your computer and use it in GitHub Desktop.
Save j05h/662881 to your computer and use it in GitHub Desktop.
Code to handle Facebook's signed_request on deauthorize.
module Crypto
class UnexpectedAlgorithmException < Exception
end
class << self
def hashtext thing, *extras
Digest::SHA1.hexdigest(([thing] + extras).join(" "))
end
# Always returns a different hex salt, using +extras+ for added
# flavor.
def salt *extras
hashtext ActiveSupport::SecureRandom.hex(64), Time.now, *extras
end
def base64_url_decode(str)
str += '=' * (4 - str.length.modulo(4))
Base64.decode64(str.gsub("-", "+").gsub("_", "/"))
end
def parse_signed_request signed_request, secret
encoded_sig, payload = signed_request.split '.'
# decode the data
sig = base64_url_decode encoded_sig
data = JSON.parse(base64_url_decode payload)
if data["algorithm"] != "HMAC-SHA256"
raise UnexpectedAlgorithmException.new "Expected Facebook to use HMAC-SHA256. Got #{payload['algorithm']} instead."
end
# check sig
return nil unless sig.eql? HMAC::SHA256.digest(secret, payload)
data
end
### These are just used for testing, but are here because they have their own tests.
def encode_signed_request payload, secret
encoded = base64_url_encode payload
sig = base64_url_encode HMAC::SHA256.digest(secret, encoded)
"#{sig}.#{encoded}"
end
def base64_url_encode(str)
Base64.encode64(str).gsub('/', '_').gsub('+', '-').sub(/=.*$/, '').strip
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment