github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/internal/util/sign.go (about)

     1  package util
     2  
     3  import (
     4  	"bufio"
     5  	"crypto/sha1"
     6  	"encoding/hex"
     7  	"sort"
     8  )
     9  
    10  // Sign 微信公众号 url 签名.
    11  func Sign(token, timestamp, nonce string) (signature string) {
    12  	strs := sort.StringSlice{token, timestamp, nonce}
    13  	strs.Sort()
    14  
    15  	buf := make([]byte, 0, len(token)+len(timestamp)+len(nonce))
    16  	buf = append(buf, strs[0]...)
    17  	buf = append(buf, strs[1]...)
    18  	buf = append(buf, strs[2]...)
    19  
    20  	hashsum := sha1.Sum(buf)
    21  	return hex.EncodeToString(hashsum[:])
    22  }
    23  
    24  // MsgSign 微信公众号/企业号 消息体签名.
    25  func MsgSign(token, timestamp, nonce, encryptedMsg string) (signature string) {
    26  	strs := sort.StringSlice{token, timestamp, nonce, encryptedMsg}
    27  	strs.Sort()
    28  
    29  	h := sha1.New()
    30  
    31  	bufw := bufio.NewWriterSize(h, 128) // sha1.BlockSize 的整数倍
    32  	bufw.WriteString(strs[0])
    33  	bufw.WriteString(strs[1])
    34  	bufw.WriteString(strs[2])
    35  	bufw.WriteString(strs[3])
    36  	bufw.Flush()
    37  
    38  	hashsum := h.Sum(nil)
    39  	return hex.EncodeToString(hashsum)
    40  }