在对接PHP语言实现的签名的时候,看见对方用了ksort,由于golang里面对map的遍历是无序的,所以用golang实现了对map按key值进行升序排序:
package mainimport ("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//ksortvar keys []stringfor 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" + "=" + signfmt.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