詳解如何在Go語言中生成隨機種子
更新時間:2024年04月28日 08:22:01 作者:喵個咪
這篇文章主要為大家詳細介紹了如何在Go語言中生成隨機種子,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考一下
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生成隨機種子內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Go語言MySQLCURD數(shù)據(jù)庫操作示例詳解
這篇文章主要為大家介紹了Go語言MySQLCURD數(shù)據(jù)庫操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12Go語言實現(xiàn)類似c++中的多態(tài)功能實例
Go本身不具有多態(tài)的特性,不能夠像Java、C++那樣編寫多態(tài)類、多態(tài)方法。但是,使用Go可以編寫具有多態(tài)功能的類綁定的方法。下面來一起看看吧2016-09-09