淺析Go 字符串指紋
寫項目時,有時我們需要緩存, 緩存就會需要唯一的key. 常規(guī)是對字符串求md5指紋. 在golang里我們也可以使用, 目前可以計算一個字符串的crc32, md5, sha1的指紋.
md5 : 一種被廣泛使用的密碼散列函數(shù),可以產(chǎn)bai生出一個128位(du16字節(jié))的散列值(hash value),用于確保信息傳輸完整一zhi致。MD5由美國密碼學家羅納德·李維斯特(Ronald Linn Rivest)設計,于1992年公開,用以取代MD4算法。
sha1: SHA1是由NISTNSA設計為同DSA一起使用的,它對長度小于264的輸入,產(chǎn)生長度為160bit的散列值,因此抗窮舉(brute-force)性更好。SHA-1基于MD5,MD5又基于MD4。
crc32: 本身是“冗余校驗碼”的意思,CRC32則表示會產(chǎn)生一個32bit(8位十六進制數(shù))的校驗值。由于CRC32產(chǎn)生校驗值時源數(shù)據(jù)塊的每一個bit(位)都參與了計算,所以數(shù)據(jù)塊中即使只有一位發(fā)生了變化,也會得到不同的CRC32值。
golang 實現(xiàn)
md5
// md5值 func Md5Str(s string) string { hash := md5.Sum([]byte(s)) return hex.EncodeToString(hash[:]) }
sha1
// 散列值 func Sha1Str(s string) string { r := sha1.Sum([]byte(s)) return hex.EncodeToString(r[:]) }
crc32
// String hashes a string to a unique hashcode. // https://github.com/hashicorp/terraform/blob/master/helper/hashcode/hashcode.go // crc32 returns a uint32, but for our use we need // and non negative integer. Here we cast to an integer // and invert it if the result is negative. func HashCode(s string) int { v := int(crc32.ChecksumIEEE([]byte(s))) if v >= 0 { return v } if -v >= 0 { return -v } // v == MinInt return 0 } // Strings hashes a list of strings to a unique hashcode. func HashCodes(strings []string) string { var buf bytes.Buffer for _, s := range strings { buf.WriteString(fmt.Sprintf("%s-", s)) } return fmt.Sprintf("%d", HashCode(buf.String())) }
使用
func main() { // 2713056744 // 1f8689c0dd07ce42757ac01b1ea714f9 // 9addcbc6fee9c06f43d7110b657f3c61ff707032 txt := "https://github.com/hashicorp/terraform/blob/master/helper/hashcode/hashcode.go" fmt.Println(HashCode(txt)) fmt.Println(Md5Str(txt)) fmt.Println(Sha1Str(txt)) }
效率
得出效率: hash_code > md5 > sha1
const ( Txt = "https://github.com/hashicorp/terraform/blob/master/helper/hashcode/hashcode.go" ) // go test -test.bench=. -test.benchmem func BenchmarkMd5Str(b *testing.B) { for i := 0; i < b.N; i++ { Md5Str(Txt) } } func BenchmarkHashCode(b *testing.B) { for i := 0; i < b.N; i++ { HashCode(Txt) } } func BenchmarkSha1Str(b *testing.B) { for i := 0; i < b.N; i++ { Sha1Str(Txt) } } // BenchmarkMd5Str-8 2148428 518 ns/op 144 B/op 3 allocs/op // BenchmarkHashCode-8 8105571 160 ns/op 80 B/op 1 allocs/op // BenchmarkSha1Str-8 1836854 700 ns/op 176 B/op 3 allocs/op // 得出效率: hash_code > md5 > sha1
以上就是淺析Go 字符串指紋的詳細內容,更多關于Go 字符串指紋的資料請關注腳本之家其它相關文章!
相關文章
Golang 使用Map實現(xiàn)去重與set的功能操作
這篇文章主要介紹了Golang 使用 Map 實現(xiàn)去重與 set 的功能操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04在go文件服務器加入http.StripPrefix的用途介紹
這篇文章主要介紹了在go文件服務器加入http.StripPrefix的用途介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12GOPROXY:解決go get golang.org/x包失敗問題
這篇文章主要介紹了GOPROXY:解決go get golang.org/x包失敗問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01golang解析網(wǎng)頁利器goquery的使用方法
這篇文章主要給大家介紹了關于golang解析網(wǎng)頁利器goquery的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考借鑒,下面來一起學習學習吧。2017-09-09