如何使用安全随机数创建大整数

Mat*_*iro 5 go amadeus

我在 java 中有这段代码,我需要在 Go 中重现。

String nonce = new BigInteger(130, new SecureRandom()).toString(32);
Run Code Online (Sandbox Code Playgroud)

是为 GDS amadeussoap 标头 4 生成随机数的唯一方法。

谢谢

put*_*utu 9

使用包math/bigcrypto/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)
Run Code Online (Sandbox Code Playgroud)

可以在The Go Playground找到一个工作示例。