Skip to content

Instantly share code, notes, and snippets.

@qs-wang
Last active November 8, 2022 06:15
Show Gist options
  • Select an option

  • Save qs-wang/3cfeb266bfb3938c8a3cedc7542fa6b0 to your computer and use it in GitHub Desktop.

Select an option

Save qs-wang/3cfeb266bfb3938c8a3cedc7542fa6b0 to your computer and use it in GitHub Desktop.

Revisions

  1. qs-wang renamed this gist Nov 8, 2022. 1 changed file with 0 additions and 0 deletions.
  2. qs-wang created this gist Nov 8, 2022.
    84 changes: 84 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    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)