seed - Quickly Seed Go's Random Number Generator

Boiler-plate to securely seed Go's random number generator (if possible). This library isn't anything fancy, it's just a canonical way of seeding Go's random number generator. Cribbed from Nomad before it was moved into Consul and made into a helper function, and now further modularized to be a super lightweight and reusable library.

Time is better than Go's default seed of 1, but friends don't let friends use time as a seed to a random number generator. Use seed.MustInit() instead.

seed.Init() is an idempotent and reentrant call that will return an error if it can't seed the value the first time it is called. Init() is reentrant.

seed.MustInit() is idempotent and reentrant call that will panic() if it can't seed the value the first time it is called. MustInit() is reentrant.


package mypackage

import (

// MustInit will panic() if it is unable to set a high-entropy random seed:
func init() {

// Or if you want to not panic() and can actually handle this error:
func init() {
  if secure, err := !seed.Init(); !secure {
    // Handle the error
    //panic(fmt.Sprintf("Unable to securely seed Go's RNG: %v", err))
Expand ▾ Collapse ▴




This section is empty.


This section is empty.


func Init

func Init() (seededSecurely bool, err error)

    Init provides best-effort seeding (which is better than running with Go's default seed of 1). If `/dev/urandom` is available, Init() will seed Go's runtime with entropy from `/dev/urandom` and return true because the runtime was securely seeded. If Init() has already initialized the random number or it had failed to securely initialize the random number generation, Init() will return false. See MustInit().

    func MustInit

    func MustInit()

      MustInit provides guaranteed secure seeding. If `/dev/urandom` is not available, MustInit will panic() with an error indicating why reading from `/dev/urandom` failed. MustInit() will upgrade the seed if for some reason a call to Init() failed in the past.

      func Secure

      func Secure() bool

        Secure returns true if a cryptographically secure seed was used to initialize rand.

        func Seeded

        func Seeded() bool

          Seeded returns true if Init has seeded the random number generator.


          This section is empty.

          Source Files