简体   繁体   English

创建公钥和私钥

[英]Creating public and private keys

Im using the following code to create keys, but when i try to use KeyGeneration.getPublicKey() returns null . 我使用以下代码创建密钥,但是当我尝试使用KeyGeneration.getPublicKey()返回null

public KeyGeneration() throws Exception,(more but cleared to make easier to read)
{
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.genKeyPair();
    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

}

public static PublicKey getPublicKey() { return publicKey; }

Error message as below: 错误信息如下:

java.security.InvalidKeyException: No installed provider supports this key: (null)  
    at javax.crypto.Cipher.chooseProvider(Cipher.java:878)
    at javax.crypto.Cipher.init(Cipher.java:1213)
    at javax.crypto.Cipher.init(Cipher.java:1153)
    at RSAHashEncryption.RSAHashCipher(RSAHashEncryption.java:41)
    at RSAHashEncryption.exportEHash(RSAHashEncryption.java:21)
    at Main.main(Main.java:28)

If you would like to see the full code, i can post here. 如果您想查看完整的代码,我可以在这里发布。

If the code you supplied is a true reflection of your actual class, then the problem is that this: 如果您提供的代码是您实际类的真实反映,那么问题是:

    PublicKey publicKey = kp.getPublic();

is writing to a local variable, but this: 正在写入局部变量,但这:

    public static PublicKey getPublicKey() { return publicKey; }

is returning the value of a different variable. 返回另一个变量的值。 In fact it has to be a static field of the enclosing class ... and I expect that it is null because you haven't initialized it! 实际上,它必须是封闭类的静态字段...,我希望它为null因为您尚未初始化它!

I think the real problem here is that you don't really understand the difference between Java instance variables, static variables and local variables. 我认为这里的真正问题是您不太了解Java实例变量,静态变量和局部变量之间的区别。 Putting the pieces together, I suspect that your code should really look like this: 放在一起,我怀疑您的代码应该看起来像这样:

public class KeyGeneration {

    private PublicKey publicKey;
    private PrivateKey privateKey;

    public KeyGeneration() throws Exception /* replace with the actual list ... */ {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        KeyPair kp = kpg.genKeyPair();
        publicKey = kp.getPublic();
        privateKey = kp.getPrivate();
    }

    public PublicKey getPublicKey() { return publicKey; }

    public PrivateKey getPrivateKey() { return privateKey; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM