Added random package

This commit is contained in:
tyler 2021-09-07 22:24:42 -04:00
parent 94e8e766a4
commit bb5a453bec
3 changed files with 62 additions and 0 deletions

23
.gitignore vendored Normal file
View file

@ -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

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module github.com/tylertravisty/go-utils
go 1.16

36
random/random.go Normal file
View file

@ -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
}