Skip to content

Instantly share code, notes, and snippets.

@christ0pher
Created June 15, 2015 16:37
Show Gist options
  • Save christ0pher/f2c4748a09ed31cf71a8 to your computer and use it in GitHub Desktop.
Save christ0pher/f2c4748a09ed31cf71a8 to your computer and use it in GitHub Desktop.
Google URL-signing for Python3
from requests.packages.urllib3.util import parse_url
import hashlib
import hmac
import base64
""" Sign a URL using the client_secret """
__author__ = 'christopher@levire.com'
def sign_url(input_url=None, client_id=None, client_secret=None):
""" Sign a request URL with a Crypto Key.
Usage:
from urlsigner import sign_url
signed_url = sign_url(input_url=my_url,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET)
Args:
input_url - The URL to sign
client_id - Your Client ID
client_secret - Your Crypto Key
Returns:
The signed request URL
"""
# Return if any parameters aren't given
if not input_url or not client_id or not client_secret:
return None
# Add the Client ID to the URL
input_url += "&client=%s" % (client_id)
url = parse_url(input_url)
# We only need to sign the path+query part of the string
url_to_sign = url.path + "?" + url.query
# Decode the private key into its binary format
# We need to decode the URL-encoded private key
decoded_key = base64.urlsafe_b64decode(client_secret)
# Create a signature using the private key and the URL-encoded
# string using HMAC SHA1. This signature will be binary.
signature = hmac.new(decoded_key, url_to_sign.encode(), hashlib.sha1)
# Encode the binary signature into base64 for use within a URL
encoded_signature = base64.urlsafe_b64encode(signature.digest())
original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query
# Return signed URL
return original_url + "&signature=" + encoded_signature.decode()
@christ0pher
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment