golang 生成MD5、SHA256摘要
golang生成常用摘要字符串比较简单,简单总结下用的比较多的两种。
method-1
func GenerateMd5(str string) string {
// method_1, cannot reset
hash := md5.Sum([]byte(str))
return fmt.Sprintf("%x", hash)
}
method-2
func GenerateMd5(str string) string {
// method_2, can reset, call hash.Reset()
hash := md5.New()
hash.Write([]byte(str))
hashed := hash.Sum(nil)
// return fmt.Sprintf("%x", hashed)
return hex.EncodeToString(hashed)
}
两种方法都可以,法一,只能用一次,但代码少,法二可以重复用,代码相对多些,SHA256和MD5差不多,下面给出可以reset的sha256代码:
func GenerateSHA256(str string) string {
hash := sha256.New()
hash.Write([]byte(str))
hashed := hash.Sum(nil)
return hex.EncodeToString(hashed)
}