Skip to content

Instantly share code, notes, and snippets.

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 alokmenghrajani/94703a63652bf17c328f921bd3431189 to your computer and use it in GitHub Desktop.
Save alokmenghrajani/94703a63652bf17c328f921bd3431189 to your computer and use it in GitHub Desktop.
Java 11 RsaKeyGen bug?
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.RSAKeyGenParameterSpec;
import static java.lang.String.format;
public class Main {
private static int KEY_SIZE = 2048;
public static void main(String[] args) throws Exception {
genKey1();
genKey2();
}
public static void genKey1() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec params = new RSAKeyGenParameterSpec(KEY_SIZE, RSAKeyGenParameterSpec.F4);
keyGen.initialize(params, new FakeRandom());
KeyPair keyPair = keyGen.generateKeyPair();
print(keyPair);
}
public static void genKey2() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(KEY_SIZE, new FakeRandom());
KeyPair keyPair = keyGen.generateKeyPair();
print(keyPair);
}
public static void print(KeyPair key) throws NoSuchAlgorithmException {
MessageDigest prng = MessageDigest.getInstance("SHA-256");
byte[] pub = prng.digest(key.getPublic().getEncoded());
for (int i = 0; i < pub.length; i++) {
System.out.print(format("%02x", pub[i]));
}
System.out.println();
}
public static class FakeRandom extends SecureRandom {
private byte[] state;
private int counter;
public FakeRandom() {
state = new byte[32];
for (byte i=0; i<32; i++) {
state[i] = i;
}
}
@Override
public void nextBytes(byte[] bytes) {
System.err.println(format("in FakeRandom: %d %d", bytes.length, counter++));
try {
int offset = 0;
while (true) {
MessageDigest prng = MessageDigest.getInstance("SHA-256");
state = prng.digest(state);
for (int i = 0; i < state.length; i++) {
if (offset == bytes.length) {
return;
}
bytes[offset++] = state[i];
}
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment