1
0
mirror of https://github.com/golang/go synced 2024-11-26 04:07:59 -07:00

[dev.boringcrypto] crypto/rand: use BoringCrypto

Change-Id: Ie630eff90f7fee9b359683930aec2daf96c1bdfe
Reviewed-on: https://go-review.googlesource.com/55473
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Adam Langley <agl@golang.org>
This commit is contained in:
Russ Cox 2017-08-02 23:25:07 -04:00
parent 6e70f88f84
commit fe02ba30f1
4 changed files with 44 additions and 0 deletions

View File

@ -37,3 +37,7 @@ func UnreachableExceptTests() {
panic("boringcrypto: invalid code execution")
}
}
type fail string
func (e fail) Error() string { return "boringcrypto: " + string(e) + " failed" }

View File

@ -15,3 +15,11 @@ func Unreachable() {}
// UnreachableExceptTests marks code that should be unreachable
// when BoringCrypto is in use. It is a no-op without BoringCrypto.
func UnreachableExceptTests() {}
type randReader int
func (randReader) Read(b []byte) (int, error) {
panic("boringcrypto: not available")
}
const RandReader = randReader(0)

View File

@ -0,0 +1,25 @@
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux,amd64
// +build !cmd_go_bootstrap
package boring
// #include "goboringcrypto.h"
import "C"
import "unsafe"
type randReader int
func (randReader) Read(b []byte) (int, error) {
// Note: RAND_bytes should never fail; the return value exists only for historical reasons.
// We check it even so.
if len(b) > 0 && C._goboringcrypto_RAND_bytes((*C.uint8_t)(unsafe.Pointer(&b[0])), C.size_t(len(b))) == 0 {
return 0, fail("RAND_bytes")
}
return len(b), nil
}
const RandReader = randReader(0)

View File

@ -13,6 +13,7 @@ import (
"bufio"
"crypto/aes"
"crypto/cipher"
"crypto/internal/boring"
"io"
"os"
"runtime"
@ -26,6 +27,10 @@ const urandomDevice = "/dev/urandom"
// This is sufficient on Linux, OS X, and FreeBSD.
func init() {
if boring.Enabled {
Reader = boring.RandReader
return
}
if runtime.GOOS == "plan9" {
Reader = newReader(nil)
} else {
@ -45,6 +50,7 @@ type devReader struct {
var altGetRandom func([]byte) (ok bool)
func (r *devReader) Read(b []byte) (n int, err error) {
boring.Unreachable()
if altGetRandom != nil && r.name == urandomDevice && altGetRandom(b) {
return len(b), nil
}
@ -108,6 +114,7 @@ type reader struct {
}
func (r *reader) Read(b []byte) (n int, err error) {
boring.Unreachable()
r.mu.Lock()
defer r.mu.Unlock()
n = len(b)