#!/usr/bin/python

import base64
import hmac, sha
from Crypto.Cipher import AES

# App output when works:
# DeviceId: AOuj_RqCSeCZy8wgPSmXBFBnN7vKhqXUZVD5ufDaVXhxI8XxspMxLMQZYpR4z-poiAxjkzm0gJyusNBXHfXKPfDcHlZjFubgR56GH55LzbqpaM6v-BdVB8o
# DeviceKey: nX3iN+5PPYg3zSh8ljDZJSjivNjcGk6E4nYVev+7bcc=
# data: Cjc9v/5xTrlZvL30fV3kwRNYJSE=
# decrypted key: lr17uYS5dKeu5Syrg/gL+n/eEMA=

developer_secret = 'IyBYcfo/d8cNaXAzQyBIeA=='
# works
# device_key = 'nX3iN+5PPYg3zSh8ljDZJSjivNjcGk6E4nYVev+7bcc='

# doesn't work
device_key = 'wsUrjmNHeaXZFpzQlDFqK+KklHuanIJRde9VNT+m/LY='
# App decoded device key: XWkOzAjNXGQZHrffLJMg1GS0uQ==

path = '/feeds/api/standardfeeds/most_popular?v=2&max-results=10&start-index=1&time=today&alt=json&format=3&safeSearch=strict'

aes_key = base64.b64decode(developer_secret) # 1
cipher = AES.new(aes_key, AES.MODE_ECB)
decrypted = cipher.decrypt(base64.b64decode(device_key)) # 2, 3

# Find and remove padding:
potential_padding = ord(decrypted[-1])
if decrypted.endswith(decrypted[-1] * potential_padding): # 4
	decrypted = decrypted[:len(decrypted) - potential_padding]

decrypted_base64enc = base64.b64encode(decrypted);
print "Decrypted key base64 encoded (%s)" % (decrypted_base64enc)

# def GenerateAuthHeader(self, path):
# Initialize HMAC-SHA1 with our decrypted device key from the registration process
# The data to sign is the path portion of the URL
h = hmac.new(decrypted, path, digestmod=sha) # 1
# base64 encode the digest for transmission
signature = base64.b64encode(h.digest()) # 2
# Include this encoded digest with our device ID in the

print "Generated auth header data (%s)" % (signature)
  
#  return {'X-GData-Device': header_value} # 3





