10

User-friendly access to crypto/rand

 3 years ago
source link: https://yourbasic.org/golang/crypto-rand-int/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

User-friendly access to crypto/rand

yourbasic.org/golang
Masked programmer

Go has two packages for random numbers:

  • math/rand implements a large selection of pseudo-random number generators.
  • crypto/rand implements a cryptographically secure pseudo-random number generator with a limited interface.

The two packages can be combined by calling rand.New in package math/rand with a source that gets its data from crypto/rand.

import (
    crand "crypto/rand"
    rand "math/rand"

    "encoding/binary"
    "fmt"
    "log"
)

func main() {
    var src cryptoSource
    rnd := rand.New(src)
    fmt.Println(rnd.Intn(1000)) // a truly random number 0 to 999
}

type cryptoSource struct{}

func (s cryptoSource) Seed(seed int64) {}

func (s cryptoSource) Int63() int64 {
    return int64(s.Uint64() & ^uint64(1<<63))
}

func (s cryptoSource) Uint64() (v uint64) {
    err := binary.Read(crand.Reader, binary.BigEndian, &v)
    if err != nil {
        log.Fatal(err)
    }
    return v
}

Warning: The crand.Reader returns an error if the underlying system call fails. For instance if it can't read /dev/urandom on a Unix system, or if CryptAcquireContext fails on a Windows system.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK