hmac-sha256
本质上,hmac-sha256是对字节流进行加密,得到的结果也是字节流
而我们可以根据需要,将加密后的字节流转换为base64格式字符串、hex格式字符串或者其他格式字符串
以下为hmac-sha256生成【base64格式字符串】签名的样例
python
import base64
import hmac
import hashlib
def hmac_sha256_sign(data, key):
key = key.encode('utf-8')
message = data.encode('utf-8')
temp_sign = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest())
# bytes -> str
sign = str(temp_sign)
print(sign)
return sign
Golang
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
)
func HmacSha256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
网友评论