种子与随机数生成器的时间替代方案



在Go中,对于随机数生成器的种子,可以使用什么值作为当前时间
的替代值?

当我跟随围棋之旅
时,我想到了这个简单的问题,他们说他们沙箱环境中的当前时间是固定的。

您可以使用crypto.rand包读取一些随机字节,并将其转换为int64:

import (
"crypto/rand"
"encoding/binary"
)
...
b:=make([]byte,8)
rand.Read(b)
seed:=binary.BigEndian.Uint64(b)

如果您想在没有确定性PRNG的情况下访问math/rand便利函数,您可以自己创建一个新的安全rand.Source

type cryptoSource [8]byte
func (s *cryptoSource) Int63() int64 {
const mask = (1 << 63) - 1
crand.Read(s[:])
i := int64(binary.BigEndian.Uint64(s[:]))
return i & mask
}
func (cryptoSource) Seed(int64) {}

https://play.golang.org/p/sD4fOkE8LeD

相关内容

最新更新