2013-10-23 337 views
0

使用下面的代码创建密钥,但是当我尝试使用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; } 

如下错误信息:

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) 

如果你想看到完整的代码,我可以张贴在这里。

+0

你正在使用哪个java版本? –

+0

我们不需要完整的代码,只需[SSCCE](http://www.sscce.org)=) –

回答

1

如果你提供的代码是你的实际类的真实反映,那么问题是这样的:

PublicKey publicKey = kp.getPublic(); 

被写入当地变量,但这样的:

public static PublicKey getPublicKey() { return publicKey; } 

正在返回一个不同的变量的值。实际上它必须是封闭类的静态字段......我期望它是null,因为你还没有初始化它!

我认为这里真正的问题是,你不能真正理解Java实例变量,静态变量和局部变量之间的区别。放在一起,我怀疑你的代码应该看起来像这样:

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; } 

}