github.com/tickstep/library-go@v0.1.1/crypto/random.go (about)

     1  package crypto
     2  
     3  import (
     4  	crand "crypto/rand"
     5  	"encoding/hex"
     6  	"io"
     7  )
     8  
     9  // This only uses the OS's randomness
    10  func randBytes(numBytes int) []byte {
    11  	b := make([]byte, numBytes)
    12  	_, err := crand.Read(b)
    13  	if err != nil {
    14  		panic(err)
    15  	}
    16  	return b
    17  }
    18  
    19  // This only uses the OS's randomness
    20  func CRandBytes(numBytes int) []byte {
    21  	return randBytes(numBytes)
    22  }
    23  
    24  // CRandHex returns a hex encoded string that's floor(numDigits/2) * 2 long.
    25  //
    26  // Note: CRandHex(24) gives 96 bits of randomness that
    27  // are usually strong enough for most purposes.
    28  func CRandHex(numDigits int) string {
    29  	return hex.EncodeToString(CRandBytes(numDigits / 2))
    30  }
    31  
    32  // Returns a crand.Reader.
    33  func CReader() io.Reader {
    34  	return crand.Reader
    35  }