读取文件,同时计算多组 Hash 值,包括:md5、sha1、sha256、HMACSHA256、HMACSHA512
package main
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"io"
"log"
"strings"
)
func main() {
md5Hash := md5.New()
sha1Hash := sha1.New()
sha256Hash := sha256.New()
sha512Hash := sha512.New()
hmacSHA256 := hmac.New(sha256.New, []byte("test-data"))
hamcSHA512 := hmac.New(sha512.New, []byte("test-data"))
writers := io.MultiWriter(md5Hash, sha1Hash, sha256Hash, sha1Hash, hmacSHA256, hamcSHA512)
r := strings.NewReader(`{ "a":"b" }`)
tee := io.TeeReader(r, writers)
data, err := io.ReadAll(tee)
if err != nil {
log.Fatal(err)
}
log.Printf("data:%s", data)
log.Printf("md5 hash data value:%s", hex.EncodeToString(md5Hash.Sum(nil)))
log.Printf("sha1 hash data value:%s", hex.EncodeToString(sha1Hash.Sum(nil)))
log.Printf("sha256 hash data value:%s", hex.EncodeToString(sha256Hash.Sum(nil)))
log.Printf("sha512 hash data value:%s", hex.EncodeToString(sha512Hash.Sum(nil)))
log.Printf("hmacSHA256 hash data value:%s", hex.EncodeToString(hmacSHA256.Sum(nil)))
log.Printf("hamcSHA512 hash data value:%s", hex.EncodeToString(hamcSHA512.Sum(nil)))
}
输出为:
2022/11/27 13:18:31 data:{ "a":"b" }
2022/11/27 13:18:31 md5 hash data value:41bbddfdf95b1df3b0d969c9b4e07969
2022/11/27 13:18:31 sha1 hash data value:c0f0ba3863f94e59c6b23534034ce7c3f9d8a7b8
2022/11/27 13:18:31 sha256 hash data value:f0e41e75ada09f87a59cd7ddacd66b7b8ef311fa415f753a40aeaef222046502
2022/11/27 13:18:31 sha512 hash data value:cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e
2022/11/27 13:18:31 hmacSHA256 hash data value:8de00b01588e01c71f8dedf007b51bf26a9bba3328dfaafebbaca94d19a01c6e
2022/11/27 13:18:31 hamcSHA512 hash data value:27e6a45f2e23e9c8a5326113f64c8aff76fb431c2b455f8a56de347b5af687012ea312cf42bcc141e3a03dd840ad2dc579678d2dc28fb09b896d64196dfa556a