2023-01-30 16:27:06 +03:00
|
|
|
package mox
|
|
|
|
|
|
|
|
import (
|
|
|
|
cryptorand "crypto/rand"
|
|
|
|
"encoding/binary"
|
|
|
|
"fmt"
|
|
|
|
mathrand "math/rand"
|
2023-11-09 19:15:46 +03:00
|
|
|
"sync"
|
2023-01-30 16:27:06 +03:00
|
|
|
)
|
|
|
|
|
2023-11-09 19:15:46 +03:00
|
|
|
type rand struct {
|
|
|
|
*mathrand.Rand
|
|
|
|
sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewPseudoRand returns a new PRNG seeded with random bytes from crypto/rand.
|
|
|
|
func NewPseudoRand() *rand {
|
|
|
|
return &rand{Rand: mathrand.New(mathrand.NewSource(CryptoRandInt()))}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read can be called concurrently.
|
|
|
|
func (r *rand) Read(buf []byte) (int, error) {
|
|
|
|
r.Lock()
|
|
|
|
defer r.Unlock()
|
|
|
|
return r.Rand.Read(buf)
|
2023-01-30 16:27:06 +03:00
|
|
|
}
|
|
|
|
|
2023-02-05 18:29:03 +03:00
|
|
|
// CryptoRandInt returns a cryptographically random number.
|
|
|
|
func CryptoRandInt() int64 {
|
2023-01-30 16:27:06 +03:00
|
|
|
buf := make([]byte, 8)
|
|
|
|
_, err := cryptorand.Read(buf)
|
|
|
|
if err != nil {
|
|
|
|
panic(fmt.Errorf("reading random bytes: %v", err))
|
|
|
|
}
|
|
|
|
return int64(binary.LittleEndian.Uint64(buf))
|
|
|
|
}
|