github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/crypto/utils.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/base64"
     6  	"fmt"
     7  	"io"
     8  	math "math/rand"
     9  	"time"
    10  )
    11  
    12  // GenerateRandomBytes returns securely generated random bytes. It will return
    13  // an error if the system's secure random number generator fails to function
    14  // correctly, in which case the caller should not continue.
    15  func GenerateRandomBytes(n int) []byte {
    16  	b := make([]byte, n)
    17  	if _, err := io.ReadFull(rand.Reader, b); err != nil {
    18  		panic(err)
    19  	}
    20  	return b
    21  }
    22  
    23  // Timestamp returns the current timestamp, in seconds.
    24  func Timestamp() int64 {
    25  	return time.Now().Unix()
    26  }
    27  
    28  // Base64Encode encodes a value using base64.
    29  func Base64Encode(value []byte) []byte {
    30  	enc := make([]byte, base64.RawURLEncoding.EncodedLen(len(value)))
    31  	base64.RawURLEncoding.Encode(enc, value)
    32  	return enc
    33  }
    34  
    35  // Base64Decode decodes a value using base64.
    36  func Base64Decode(value []byte) ([]byte, error) {
    37  	dec := make([]byte, base64.RawURLEncoding.DecodedLen(len(value)))
    38  	b, err := base64.RawURLEncoding.Decode(dec, value)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	return dec[:b], nil
    43  }
    44  
    45  // GenerateRandomString generates a secure random string of length N
    46  func GenerateRandomString(n int) string {
    47  	const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    48  	bytes := GenerateRandomBytes(n)
    49  
    50  	for i, b := range bytes {
    51  		bytes[i] = letters[b%byte(len(letters))]
    52  	}
    53  
    54  	return string(bytes)
    55  }
    56  
    57  // GenerateRandomSixDigits returns a random string made of 6 digits
    58  func GenerateRandomSixDigits() string {
    59  	n := math.Intn(999999)
    60  	return fmt.Sprintf("%06d", n+1)
    61  }