Skip to content

Instantly share code, notes, and snippets.

@carlansell94
Created December 11, 2022 18:30
Show Gist options
  • Save carlansell94/f1fecf94da53f5e51c065df5ed0492fb to your computer and use it in GitHub Desktop.
Save carlansell94/f1fecf94da53f5e51c065df5ed0492fb to your computer and use it in GitHub Desktop.
Functions to create and use an eBay digital signature in Python
#!/usr/bin/env python3
from base64 import b64encode
from urllib.parse import urlparse
import sys
import time
import requests
from Crypto.PublicKey import ECC
from Crypto.Signature import eddsa
from Crypto.Hash import SHA256
from requests.exceptions import HTTPError
def get_content_digest(content: str) -> str:
hasher = SHA256.new()
hasher.update(bytes(content, encoding="utf-8"))
return b64encode(hasher.digest()).decode()
def get_digital_signature(
ebay_private_key: str,
ebay_public_key_jwe: str,
request_url: str,
signature_params: str,
) -> str:
url = urlparse(request_url)
params = (
f'"x-ebay-signature-key": {ebay_public_key_jwe}\n'
f'"@method": GET\n'
f'"@path": {url.path}\n'
f'"@authority": {url.netloc}\n'
f'"@signature-params": {signature_params}'
).encode()
try:
private_key = ECC.import_key(
f"""-----BEGIN PRIVATE KEY-----\n{ebay_private_key}\n-----END PRIVATE KEY-----"""
)
signer = eddsa.new(private_key, mode="rfc8032")
signature = signer.sign(params)
return b64encode(signature).decode()
except ValueError as error:
sys.exit(f"Error creating digital signature: {error}")
def send_signed_api_request(
ebay_private_key: str,
ebay_public_key_jwe: str,
access_token: str,
request_url: str
) -> None:
creation_time = int(time.time())
signature_input = (
'("x-ebay-signature-key" "@method" "@path" "@authority");'
f"created={creation_time}"
)
signature = get_digital_signature(
ebay_private_key=ebay_private_key,
ebay_public_key_jwe=ebay_public_key_jwe,
request_url=request_url,
signature_params=signature_input,
)
headers = {
"Authorization": "Bearer " + access_token,
"Signature-Input": f"sig1={signature_input}",
"Signature": f"sig1=:{signature}:",
"x-ebay-signature-key": ebay_public_key_jwe,
"x-ebay-enforce-signature": "true",
}
try:
response = requests.get(request_url, headers=headers, timeout=10)
response.raise_for_status()
print(response.text)
sys.exit()
except HTTPError as error:
sys.exit(f"Unable to send request: {error}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment