apg-go/random/random.go

81 lines
1.9 KiB
Go
Raw Normal View History

package random
2021-03-21 14:05:14 +01:00
import (
"crypto/rand"
"encoding/binary"
2021-03-21 14:05:14 +01:00
"fmt"
"math/big"
"strings"
)
// Bitmask sizes for the string generators (based on 93 chars total)
const (
letterIdxBits = 7 // 7 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
2021-03-21 14:05:14 +01:00
)
// GetChar generates random characters based on given character range
2021-03-21 14:05:14 +01:00
// and password length
func GetChar(cr string, l int) (string, error) {
if l < 1 {
return "", fmt.Errorf("length is negative")
}
rs := strings.Builder{}
rs.Grow(l)
crl := len(cr)
rp := make([]byte, 8)
_, err := rand.Read(rp)
if err != nil {
return rs.String(), err
2021-03-21 14:05:14 +01:00
}
for i, c, r := l-1, binary.BigEndian.Uint64(rp), letterIdxMax; i >= 0; {
if r == 0 {
_, err := rand.Read(rp)
if err != nil {
return rs.String(), err
}
c, r = binary.BigEndian.Uint64(rp), letterIdxMax
}
if idx := int(c & letterIdxMask); idx < crl {
rs.WriteByte(cr[idx])
i--
2021-03-21 14:05:14 +01:00
}
c >>= letterIdxBits
r--
2021-03-21 14:05:14 +01:00
}
return rs.String(), nil
2021-03-21 14:05:14 +01:00
}
// GetNum generates a random number with given maximum value
func GetNum(maxNum int) (int, error) {
2021-03-21 14:05:14 +01:00
if maxNum <= 0 {
err := fmt.Errorf("provided maxNum is <= 0: %v", maxNum)
return 0, err
}
maxNumBigInt := big.NewInt(int64(maxNum))
if !maxNumBigInt.IsUint64() {
err := fmt.Errorf("big.NewInt() generation returned negative value: %v", maxNumBigInt)
return 0, err
}
randNum64, err := rand.Int(rand.Reader, maxNumBigInt)
if err != nil {
return 0, err
}
randNum := int(randNum64.Int64())
if randNum < 0 {
err := fmt.Errorf("generated random number does not fit as int64: %v", randNum64)
return 0, err
}
return randNum, nil
}
2021-09-23 14:40:52 +02:00
// CoinFlip performs a simple coinflip based on the rand library and returns true or false
func CoinFlip() bool {
num := big.NewInt(2)
cf, _ := rand.Int(rand.Reader, num)
r := int(cf.Int64())
return r == 1
}