crypto/rand: use getrandom system call on Linux

Adds internal/syscall package.

Fixes #8520

LGTM=r, agl
R=agl, rsc, r
CC=golang-codereviews, iant
https://golang.org/cl/123260044
This commit is contained in:
Brad Fitzpatrick 2014-08-12 14:35:27 -07:00
parent 1837419f30
commit 67e1d40031
4 changed files with 105 additions and 2 deletions

View file

@ -20,6 +20,8 @@ import (
"time"
)
const urandomDevice = "/dev/urandom"
// Easy implementation: read from /dev/urandom.
// This is sufficient on Linux, OS X, and FreeBSD.
@ -27,7 +29,7 @@ func init() {
if runtime.GOOS == "plan9" {
Reader = newReader(nil)
} else {
Reader = &devReader{name: "/dev/urandom"}
Reader = &devReader{name: urandomDevice}
}
}
@ -38,7 +40,14 @@ type devReader struct {
mu sync.Mutex
}
// altGetRandom if non-nil specifies an OS-specific function to get
// urandom-style randomness.
var altGetRandom func([]byte) (ok bool)
func (r *devReader) Read(b []byte) (n int, err error) {
if altGetRandom != nil && r.name == urandomDevice && altGetRandom(b) {
return len(b), nil
}
r.mu.Lock()
defer r.mu.Unlock()
if r.f == nil {