Skip to content

Instantly share code, notes, and snippets.

@qs-wang
Last active November 8, 2022 06:15
Show Gist options
  • Save qs-wang/3cfeb266bfb3938c8a3cedc7542fa6b0 to your computer and use it in GitHub Desktop.
Save qs-wang/3cfeb266bfb3938c8a3cedc7542fa6b0 to your computer and use it in GitHub Desktop.
import json
from datetime import datetime as dt
from Crypto.Hash import SHA1 # Python3 should use PyCryptodome
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
import requests
from base64 import (
b64encode
)
private_key_string = ("-----BEGIN RSA PRIVATE KEY-----\n"
"privatekeyhere"
"\n-----END RSA PRIVATE KEY-----\n")
URL = 'endpointhere'
def encryptMap(maps):
keys = sorted(maps.keys())
str_exp = ""
for key in keys:
value = maps[key]
if key != "appId":
if type(value) == dict:
if key == 'content':
str_exp += key + "=" + json.dumps(dict(sorted(value.items(), key=lambda x: x[0]))) + "&"
else:
str_exp += key + "={" + encryptMap(value) + "}"
elif type(value) == list:
str_exp += key + "=[" + encryptlist(value) + "]"
elif value != None:
str_exp += key + "=" + str(value) + "&"
return str_exp.strip('&')
def encryptValue(value):
if type(value) == dict:
return "{" + encryptMap(value) + "}"
elif (type(value) == list):
return "[" + encryptlist(value) + "]"
elif (value != None):
return str(value)
def encryptlist(lst):
return ','.join(list(map(encryptValue, lst)))
def attachSignature(params):
params_new = params.copy()
now = dt.now()
s = now.strftime("%Y-%m-%d %H:%m:%S")
params_new['time'] = s
exp_str = encryptValue(params_new)
exp_str = exp_str.strip("{").strip("}")
print("raw:",exp_str)
digest = SHA1.new(data=exp_str.encode("utf-8"))
private_key = RSA.importKey(private_key_string)
# Load private key and sign message
signer = PKCS1_v1_5.new(private_key)
sig = signer.sign(digest)
sigbase64 = b64encode(sig)
params_new['sign'] = sigbase64.decode("utf-8")
return params_new
if __name__ == "__main__":
content = {"testContent": "test"}
params = attachSignature(content)
print("params:", params)
r = requests.post(url = URL, json = params)
pastebin_url = r.text
print("The response:%s"%pastebin_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment