1. 程式人生 > 程式設計 >淺析Go 字串指紋

淺析Go 字串指紋

寫專案時,有時我們需要快取,快取就會需要唯一的key. 常規是對字串求md5指紋. 在golang裡我們也可以使用,目前可以計算一個字串的crc32,md5,sha1的指紋.

md5 : 一種被廣泛使用的密碼雜湊函式,可以產bai生出一個128位(du16位元組)的雜湊值(hash value),用於確保資訊傳輸完整一zhi致。MD5由美國密碼學家羅納德·李維斯特(Ronald Linn Rivest)設計,於1992年公開,用以取代MD4演算法。

sha1: SHA1是由NISTNSA設計為同DSA一起使用的,它對長度小於264的輸入,產生長度為160bit的雜湊值,因此抗窮舉(brute-force)性更好。SHA-1基於MD5,MD5又基於MD4。

crc32: 本身是“冗餘校驗碼”的意思,CRC32則表示會產生一個32bit(8位十六進位制數)的校驗值。由於CRC32產生校驗值時源資料塊的每一個bit(位)都參與了計算,所以資料塊中即使只有一位發生了變化,也會得到不同的CRC32值。

golang 實現

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 字串指紋的資料請關注我們其它相關文章!