寫項目時,有時我們需要緩存, 緩存就會需要唯一的key. 常規(guī)是對字符串求md5指紋. 在golang里我們也可以使用, 目前可以計算一個字符串的crc32, md5, sha1的指紋.
md5 : 一種被廣泛使用的密碼散列函數(shù),可以產(chǎn)bai生出一個128位(du16字節(jié))的散列值(hash value),用于確保信息傳輸完整一zhi致。MD5由美國密碼學(xué)家羅納德·李維斯特(Ronald Linn Rivest)設(shè)計,于1992年公開,用以取代MD4算法。
sha1: SHA1是由NISTNSA設(shè)計為同DSA一起使用的,它對長度小于264的輸入,產(chǎn)生長度為160bit的散列值,因此抗窮舉(brute-force)性更好。SHA-1基于MD5,MD5又基于MD4。
crc32: 本身是“冗余校驗碼”的意思,CRC32則表示會產(chǎn)生一個32bit(8位十六進(jìn)制數(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 字符串指紋的詳細(xì)內(nèi)容,更多關(guān)于Go 字符串指紋的資料請關(guān)注腳本之家其它相關(guān)文章!
標(biāo)簽:廣西 阿克蘇 調(diào)研邀請 慶陽 西雙版納 德州 貴陽 太原
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《淺析Go 字符串指紋》,本文關(guān)鍵詞 淺析,字符串,指紋,淺析,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。