diff --git a/mac.go b/mac.go index df740af..8aaaffb 100644 --- a/mac.go +++ b/mac.go @@ -2,13 +2,12 @@ package security import ( "crypto/hmac" - crand "crypto/rand" + "crypto/rand" "crypto/sha256" - "encoding/binary" "encoding/hex" "errors" "fmt" - "math/rand" + "math/big" "net/http" "strings" "time" @@ -218,33 +217,22 @@ var randByteString = randomByteString const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func randomByteString(n int) []byte { - b := make([]byte, n) - for i := range b { - // FIXME convert to rand/v2 rand.N() - b[i] = letterBytes[secureRand.Intn(len(letterBytes))] - } - return b -} + ret := make([]byte, n) + i := 0 + for { -// create a math/random with a secure source to get real random numbers -// -//nolint:gosec -var secureRand = rand.New(src) -var src cryptoSource + num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes)))) + if err != nil { + continue + } -type cryptoSource struct{} + ret[i] = letterBytes[num.Int64()] -func (s cryptoSource) Seed(seed int64) { - // crypto/rand does not need a seed -} -func (s cryptoSource) Int63() int64 { - return int64(s.Uint64() & ^uint64(1<<63)) -} - -func (s cryptoSource) Uint64() (v uint64) { - err := binary.Read(crand.Reader, binary.BigEndian, &v) - if err != nil { - panic(fmt.Sprintf("crypto/rand is unavailable, read failed with: %v", err)) + i++ + if i == n { + break + } } - return v + + return ret } diff --git a/mac_test.go b/mac_test.go index 279e432..d1bc9f6 100644 --- a/mac_test.go +++ b/mac_test.go @@ -287,4 +287,7 @@ func TestMacCalc2(t *testing.T) { func Test_randomByteString(t *testing.T) { // make sure that we dont rely on pseudo-random-numbers require.NotEqual(t, "XVlBzgbaiCMRAjWwhTHctcuA", string(randomByteString(24))) + require.Len(t, randomByteString(24), 24) + require.Len(t, randomByteString(32), 32) + }