@@ -112,28 +112,24 @@ pointer type, `*T`.
112
112
113
113
## Crypto Rand
114
114
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
+
119
124
120
125
` ` ` go
121
126
import (
122
127
" crypto/rand"
123
- // "encoding/base64"
124
- // "encoding/hex"
125
128
" fmt"
126
129
)
127
130
128
131
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 ()
137
133
}
138
134
` ` `
139
135
0 commit comments