我使用以下代码创建密钥,但是当我尝试使用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)
如果您想查看完整的代码,我可以在这里发布。
最佳答案
如果您提供的代码是您实际类的真实反映,那么问题是:
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; }
}