寫項目時,有時我們需要緩存, 緩存就會需要唯一的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 字符串指紋的詳細內(nèi)容,更多關于Go 字符串指紋的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- Golang中的Unicode與字符串示例詳解
- 讓Django的BooleanField支持字符串形式的輸入方式
- go浮點數(shù)轉(zhuǎn)字符串保留小數(shù)點后N位的完美解決方法
- Go 驗證字符串中是否包含中文(推薦)
- Golang中生成隨機字符串并復制到粘貼板的方法
- 分享6個Go處理字符串的技巧小結(jié)
- Go 高效截取字符串的一些思考
- Go 結(jié)構(gòu)體、數(shù)組、字典和 json 字符串的相互轉(zhuǎn)換方法
- 簡單談談Golang中的字符串與字節(jié)數(shù)組
- Go語言中的字符串處理方法示例詳解
- Golang字符串的拼接方法匯總
- Golang 中整數(shù)轉(zhuǎn)字符串的方法