如何使用安全随机数创建一个大整数
How to create a big int with a secure random
我在 java 中有这段代码,我需要在 Go 中重现。
String nonce = new BigInteger(130, new SecureRandom()).toString(32);
是为 GDS amadeus soap header 4 生成随机数的唯一方法。
谢谢
使用包 math/big
and crypto/rand
。该代码段如下所示:
//Max random value, a 130-bits integer, i.e 2^130 - 1
max := new(big.Int)
max.Exp(big.NewInt(2), big.NewInt(130), nil).Sub(max, big.NewInt(1))
//Generate cryptographically strong pseudo-random between 0 - max
n, err := rand.Int(rand.Reader, max)
if err != nil {
//error handling
}
//String representation of n in base 32
nonce := n.Text(32)
可以在 The Go Playground 找到一个工作示例。
我在 java 中有这段代码,我需要在 Go 中重现。
String nonce = new BigInteger(130, new SecureRandom()).toString(32);
是为 GDS amadeus soap header 4 生成随机数的唯一方法。
谢谢
使用包 math/big
and crypto/rand
。该代码段如下所示:
//Max random value, a 130-bits integer, i.e 2^130 - 1
max := new(big.Int)
max.Exp(big.NewInt(2), big.NewInt(130), nil).Sub(max, big.NewInt(1))
//Generate cryptographically strong pseudo-random between 0 - max
n, err := rand.Int(rand.Reader, max)
if err != nil {
//error handling
}
//String representation of n in base 32
nonce := n.Text(32)
可以在 The Go Playground 找到一个工作示例。