3

I want to generate 64-bit random integer using the secure crypto/rand package. I found this online:

package main import ( "crypto/rand" "encoding/base64" ) // GenerateRandomBytes returns securely generated random bytes. // It will return an error if the system's secure random // number generator fails to function correctly, in which // case the caller should not continue. func GenerateRandomBytes(n int) ([]byte, error) { b := make([]byte, n) _, err := rand.Read(b) // Note that err == nil only if we read len(b) bytes. if err != nil { return nil, err } return b, nil } 

But it seems to generate random bytes instead. I want a random 64-bit int. Namely, I want something like var i uint64 = rand(). Any ideas how to achieve this?

3
  • You can't figure out how to convert 8 random bytes into a random 64-bit integer? Commented Jun 11, 2017 at 10:30
  • Possible duplicate of How do you generate a random uint64 in Go? Commented Jun 11, 2017 at 11:07
  • 2
    Not a duplicate, @icza. He wants to use cryptographic randomness. Commented Jun 11, 2017 at 11:34

2 Answers 2

3

You can generate a random number with crypto.Rand, and then convert those bytes to an int64 using the binary package:

func randint64() (int64, error) { var b [8]byte if _, err := rand.Read(b[:]); err != nil { return 0, err } return int64(binary.LittleEndian.Uint64(b[:])), nil } 

https://play.golang.org/p/2Q8tvttqbJ (result is cached)

If you look at the source code for LittleEndian.Uint64, you can see it's simply performing a few bit operations on the data; something that you could implemented for yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Didn't know for the binary encoding package.
2

You also use rand.Int in crypto/rand package

func randint64() (int64, error) { val, err := rand.Int(rand.Reader, big.NewInt(int64(math.MaxInt64))) if err != nil { return 0, err } return val.Int64(), nil } 

https://play.golang.org/p/fqoQxpmjOSu

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.