Last active
August 29, 2015 14:25
-
-
Save jpillora/5a0471b246d541b984ab to your computer and use it in GitHub Desktop.
Deterministic crypto/rand Reader
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
// 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 | |
} |
If you dont need strong crypto randomness, you can use https://github.com/dustin/randbo to get the reader interface over math/rand
@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
Run it here https://go-sandbox.com/#/kX-LptvhoF