go

How to create a big int with a secure random


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


Solution

  • 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.