Skip to content

Instantly share code, notes, and snippets.

@jpillora
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpillora/5a0471b246d541b984ab to your computer and use it in GitHub Desktop.
Save jpillora/5a0471b246d541b984ab to your computer and use it in GitHub Desktop.
Deterministic crypto/rand Reader
// WARNING: This is a bad idea.
// Instead, use a Deterministic random bit generator specified in NIST SP 800-90A
// Unverified Go implementation from the TOR project:
// https://gist.github.com/jpillora/ed5cf69af7d35f9bb5f1
// Deterministic crypto/rand Reader
//
// Overview: half the result is used as the output,
// the other half is used as the next input
//
// [a|b] -> sha512(a) -> [a'|b'] -> sha512(a') -> [a''|b'']
// | | |
// output output output
package dcrypto
import (
"crypto/sha512"
"io"
)
func NewDetermRand(seed []byte) io.Reader {
return &DetermRand{next: seed}
}
type DetermRand struct {
next []byte
}
func (d *DetermRand) cycle() []byte {
result := sha512.Sum512(d.next)
d.next = result[:sha512.Size/2]
return result[sha512.Size/2:]
}
func (d *DetermRand) Read(b []byte) (int, error) {
n := 0
for n < len(b) {
out := d.cycle()
n += copy(b[n:], out)
}
return n, nil
}
@jpillora
Copy link
Author

@whyrusleeping
Copy link

If you dont need strong crypto randomness, you can use https://github.com/dustin/randbo to get the reader interface over math/rand

@jpillora
Copy link
Author

@whyrusleeping how would you seed it with a []byte? Hash then take 8 bytes to convert to int64?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment