github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/crypto_hash.go (about) 1 package f 2 3 import ( 4 "crypto" 5 "crypto/hmac" 6 "encoding/hex" 7 "fmt" 8 "reflect" 9 ) 10 11 // CryptoMD5 md5 hash. 12 func CryptoMD5(origData string) string { 13 s := crypto.MD5.New() 14 s.Write(Bytes(origData)) 15 return hex.EncodeToString(s.Sum(nil)) 16 } 17 18 // CryptoMD5Key md5 hash key. 19 func CryptoMD5Key(key interface{}) string { 20 digest := crypto.MD5.New() 21 _, _ = fmt.Fprint(digest, reflect.TypeOf(key)) 22 _, _ = fmt.Fprint(digest, key) 23 hash := digest.Sum(nil) 24 return fmt.Sprintf("%x", hash) 25 } 26 27 // CryptoHmac hmac SHA256|SHA384|SHA512 hash. 28 // encryptedBytes, err := CryptoHmac(origData, key, crypto.SHA256, base64.URLEncoding.EncodeToString) 29 // encryptedBytes, err := CryptoHmac(origData, key, crypto.SHA384, EncodeBase64RawURL) 30 // encryptedBytes, err := CryptoHmac(origData, key, crypto.SHA512, EncodeBase64URL) 31 func CryptoHmac(origData, key string, hash crypto.Hash, encode func(src []byte) string) string { 32 h := hmac.New(hash.New, Bytes(key)) 33 _, err := h.Write(Bytes(origData)) 34 if err == nil { 35 if encode == nil { 36 encode = EncodeBase64RawURL 37 } 38 return encode(h.Sum(nil)) 39 } 40 return "" 41 }