php实现
function makeSignature($args, $key){ if(isset($args['sign'])) { $oldSign = $args['sign']; unset($args['sign']); } else { $oldSign = ''; } ksort($args); $requestString = ''; foreach($args as $k => $v) { $requestString .= $k . '=' . urlencode($v); } $newSign = hash_hmac("sha256",strtolower($requestString) , $key); return $newSign;}
golang 实现
package mainimport ( "crypto/sha1" "crypto/hmac""crypto/sha256" "encoding/hex" "fmt" "sort" "strconv" "time")func makeSign(params, key) { var dataParams string //ksort var keys []string for k := range params { keys = append(keys, k) } sort.Strings(keys) //拼接 for _, k := range keys { fmt.Println("key:", k, "Value:", params[k]) dataParams = dataParams + k + "=" + params[k] + "&" } fmt.Println(dataParams) ff := dataParams[0 : len(dataParams)-1] fmt.Println("去掉最后一个&:", ff) //对字符串进行hmac哈希 h := hmac.New(sha256.New, key) h.Write([]byte(dataParams)) bs := h.Sum(nil) sign := hex.EncodeToString(bs) //拼接请求参数 dataPost := dataParams + "&sign" + "=" + sign return dataPost}
python实现
from hashlib import sha256import urllibimport hmacdef urlencode(val): return urllib.parse.quote(val, safe='/', encoding=None, errors=None)def ksort(d): '''遍历字典转成list''' return [(k,urlencode(d[k])) for k in sorted(d.keys())]def makeSign(params, key): dd = ksort(params) data = "&".join(["=".join(i) for i in dd if i[1] and i[0] != "sign"]) return hmac.new(key.encode('utf-8'), data.encode('utf-8'), digestmod=sha256).hexdigest().upper()
来源地址:https://blog.csdn.net/yangyin007/article/details/126875510