aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSean Liao <sean@liao.dev>2025-04-13 17:48:48 +0100
committerSean Liao <sean@liao.dev>2025-04-16 16:10:00 -0700
commit3cefe69c5a5ad687f220696d4f8a2fe4d59241dd (patch)
treef21981c6e8a44c1ecbc1451137a3a18ea9e4ae2f /src
parentae5a5132eb105e712799be4717929d55d75a04b2 (diff)
downloadgo-3cefe69c5a5ad687f220696d4f8a2fe4d59241dd.tar.xz
crypto/rand: add and update examples
Change-Id: I77406c22b82c9f8bc57323c783f63c4897486e7e Reviewed-on: https://go-review.googlesource.com/c/go/+/665096 Reviewed-by: Daniel McCarney <daniel@binaryparadox.net> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Dmitri Shuralyov <dmitshur@google.com> Reviewed-by: Roland Shoemaker <roland@golang.org>
Diffstat (limited to 'src')
-rw-r--r--src/crypto/rand/example_test.go24
1 files changed, 19 insertions, 5 deletions
diff --git a/src/crypto/rand/example_test.go b/src/crypto/rand/example_test.go
index 64e38b11ce..cc074cceec 100644
--- a/src/crypto/rand/example_test.go
+++ b/src/crypto/rand/example_test.go
@@ -12,16 +12,30 @@ import (
// ExampleInt prints a single cryptographically secure pseudorandom number between 0 and 99 inclusive.
func ExampleInt() {
- a, err := rand.Int(rand.Reader, big.NewInt(100))
- if err != nil {
- fmt.Println("error:", err)
- return
- }
+ // Int cannot return an error when using rand.Reader.
+ a, _ := rand.Int(rand.Reader, big.NewInt(100))
fmt.Println(a.Int64())
}
+// ExamplePrime prints a cryptographically secure pseudorandom 64 bit prime number.
+func ExamplePrime() {
+ // Prime cannot return an error when using rand.Reader and bits >= 2.
+ a, _ := rand.Prime(rand.Reader, 64)
+ fmt.Println(a.Int64())
+}
+
+// ExampleRead prints a cryptographically secure pseudorandom 32 byte key.
func ExampleRead() {
// Note that no error handling is necessary, as Read always succeeds.
key := make([]byte, 32)
rand.Read(key)
+ // The key can contain any byte value, print the key in hex.
+ fmt.Printf("% x\n", key)
+}
+
+// ExampleText prints a random key encoded in base32.
+func ExampleText() {
+ key := rand.Text()
+ // The key is base32 and safe to display.
+ fmt.Println(key)
}