Random Generators

Overview

This page contains recommendations for generating random values.

General

  • Use only cryptographically strong random generators to produce random values, see the Cryptographically strong random generators section.

  • Do not use standard pseudo-random number generators, such as those used in mathematics to generate pseudo-random numbers.

Clarification

Standard pseudo-random number generators can not withstand cryptographic attacks because such generators are based on functions that produce predictable values.

  • Make sure the seed that is used to initialize a generator has enough entropy.

  • Periodically reinitialize seeds.

Cryptographically strong random generators

Use the crypto/rand package to generate cryptographically strong random values in Go.

import "crypto/rand"

func GetRandomBytes(length int) ([]byte, error) {
    r := make([]byte, length)
    if _, err := rand.Read(r); err != nil {
        return nil, err
    }
    return r, nil
}

func GetRandomString(length int) (string, error) {
    const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    r := make([]byte, length)
    for i := 0; i < length; i++ {
        num, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))
        if err != nil {
            return "", err
        }
        r[i] = alphabet[num.Int64()]
    }
    return string(ret), nil
}

Last updated