0

Im using the following code to create keys, but when i try to use KeyGeneration.getPublicKey() returns 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.

2
  • Which java version your are using ? Commented Oct 23, 2013 at 15:06
  • We do not need the full code, just SSCCE =) Commented Oct 23, 2013 at 15:24

1 Answer 1

1

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!

I think the real problem here is that you don't really understand the difference between Java instance variables, static variables and local variables. 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; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.