time.now().unixnano
这是用的最多的,但是,也是安全隐患最大的方法。
从表面上看go的时间方法最大精度到纳秒,但是好像其实并不能到达的绝对的纳秒精度。
测试结果很不好,碰撞很高。
import "time" func testseednanotime(t *testing.t) { var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { seed := time.now().unixnano() seeds[seed] = true fmt.println(seed) } fmt.println(len(seeds)) }
maphash.hash
此方法无碰撞
import "hash/maphash" func testseedmaphash(t *testing.t) { var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { seed := int64(new(maphash.hash).sum64()) seeds[seed] = true fmt.println(seed) } fmt.println(len(seeds)) }
cryptorand.read
该方法无碰撞
import ( cryptorand "crypto/rand" mathrand "math/rand" ) func testseedcryptorand(t *testing.t) { var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { var b [8]byte _, err := cryptorand.read(b[:]) if err != nil { panic("cannot seed math/rand package with cryptographically secure random number generator") } seed := int64(binary.littleendian.uint64(b[:])) seeds[seed] = true fmt.println(seed) } fmt.println(len(seeds)) }
映射表
该方法无碰撞
func testseedrandomstring(t *testing.t) { const alpha = "abcdefghijkmnpqrstuvwxyzabcdefghjklmnpqrstuvwxyz23456789" size := 8 var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { buf := make([]byte, size) for i := 0; i < size; i++ { buf[i] = alpha[mathrand.intn(len(alpha))] } seed := int64(binary.littleendian.uint64(buf[:])) seeds[seed] = true fmt.println(seed) } fmt.println(len(seeds)) }
参考资料
how to properly seed random number generator
到此这篇关于详解如何在go语言中生成随机种子的文章就介绍到这了,更多相关go生成随机种子内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论