X-Git-Url: http://www.club.cc.cmu.edu/~cmccabe/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=pickrand.go;h=1bf4844c67599735c972cc6287d49b4e6b0a99b9;hb=235c8f2e5692d8c89145085057609de827dc0aee;hp=a21efdaa80c8b7013e03b02bc1be5c312c4aa188;hpb=c37c837ee385eb4fd72f1af18b3a8523fe817282;p=cmccabe-bin diff --git a/pickrand.go b/pickrand.go index a21efda..1bf4844 100644 --- a/pickrand.go +++ b/pickrand.go @@ -1,11 +1,12 @@ package main import ( + "bytes" + "crypto/rand" "fmt" + "math/big" "os" "path/filepath" - "math/rand" - "time" ) func main() { @@ -27,7 +28,19 @@ func main() { fmt.Fprintf(os.Stderr, "** Error: %s\n", err.Error()) os.Exit(1) } - rand.Seed(time.Now().UTC().UnixNano()) - i := rand.Int31n(int32(len(files))) - fmt.Printf("%s\n", root + "/" + files[i]) + var b [8]byte + _, err = rand.Read(b[:]) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to access cryptographic randomness. " + + "Error: %s\n\n", err.Error()) + os.Exit(1) + } + i, err := rand.Int(bytes.NewReader(b[:]), big.NewInt(int64(len(files)))) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to get a random int. Error: %s\n", err.Error()) + os.Exit(1) + } + j := int(i.Uint64()) + + fmt.Printf("%s\n", root + "/" + files[j]) }