使用RandomSecure生成密钥对 [英] Generate KeyPair with RandomSecure

查看:175
本文介绍了使用RandomSecure生成密钥对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,我是否可以始终生成相同的私钥?我累了用 KeyPairGenerator href ="https://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html#SecureRandom%28byte[]%29" rel ="nofollow"> RandomSecure 对象使用相同的seed:

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 ?

推荐答案

Java的SecureRandom实现取决于可用的提供程序,因此在不同的OS上或针对不同的实现,它可能会有所不同.

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

在linux上,默认实现是NativePRNG,它会忽略您的种子AFAIK.

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.

我过去已经这样做过,请记住它至少适用于某些Java实现.

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(); 
...

这篇关于使用RandomSecure生成密钥对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆