在对接PHP语言实现的签名的时候,看见对方用了ksort,由于golang里面对map的遍历是无序的,所以用golang实现了对map按key值进行升序排序:
package main
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"sort"
"strconv"
"time"
)
func main() {
timeStamp := time.Now().Unix()
params := map[string]string{
"staff_name": "hhh",
"client_id": "123",
"staff_id": "114",
"time": strconv.FormatInt(timeStamp, 10),
"secret": "aaa-999",
"sign": "",
}
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)
//对字符串进行sha1哈希
h := sha1.New()
h.Write([]byte(dataParams))
bs := h.Sum(nil)
sign := hex.EncodeToString(bs)
//拼接请求参数
dataPost := dataParams + "&sign" + "=" + sign
fmt.Println(dataPost)
}
排序结果如下:
key: client_id Value: 123
key: secret Value: aaa-999
key: sign Value:
key: staff_id Value: 114
key: staff_name Value: hhh
key: time Value: 1554100502
sh1哈希结果:
3c8cfd20311b2ac0c74df290686e34a61a55ad71
有疑问加站长微信联系(非本文作者)