Skip to content

Commit 8bbed0e

Browse files
seankhliaogopherbot
authored andcommitted
CodeReviewComments: recommend rand.Text for keys
This was added in https://go.dev/issue/67057 expressly for the purpose of generating keys. Change-Id: I5c63e7086649801421bc977e50bf619ed9078439 Reviewed-on: https://go-review.googlesource.com/c/wiki/+/655636 Auto-Submit: Ian Lance Taylor <[email protected]> Commit-Queue: Ian Lance Taylor <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]>
1 parent 81bdd2e commit 8bbed0e

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

CodeReviewComments.md

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -112,28 +112,24 @@ pointer type, `*T`.
112112
113113
## Crypto Rand
114114
115-
Do not use package `math/rand` to generate keys, even throwaway ones.
116-
Unseeded, the generator is completely predictable. Seeded with `time.Nanoseconds()`,
117-
there are just a few bits of entropy. Instead, use `crypto/rand`'s Reader,
118-
and if you need text, print to hexadecimal or base64:
115+
Do not use package [`math/rand`](https://pkg.go.dev/math/rand)
116+
or [`math/rand/v2`](https://pkg.go.dev/math/rand/v2) to generate keys, even throwaway ones.
117+
Seeded with [`Time.Nanoseconds()`](https://pkg.go.dev/time#Time.Nanosecond),
118+
there are just a few bits of entropy.
119+
Instead, use [`crypto/rand.Reader`](https://pkg.go.dev/crypto/rand#pkg-variables).
120+
If you need text, use [`crypto/rand.Text`](https://pkg.go.dev/crypto/rand#Text),
121+
or alternatively, encode random bytes with [`encoding/hex`](https://pkg.go.dev/encoding/hex)
122+
or [`encoding/base64`](https://pkg.go.dev/encoding/base64).
123+
119124
120125
``` go
121126
import (
122127
"crypto/rand"
123-
// "encoding/base64"
124-
// "encoding/hex"
125128
"fmt"
126129
)
127130

128131
func Key() string {
129-
buf := make([]byte, 16)
130-
_, err := rand.Read(buf)
131-
if err != nil {
132-
panic(err) // out of randomness, should never happen
133-
}
134-
return fmt.Sprintf("%x", buf)
135-
// or hex.EncodeToString(buf)
136-
// or base64.StdEncoding.EncodeToString(buf)
132+
return rand.Text()
137133
}
138134
```
139135

0 commit comments

Comments
 (0)