github.com/decred/politeia@v1.4.0/util/random.go (about)

     1  // Copyright (c) 2017-2019 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"crypto/rand"
     9  	"encoding/binary"
    10  	"io"
    11  )
    12  
    13  // Random returns a variable number of bytes of random data.
    14  func Random(n int) ([]byte, error) {
    15  	k := make([]byte, n)
    16  	_, err := io.ReadFull(rand.Reader, k)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  
    21  	return k, nil
    22  }
    23  
    24  // RandomInt returns a random unsigned integer.
    25  func RandomUint64() (uint64, error) {
    26  	k, err := Random(8)
    27  	if err != nil {
    28  		return 0xffffffffffffffff, err
    29  	}
    30  	return binary.LittleEndian.Uint64(k), nil
    31  }