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
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
Use package math/big
and crypto/rand
. The snippet looks like:
//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)
A working example can be found at The Go Playground.
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)