github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/crypto/rand.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/rand"
     5  	"fmt"
     6  	"math/big"
     7  )
     8  
     9  func init() {
    10  	if err := assertPRNG(); err != nil {
    11  		panic(err)
    12  	}
    13  }
    14  
    15  func assertPRNG() error {
    16  	buf := make([]byte, 1)
    17  	_, err := rand.Read(buf)
    18  	if err != nil {
    19  		return fmt.Errorf("crypto/rand: failed to read random data: %v", err)
    20  	}
    21  
    22  	return nil
    23  }
    24  
    25  func RandomBytes(length int) ([]byte, error) {
    26  	bytes := make([]byte, length)
    27  	_, err := rand.Read(bytes)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	return bytes, nil
    33  }
    34  
    35  // Ref: https://gist.github.com/dopey/c69559607800d2f2f90b1b1ed4e550fb?permalink_comment_id=3398811#gistcomment-3398811
    36  func RandomString(length int, alphabet string) (string, error) {
    37  	bytes := make([]byte, length)
    38  	for i := 0; i < length; i++ {
    39  		n, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))
    40  		if err != nil {
    41  			return "", err
    42  		}
    43  
    44  		bytes[i] = alphabet[n.Int64()]
    45  	}
    46  
    47  	return string(bytes), nil
    48  }
    49  
    50  func RandomUrlSafeString(length int) (string, error) {
    51  	return RandomString(length,
    52  		"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_")
    53  }