How to create a big int with a secure random

Viewed 3786

I have this code in java and I need to reproduce in Go.

String nonce = new BigInteger(130, new SecureRandom()).toString(32);

Is the only way to generate a nonce for GDS amadeus soap header 4.

Thanks

2 Answers

The accepted answer is wrong because the crypto/rand rand.Int function

returns a uniform random value in [0, max). It panics if max <= 0. Here is an answer that doesn't skip the 2^130 - 1 value.

// Max value, a 130-bits integer, i.e 2^130 - 1
var max *big.Int = big.NewInt(0).Exp(big.NewInt(2), big.NewInt(130), nil)
// Generate cryptographically strong pseudo-random between [0, max)
n, err := rand.Int(rand.Reader, max)
if err != nil {
    // error handling
}
fmt.Println(n)
Related