我使用以下代码创建密钥,但当我尝试使用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 :(得分:1)
如果您提供的代码是您实际课程的真实反映,那么问题是:
PublicKey publicKey = kp.getPublic();
正在写一个 local 变量,但是这个:
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; }
}