randutil.go 927 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. // Package randutil contains internal randomness utilities for various
  5. // crypto packages.
  6. package randutil
  7. import (
  8. "io"
  9. "sync"
  10. )
  11. var (
  12. closedChanOnce sync.Once
  13. closedChan chan struct{}
  14. )
  15. // MaybeReadByte reads a single byte from r with ~50% probability. This is used
  16. // to ensure that callers do not depend on non-guaranteed behaviour, e.g.
  17. // assuming that rsa.GenerateKey is deterministic w.r.t. a given random stream.
  18. //
  19. // This does not affect tests that pass a stream of fixed bytes as the random
  20. // source (e.g. a zeroReader).
  21. func MaybeReadByte(r io.Reader) {
  22. closedChanOnce.Do(func() {
  23. closedChan = make(chan struct{})
  24. close(closedChan)
  25. })
  26. select {
  27. case <-closedChan:
  28. return
  29. case <-closedChan:
  30. var buf [1]byte
  31. r.Read(buf[:])
  32. }
  33. }