Use crypto/rand rather than math/rand

Who knows how random math/rand actually is
This commit is contained in:
Kovid Goyal 2023-02-02 06:04:17 +05:30
parent a9da57d9b3
commit 1d45cf4f91
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
3 changed files with 27 additions and 6 deletions

View File

@ -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)

View File

@ -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 {

View File

@ -3,10 +3,10 @@
package shm
import (
"crypto/rand"
"errors"
"fmt"
"io/fs"
"math/rand"
"os"
"reflect"
"testing"