securerand

package module
v0.0.0-...-1cef830 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2021 License: Apache-2.0 Imports: 4 Imported by: 0

README

SecureRand

This project provides a simple wrapper around Go's crypto/rand to provide a nearly drop-in replacement of math/rand calls. See godoc.org for API usage.

Documentation

Overview

Package securerand provides a simple wrapper around crypto/rand calls in order to provide a nearly drop-in replacement for rand.Rand uses. Note that this can cause runtime panics if you try to seed it or if crypto cannot get values (due to, e.g., /dev/urandom not being readable).

Example

This simple example shows how you might create a random number generator that could be used exactly the same as if you'd simply imported "math/rand". This also shows that seeding is a bad idea.

package main

import (
	"fmt"

	"github.com/Nerdmaster/securerand"
)

func main() {
	var rand = securerand.New()

	defer func() {
		var rec = recover()
		if rec == nil {
			fmt.Println("Seed() should have panicked, but didn't!")
		}

		fmt.Println("Panic message: " + rec.(string))
	}()

	// Roll a die as if we'd imported math/rand
	var _ = rand.Intn(6) + 1
	fmt.Println("Rolled die successfully")

	rand.Seed(1)
}
Output:

Rolled die successfully
Panic message: securerand.Source cannot be seeded

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New() *rand.Rand

New returns a cryptographically secure PRNG that can be used as a *nearly* drop-in replacement for any other rand.Rand usage.

Note that this **cannot** be seeded. Seed() will panic if called. Cryptographically secure PRNGs by their nature must not produce predictable sequences. If you need a predictable sequence, you don't understand what "cryptographically secure" means.

Types

type Source

type Source struct{}

Source is a cryptographically secure random number source. It holds no internal state, as the rand.Source implementation merely calls crypto/rand methods, and seeding is unused.

func (Source) Int63

func (s Source) Int63() int64

Int63 implements rand.Source, returning a cryptographically secure number from 0 to 1<<63

func (Source) Seed

func (s Source) Seed(seed int64)

Seed implements rand.Source, but panics if called, as cryptographically secure randomness obviously can't be seeded

func (Source) Uint64

func (s Source) Uint64() uint64

Uint64 implements rand.Source64

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL