From 10b945c31de42660f8589e9d347601f6f0456fcf Mon Sep 17 00:00:00 2001 From: Hilko Bengen Date: Fri, 22 Oct 2021 17:50:37 +0200 Subject: [PATCH] Don't abuse PRNG -> fix identifier generation when building on Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pseudorandom number generators need to be initialized only once. Using the system time for this is Generally Fine, but re-initializing the PRNG in a tight loop every time a random number is needed significantly raises the odds that the same number sequence (or even the same number) is returned every time. Chances for this to happen on Windows are apparently much higher than on Linux. Not sure why this is the case, my best guess is that the clock used for Go's `time.Now()ยด runs with coarser granularity. --- Cryptor/Cryptor.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Cryptor/Cryptor.go b/Cryptor/Cryptor.go index 72d4061..69e0e06 100644 --- a/Cryptor/Cryptor.go +++ b/Cryptor/Cryptor.go @@ -24,6 +24,10 @@ var ( ErrInvalidPKCS7Padding = errors.New("invalid padding on input") ) +func init() { + crand.Seed(time.Now().UnixNano()) +} + func Pkcs7Pad(b []byte, blocksize int) ([]byte, error) { if blocksize <= 0 { return nil, ErrInvalidBlockSize @@ -58,7 +62,6 @@ func RandStringBytes(n int) string { func VarNumberLength(min, max int) string { var r string - crand.Seed(time.Now().UnixNano()) num := crand.Intn(max-min) + min n := num r = RandStringBytes(n) @@ -72,7 +75,6 @@ func printHexOutput(input ...[]byte) { } func GenerateNumer(min, max int) int { - crand.Seed(time.Now().UnixNano()) num := crand.Intn(max-min) + min n := num return n