Created
May 26, 2012 12:01
-
-
Save cnf/2793683 to your computer and use it in GitHub Desktop.
API signing
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import httplib2 | |
import json | |
API_URL = 'http://127.0.0.1:5000/api/rest' | |
DEVICE_ID = '36263EED-7ACA-45AB-9537-DE86D88773ED' | |
API_TOKEN = 'JmGQAOAAWkpBTvoFxHQM12tfTKfSJhH3YgwE1uHOfTpZHfhkpl3iovExjfBAeSP' | |
def get_token(): | |
"""docstring for get_token""" | |
h = httplib2.Http(".cache") | |
resp, content = h.request(API_URL + '/auth', | |
"GET") | |
return json.loads(content)['token'] | |
def send_request(body_content, sign_hash): | |
"""docstring for send_request""" | |
h = httplib2.Http(".cache") | |
h.add_credentials(DEVICE_ID, sign_hash) | |
resp, content = h.request(API_URL + '/test', | |
"GET", body=body_content, | |
headers={'content-type':'application/json'} ) | |
print resp, content | |
from hashlib import sha256 | |
trans_5C = "".join([chr (x ^ 0x5c) for x in xrange(256)]) | |
trans_36 = "".join([chr (x ^ 0x36) for x in xrange(256)]) | |
blocksize = sha256().block_size | |
def hmac_sha256(key, msg, token, counter): | |
if len(key) > blocksize: | |
key = sha256(key).digest() | |
key += chr(0) * (blocksize - len(key)) | |
o_key_pad = key.translate(trans_5C) | |
i_key_pad = key.translate(trans_36) | |
return sha256(o_key_pad + sha256(i_key_pad + msg + token + str(counter)).digest()) | |
if __name__=="__main__": | |
body_content = "The quick brown fox jumps over the lazy dog" | |
token = get_token() | |
print token | |
h = hmac_sha256(API_TOKEN, body_content, token, 1) | |
sign_hash = h.hexdigest() | |
send_request(body_content, sign_hash) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment