5

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Matías Sueiro
  • 103
  • 1
  • 7

2 Answers2

8

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.

putu
  • 6,218
  • 1
  • 21
  • 30
1

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)
Fethbita
  • 49
  • 1
  • 8