diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a358ce --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +## Go + +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# misc +.DS_Store + +# other +*.swp diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b247fe5 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/tylertravisty/go-utils + +go 1.16 diff --git a/random/random.go b/random/random.go new file mode 100644 index 0000000..3cb1512 --- /dev/null +++ b/random/random.go @@ -0,0 +1,36 @@ +package random + +import ( + "crypto/rand" + "encoding/base64" + "fmt" +) + +// Bytes creates an array of random bytes with specified size. +// If used to generate password salt, then size of 16 bytes (128 bits) is recommended. +func Bytes(size int) ([]byte, error) { + if size < 0 { + return nil, fmt.Errorf("random: size cannot be less than zero") + } + random := make([]byte, size) + + _, err := rand.Read(random) + if err != nil { + return nil, fmt.Errorf("random: error while reading random bytes: %v", err) + } + + return random, nil +} + +// String creates a Base64-encoded string of random bytes with specified length. +// If used to generate a session token, then length of 48 (36 bytes) is recommended. +func String(length int) (string, error) { + b, err := Bytes(length) + if err != nil { + return "", fmt.Errorf("random: error while generating random bytes: %v", err) + } + + str := base64.URLEncoding.EncodeToString(b) + + return str[:length], nil +}