Go实战--go中使用hmac sha256(The way to go)
声明不止,继续 go go go !!!
上一篇blog介绍了base64加密,今天继续介绍一下关于加密方面的实战应用,也就是hmac sha256.
何为hmac?
wiki:
In cryptography, a keyed-hash message authentication code (HMAC) is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key.
百度百科:
HMAC是**相关的哈希运算消息认证码,HMAC运算利用哈希算法,以一个**和一个消息为输入,生成一个消息摘要作为输出。
主要用于验证接口签名~
何为sha256?
哈希值用作表示大量数据的固定大小的唯一值。数据的少量更改会在哈希值中产生不可预知的大量更改。
SHA256 算法的哈希值大小为 256 位。
crypto/hmac
Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. An HMAC is a cryptographic hash that uses a key to sign a message. The receiver verifies the hash by recomputing it using the same key.
func New
func New(h func() hash.Hash, key []byte) hash.Hash
New returns a new HMAC hash using the given hash.Hash type and key.
crypto/sha256
Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
func New
func New() hash.Hash
New returns a new hash.Hash computing the SHA256 checksum.
使用:
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
h := sha256.New()
h.Write([]byte("hello world\n"))
fmt.Printf("%x", h.Sum(nil))
}
应用
package main
import (
"crypto/hmac"
"crypto/sha256"
"fmt"
"io"
)
func main() {
c := getSha256Code("aaa@qq.com")
fmt.Println(c)
c = getHmacCode("aaa@qq.com")
fmt.Println(c)
}
func getHmacCode(s string) string {
h := hmac.New(sha256.New, []byte("ourkey"))
io.WriteString(h, s)
return fmt.Sprintf("%x", h.Sum(nil))
}
func getSha256Code(s string) string {
h := sha256.New()
h.Write([]byte(s))
return fmt.Sprintf("%x", h.Sum(nil))
}
输出:
973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b
453159a62580804892cc90a27dfb8bfdf2309107336445dcfd0186674111ee71
上一篇: 个人站长成功的七条经验分享
下一篇: 网站站长赚钱的七条经验分享