github.com/FISCO-BCOS/crypto@v0.0.0-20200202032121-bd8ab0b5d4f1/internal/randutil/randutil.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package randutil contains internal randomness utilities for various 6 // crypto packages. 7 package randutil 8 9 import ( 10 "io" 11 "sync" 12 ) 13 14 var ( 15 closedChanOnce sync.Once 16 closedChan chan struct{} 17 ) 18 19 // MaybeReadByte reads a single byte from r with ~50% probability. This is used 20 // to ensure that callers do not depend on non-guaranteed behaviour, e.g. 21 // assuming that rsa.GenerateKey is deterministic w.r.t. a given random stream. 22 // 23 // This does not affect tests that pass a stream of fixed bytes as the random 24 // source (e.g. a zeroReader). 25 func MaybeReadByte(r io.Reader) { 26 closedChanOnce.Do(func() { 27 closedChan = make(chan struct{}) 28 close(closedChan) 29 }) 30 31 select { 32 case <-closedChan: 33 return 34 case <-closedChan: 35 var buf [1]byte 36 r.Read(buf[:]) 37 } 38 }