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)

如果您想查看完整的代码,我可以在这里发布。

4

1 回答 1

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

}
于 2013-10-23T15:45:01.497 回答