Generate n random bytes based on m-byte seed in Java -


i'd generate n random bytes given m-byte seed. generated sequence has reproducible; same seed same sequence has generated. n can either higher or lower m.

the 2 following trivial approaches coming mind biased:

  • hash m bytes create long seed feed new java.util.random generator. problem: discard entropy if n<8, default random seed in java 8-byte long.
  • hash m bytes generate "random" data. problem: cap n value (20 sha1 example).

is there standard way of doing this? did not see relevant class in java.security, guess basic need cryptography?

note: not need "crypto-level extra-secure" random, random passes basic statistical randomness tests. i'd prefer relying on standard code instead of having code myself.

edit: java.security.securerandom(byte[] seed) not fit bill, generated sequence purely random , not depend on seed (at least on jvm, i'd have predictable result).

for record, (rather slow) solution discussed above:

    public byte[] rand(byte[] seed, int n) {         try {             byte[] data = null;             bytearrayoutputstream ret = new bytearrayoutputstream(n);             while (ret.size() < n) {                 messagedigest md = messagedigest.getinstance("sha1");                 md.update(seed);                 if (data != null)                     md.update(data);                 data = md.digest();                 ret.write(data, 0, math.min(n - ret.size(), data.length));             }             return ret.tobytearray();         } catch (nosuchalgorithmexception e) {             throw new runtimeexception(e);         }     } 

this generates 1m "random" bytes in ~500ms, , passes basic statistical randomness tests. maybe picking faster hash sha1 speed-up thing, did not investigated that.


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -