Created
September 8, 2017 16:29
-
-
Save lmas/a45db81e23a6592ce302e145ce33ac4d to your computer and use it in GitHub Desktop.
Simple attempt at visual analysis of RNG sources
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Inspiration: https://www.random.org/analysis/ | |
import ( | |
"image" | |
"image/color" | |
"image/png" | |
"math/big" | |
"os" | |
cr "crypto/rand" | |
mr "math/rand" | |
) | |
func main() { | |
maxSize := 512 | |
// Using a bad RNG source, aka math/rand | |
mathRND := func(max int) int { | |
return mr.Intn(max) | |
} | |
err := GenerateImage(maxSize, "math.png", mathRND) | |
if err != nil { | |
panic(err) | |
} | |
// And here's the good one, crypto/rand | |
cryptoRND := func(max int) int { | |
i, err := cr.Int(cr.Reader, big.NewInt(int64(max))) | |
if err != nil { | |
panic(err) | |
} | |
return int(i.Int64()) | |
} | |
err = GenerateImage(maxSize, "crypto.png", cryptoRND) | |
if err != nil { | |
panic(err) | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////// | |
type RNDFunc func(int) int | |
func GenerateImage(max int, path string, f RNDFunc) error { | |
points := makePoints(max, f) | |
img := makeImage(max, points) | |
err := saveImage(path, img) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
//////////////////////////////////////////////////////////////////////////////// | |
func makePoints(max int, fn RNDFunc) []image.Point { | |
var points []image.Point | |
for i := 40000; i > 0; i-- { | |
x, y := fn(max), fn(max) | |
points = append(points, image.Point{x, y}) | |
} | |
return points | |
} | |
func makeImage(max int, points []image.Point) image.Image { | |
min := 0 | |
c := color.Gray{255} | |
img := image.NewGray(image.Rect(min, min, max, max)) | |
for _, p := range points { | |
if p.X >= min && p.X <= max && p.Y >= min && p.Y <= max { | |
img.Set(p.X, p.Y, c) | |
} | |
} | |
return img | |
} | |
func saveImage(path string, img image.Image) error { | |
f, err := os.Create(path) | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
if err = png.Encode(f, img); err != nil { | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment