Source file src/crypto/rand/example_test.go

     1  // Copyright 2011 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_test
     6  
     7  import (
     8  	"crypto/rand"
     9  	"fmt"
    10  	"math/big"
    11  )
    12  
    13  // ExampleInt prints a single cryptographically secure pseudorandom number between 0 and 99 inclusive.
    14  func ExampleInt() {
    15  	// Int cannot return an error when using rand.Reader.
    16  	a, _ := rand.Int(rand.Reader, big.NewInt(100))
    17  	fmt.Println(a.Int64())
    18  }
    19  
    20  // ExamplePrime prints a cryptographically secure pseudorandom 64 bit prime number.
    21  func ExamplePrime() {
    22  	// Prime cannot return an error when using rand.Reader and bits >= 2.
    23  	a, _ := rand.Prime(rand.Reader, 64)
    24  	fmt.Println(a.Int64())
    25  }
    26  
    27  // ExampleRead prints a cryptographically secure pseudorandom 32 byte key.
    28  func ExampleRead() {
    29  	// Note that no error handling is necessary, as Read always succeeds.
    30  	key := make([]byte, 32)
    31  	rand.Read(key)
    32  	// The key can contain any byte value, print the key in hex.
    33  	fmt.Printf("% x\n", key)
    34  }
    35  
    36  // ExampleText prints a random key encoded in base32.
    37  func ExampleText() {
    38  	key := rand.Text()
    39  	// The key is base32 and safe to display.
    40  	fmt.Println(key)
    41  }
    42  

View as plain text