Skip to content

Instantly share code, notes, and snippets.

@akwizgran
Created March 31, 2017 10:21
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 akwizgran/a87a379068f2bbb51e536cb00df96373 to your computer and use it in GitHub Desktop.
Save akwizgran/a87a379068f2bbb51e536cb00df96373 to your computer and use it in GitHub Desktop.
Deterministic SecureRandom (neither secure nor random)
import java.security.Provider;
import java.security.SecureRandom;
import java.security.SecureRandomSpi;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.engines.Salsa20Engine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class PseudoSecureRandom extends SecureRandom {
private static final Provider PROVIDER = new PseudoSecureRandomProvider();
public PseudoSecureRandom(byte[] seed) {
super(new PseudoSecureRandomSpi(seed), PROVIDER);
}
private static class PseudoSecureRandomSpi extends SecureRandomSpi {
private final Salsa20Engine cipher;
private PseudoSecureRandomSpi(byte[] seed) {
cipher = new Salsa20Engine();
initialise(seed);
}
private void initialise(byte[] seed) {
// Hash the seed to produce a 256-bit key
byte[] key = new byte[32];
SHA256Digest digest = new SHA256Digest();
digest.update(seed, 0, seed.length);
digest.doFinal(key, 0);
// Initialise the stream cipher with an all-zero nonce
byte[] nonce = new byte[8];
cipher.init(true, new ParametersWithIV(new KeyParameter(key), nonce));
}
@Override
protected void engineSetSeed(byte[] seed) {
initialise(seed);
}
@Override
protected void engineNextBytes(byte[] out) {
byte[] blank = new byte[out.length];
cipher.processBytes(blank, 0, out.length, out, 0);
}
@Override
protected byte[] engineGenerateSeed(int length) {
byte[] seed = new byte[length];
engineNextBytes(seed);
return seed;
}
}
private static class PseudoSecureRandomProvider extends Provider {
private PseudoSecureRandomProvider() {
super("PseudoSecureRandom", 1.0, "Deterministic PRNG");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment