diff --git a/src/crypto/rand/rand_arc4random.go b/src/crypto/rand/rand_arc4random.go new file mode 100644 index 00000000..cbc76af9 --- /dev/null +++ b/src/crypto/rand/rand_arc4random.go @@ -0,0 +1,30 @@ +// +build darwin freebsd tinygo.wasm + +// This implementation of crypto/rand uses the arc4random_buf function +// (available on both MacOS and WASI) to generate random numbers. +// +// Note: arc4random_buf (unlike what the name suggets) does not use the insecure +// RC4 cipher. Instead, it uses a high-quality cipher, varying by the libc +// implementation. + +package rand + +import "unsafe" + +func init() { + Reader = &reader{} +} + +type reader struct { +} + +func (r *reader) Read(b []byte) (n int, err error) { + if len(b) != 0 { + libc_arc4random_buf(unsafe.Pointer(&b[0]), uint(len(b))) + } + return len(b), nil +} + +// void arc4random_buf(void *buf, size_t buflen); +//export arc4random_buf +func libc_arc4random_buf(buf unsafe.Pointer, buflen uint) diff --git a/src/crypto/rand/rand_getentropy.go b/src/crypto/rand/rand_getentropy.go deleted file mode 100644 index 4cd03795..00000000 --- a/src/crypto/rand/rand_getentropy.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build darwin freebsd tinygo.wasm - -// 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