mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-09 21:43:40 +00:00
d94f42f6e2
This package provides access to an operating system resource
(cryptographic numbers) and so needs to be replaced with a TinyGo
version that does this in a different way.
I've made the following choices while adding this feature:
- I'm using the getentropy call whenever possible (most POSIX like
systems), because it is easier to use and more reliable. Linux is
the exception: it only added getentropy relatively recently.
- I've left bare-metal implementations to a future patch. This because
it's hard to reliably get cryptographically secure random numbers on
embedded devices: most devices do not have a hardware PRNG for this
purpose.
39 lines
761 B
Go
39 lines
761 B
Go
// +build darwin freebsd wasi
|
|
|
|
// This implementation of crypto/rand uses the getentropy system call (available
|
|
// on both MacOS and WASI) to generate random numbers.
|
|
|
|
package rand
|
|
|
|
import (
|
|
"errors"
|
|
"unsafe"
|
|
)
|
|
|
|
var errReadFailed = errors.New("rand: could not read random bytes")
|
|
|
|
func init() {
|
|
Reader = &reader{}
|
|
}
|
|
|
|
type reader struct {
|
|
}
|
|
|
|
func (r *reader) Read(b []byte) (n int, err error) {
|
|
if len(b) != 0 {
|
|
if len(b) > 256 {
|
|
b = b[:256]
|
|
}
|
|
result := libc_getentropy(unsafe.Pointer(&b[0]), len(b))
|
|
if result < 0 {
|
|
// Maybe we should return a syscall.Errno here?
|
|
return 0, errReadFailed
|
|
}
|
|
}
|
|
return len(b), nil
|
|
}
|
|
|
|
// int getentropy(void *buf, size_t buflen);
|
|
//export getentropy
|
|
func libc_getentropy(buf unsafe.Pointer, buflen int) int
|