Debian Codegraph @

src/crypto/internal/rand/rand.go

raw
1 // Copyright 2025 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 rand
6
7 import (
8 "crypto/internal/boring"
9 "crypto/internal/fips140/drbg"
10 "crypto/internal/randutil"
11 "internal/godebug"
12 "io"
13 _ "unsafe"
14 )
15
16 type reader struct {
17 drbg.DefaultReader
18 }
19
20 func (r reader) Read(b []byte) (n int, err error) {
21 if boring.Enabled {
22 if _, err := boring.RandReader.Read(b); err != nil {
23 panic("crypto/rand: boring RandReader failed: " + err.Error())
24 }
25 return len(b), nil
26 }
27 drbg.Read(b)
28 return len(b), nil
29 }
30
31 // Reader is an io.Reader that calls [drbg.Read].
32 //
33 // It should be used internally instead of [crypto/rand.Reader], because the
34 // latter can be set by applications outside of tests. These applications then
35 // risk breaking between Go releases, if the way the Reader is used changes.
36 var Reader io.Reader = reader{}
37
38 // SetTestingReader overrides all calls to [drbg.Read]. The Read method of
39 // r must never return an error or return short.
40 //
41 // SetTestingReader panics when building against Go Cryptographic Module v1.0.0.
42 //
43 // SetTestingReader is pulled by [testing/cryptotest.setGlobalRandom] via go:linkname.
44 //
45 //go:linkname SetTestingReader crypto/internal/rand.SetTestingReader
46 func SetTestingReader(r io.Reader) {
47 fips140SetTestingReader(r)
48 }
49
50 var cryptocustomrand = godebug.New("cryptocustomrand")
51
52 // CustomReader returns [Reader] or, only if the GODEBUG setting
53 // "cryptocustomrand=1" is set, the provided io.Reader.
54 //
55 // If returning a non-default Reader, it calls [randutil.MaybeReadByte] on it.
56 func CustomReader(r io.Reader) io.Reader {
57 if cryptocustomrand.Value() == "1" {
58 if !IsDefaultReader(r) {
59 randutil.MaybeReadByte(r)
60 cryptocustomrand.IncNonDefault()
61 }
62 return r
63 }
64 return Reader
65 }
66
67 // IsDefaultReader reports whether r is the default [crypto/rand.Reader].
68 //
69 // If true, the Read method of r can be assumed to call [drbg.Read].
70 func IsDefaultReader(r io.Reader) bool {
71 _, ok := r.(drbg.DefaultReader)
72 return ok
73 }