From 1d45cf4f91010b6664651f2d0dee9543508169f5 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Thu, 2 Feb 2023 06:04:17 +0530 Subject: [PATCH] Use crypto/rand rather than math/rand Who knows how random math/rand actually is --- tools/cmd/icat/transmit.go | 19 +++++++++++++++++-- tools/utils/shm/shm.go | 12 +++++++++--- tools/utils/shm/shm_test.go | 2 +- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/tools/cmd/icat/transmit.go b/tools/cmd/icat/transmit.go index f95c89850..5db9ac49a 100644 --- a/tools/cmd/icat/transmit.go +++ b/tools/cmd/icat/transmit.go @@ -4,11 +4,13 @@ package icat import ( "bytes" + "crypto/rand" + "encoding/binary" "errors" "fmt" "io" "math" - "math/rand" + not_rand "math/rand" "os" "path/filepath" @@ -202,6 +204,19 @@ func place_cursor(imgd *image_data) { } } +func next_random() (ans uint32) { + for ans == 0 { + b := make([]byte, 4) + _, err := rand.Read(b) + if err == nil { + ans = binary.LittleEndian.Uint32(b[:]) + } else { + ans = not_rand.Uint32() + } + } + return ans +} + func transmit_image(imgd *image_data) { defer func() { for _, frame := range imgd.frames { @@ -239,7 +254,7 @@ func transmit_image(imgd *image_data) { } if len(imgd.frames) > 1 { for imgd.image_number == 0 { - imgd.image_number = rand.Uint32() + imgd.image_number = next_random() } } place_cursor(imgd) diff --git a/tools/utils/shm/shm.go b/tools/utils/shm/shm.go index cd6e4d655..79a04a716 100644 --- a/tools/utils/shm/shm.go +++ b/tools/utils/shm/shm.go @@ -3,9 +3,11 @@ package shm import ( + "crypto/rand" + "encoding/base32" "errors" "fmt" - "math/rand" + not_rand "math/rand" "os" "strconv" "strings" @@ -42,8 +44,12 @@ func prefix_and_suffix(pattern string) (prefix, suffix string, err error) { } func next_random() string { - num := rand.Uint32() - return strconv.FormatUint(uint64(num), 16) + b := make([]byte, 8) + _, err := rand.Read(b) + if err != nil { + return strconv.FormatUint(uint64(not_rand.Uint32()), 16) + } + return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b) } type MMap interface { diff --git a/tools/utils/shm/shm_test.go b/tools/utils/shm/shm_test.go index 8bb2952ba..6d6c2817e 100644 --- a/tools/utils/shm/shm_test.go +++ b/tools/utils/shm/shm_test.go @@ -3,10 +3,10 @@ package shm import ( + "crypto/rand" "errors" "fmt" "io/fs" - "math/rand" "os" "reflect" "testing"