48 lines
1000 B
Go
48 lines
1000 B
Go
package randomutil
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
"math/big"
|
|
)
|
|
|
|
func GenerateRandomBytes(n int) ([]byte, error) {
|
|
result := make([]byte, n)
|
|
|
|
_, err := rand.Read(result)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error generating random bytes: %w", err)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
func GenerateFromCharset(charset string, n int) string {
|
|
result := make([]byte, n)
|
|
charsetBigLen := big.NewInt(int64(len(charset)))
|
|
|
|
for i := 0; i < n; i++ {
|
|
num, err := rand.Int(rand.Reader, charsetBigLen)
|
|
if err != nil {
|
|
panic(fmt.Errorf("error generating random string: %w", err))
|
|
}
|
|
|
|
result[i] = charset[num.Int64()]
|
|
}
|
|
|
|
return string(result)
|
|
}
|
|
|
|
const (
|
|
SecureTokenCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
ShortCharset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
|
)
|
|
|
|
func GenerateSecureToken(length int) string {
|
|
return GenerateFromCharset(SecureTokenCharset, length)
|
|
}
|
|
|
|
func GenerateRandomShort(n int) string {
|
|
return GenerateFromCharset(ShortCharset, n)
|
|
}
|