Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Created March 19, 2011 08:42
Show Gist options
  • Save ksamuel/877340 to your computer and use it in GitHub Desktop.
Save ksamuel/877340 to your computer and use it in GitHub Desktop.
# separate the signature from the data
try:
l = signed_request.split('.', 2)
encoded_sig = str(l[0])
payload = str(l[1])
except IndexError:
raise ParsingError("'signed_request' malformed")
# pad them with "=" to make them valid base64 data if they are too short
b64_padding = lambda x: (x + "=" * ((4 - len(x) % 4) % 4))
# decode them from base 64 to a string
# TODO: check encoding
sig = base64.urlsafe_b64decode(b64_padding(encoded_sig))
data = base64.urlsafe_b64decode(b64_padding(payload))
# decode the JSON string into a dictionary
try:
data = json.loads(data)
except ValueError:
ParsingError("JSON malformed")
# check if the data is from facebook
if data['algorithm'].upper() != 'HMAC-SHA256':
raise ParsingError("'signed_request' is using an unknown algorithm")
else:
expected_sig = hmac.new(secret_key, msg=payload,
digestmod=hashlib.sha256).digest()
if sig != expected_sig:
raise ParsingError("'signed_request' signature mismatch")
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment