2023-10-26 17:26:09 +02:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
2023-10-26 18:31:57 +02:00
|
|
|
"fmt"
|
|
|
|
"math"
|
2023-10-26 17:26:09 +02:00
|
|
|
"math/big"
|
|
|
|
)
|
|
|
|
|
2023-10-26 18:31:57 +02:00
|
|
|
type CustomError struct {
|
|
|
|
Message string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *CustomError) Error() string {
|
|
|
|
return e.Message
|
|
|
|
}
|
|
|
|
|
2023-10-26 17:26:09 +02:00
|
|
|
// RandomString generates a string with the given length using crypt/rand
|
|
|
|
func RandomString(length int) (string, error) {
|
2023-10-26 18:31:57 +02:00
|
|
|
if length < 0 {
|
|
|
|
err := &CustomError{Message: "Length has to be bigger than 0"}
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if length > math.MaxInt32 {
|
|
|
|
err := &CustomError{Message: fmt.Sprintf("Length has to be bigger than %d", math.MaxInt32)}
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
const characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"
|
2023-10-26 17:26:09 +02:00
|
|
|
byteSlice := make([]byte, length)
|
|
|
|
for i := 0; i < length; i++ {
|
|
|
|
randomInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(characters))))
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
byteSlice[i] = characters[randomInt.Int64()]
|
|
|
|
}
|
|
|
|
return string(byteSlice), nil
|
|
|
|
}
|