golang map做排序后,md5加密

Go map字典排序后md5加密

 

package main

import (
    "bytes"
    "crypto/md5"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "sort"
    "strings"
)

func main() {
    params := make(map[string]interface{})
    params["name"] = "test"
    params["key"] = "123aa!31."
    params["domain"] = "https://www.baidu.com?name=1&id=1"

    // 排序
    keys := make([]string, len(params))
    i := 0
    for k, _ := range params {
        keys[i] = k
        i++
    }
    sort.Strings(keys)
    fmt.Println("keys:",keys)

    byteBuf := bytes.NewBuffer([]byte{})
    encoder := json.NewEncoder(byteBuf)
    encoder.SetEscapeHTML(false)

    err := encoder.Encode(params)

    if err != nil {
        panic(err)
    }

    data := byteBuf.String()

    h := md5.New()
    h.Write([]byte(strings.TrimRight(data, "\n")))
    fmt.Println(hex.EncodeToString(h.Sum(nil)))
}

 

posted on 2022-01-20 14:22  星河赵  阅读(382)  评论(1编辑  收藏  举报

导航