Generate KeyPair with RandomSecure

别来无恙 提交于 2019-12-11 01:18:56

问题


Is there anyway I can generate always the same private key? I tired to initialize KeyPairGenerator with a RandomSecure object which uses the same seed:

private PrivateKey getPrivateKey(String seed) {
    try {   
        SecureRandom sr = new SecureRandom(seed.getBytes());

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024, sr);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair.getPrivate();
    } catch (NoSuchAlgorithmException e) {
        System.out.println("Failed to generate key pair!");
    }
    return null;
}

I invoke the above function and check if the private keys are the same:

String seed = "xyzabc123";
PrivateKey key1 = getPrivateKey(seed);
PrivateKey key2 = getPrivateKey(seed);

boolean same = key1.equals(key2); // false

They are different, my question is is there a way to generate always the same private key ?


回答1:


Java's SecureRandom implementation depends on the available providers, so it can be different on different OS's or for different implementations.

On linux, the default implementation is NativePRNG, which ignores your seed AFAIK.

What you could do is serialize your secure random before you call the generation, and deserialize it to reset it for the next generation.

I've done this in the past, and remember it works for at least some Java implementation.

String seed = "xyzabc123";
SecureRandom sr = new SecureRandom(seed.getBytes());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);   
out.writeObject(sr);
byte[] superseed = bos.toByteArray();
PrivateKey key1 = getPrivateKey(superseed);
PrivateKey key2 = getPrivateKey(superseed);

private PrivateKey getPrivateKey(byte[] superseed) {
    ByteArrayInputStream bis = new ByteArrayInputStream(superseed);
    ObjectInput in = new ObjectInputStream(bis);
    SecureRandom sr = (SecureRandom)in.readObject(); 
...



回答2:


I don't think this code will generate same private-key at each request. Reason behind this is this particular piece of code

SecureRandom sr = new SecureRandom(seed.getBytes());

each time you call getPrivateKey(String) method. at each time SecureRandom Class will generate a new random Number.

keyGen.initialize(1024, sr); //each time secure random number will be different.
KeyPair keyPair = keyGen.generateKeyPair();

and keyGen.initialize() method initialized with different keys all the time so,each time keyGen.generateKeyPair(); method will generate a different private-key.

If you try to change or pass same SecureRandom object in initialize() method then only it can be achieved Possibly.



来源:https://stackoverflow.com/questions/36791447/generate-keypair-with-randomsecure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!