Need help to create signature in python

191 views Asked by At

I have sample code from golang,

here is some sample values to run the code:

app_secret = 777, path = /api/orders, app_key = 12345, timestamp = 1623812664

or you guys can refer this link to get more info https://developers.tiktok-shops.com/documents/document/234136#3.Signature%20Algorithm

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "sort"
)

func generateSHA256(path string, queries map[string]string, secret string) string{
    keys := make([]string, len(queries))
    idx := 0
    for k, _ := range queries{
        keys[idx] = k
        idx++
    }
    sort.Slice(keys, func(i, j int) bool {
        return keys[i] < keys[j]
    })
    input := path
    for _, key := range keys{
        input = input + key + queries[key]
    }
    input = secret + input + secret

    h := hmac.New(sha256.New, []byte(secret))
    if _, err := h.Write([]byte(input)); err != nil{
        // todo: log error
        return ""
    }

    return hex.EncodeToString(h.Sum(nil))
}

need help converting this golang sample into python sample

i have tried but keep getting signature invalid when submit

my python code

import hmac
import hashlib

def _short_sign(self, app_key, app_secret, path, timestamp):
    base_string = "%sapp_key%stimestamp%s"%(path, app_key, timestamp)
    sign_string = app_secret + base_string + app_secret
    sign = hmac.new(app_secret.encode(), sign_string.encode(), hashlib.sha256).hexdigest()
    return sign
1

There are 1 answers

0
Aravinth Draj On

Found the issue, i was trying to digest with out digestmod

Working Example:

    sign = hmac.new(
        app_secret.encode(),
        sign_string.encode(),
        digestmod = hashlib.sha256
    ).hexdigest()