1

Below is my code for getting private key from Keystore file.

BouncyCastleProvider provider = new BouncyCastleProvider();
Security.addProvider(provider);
System.err.println(KeyStore.getDefaultType());
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream("src/main/resources/xxx.jks"), PASSWORD);
String alias = "xxxxxxx";
PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
System.err.println(pk);

I am giving right values for alias and password. But I am getting null in private key.

Why I am getting null, Is there any alternative approach to get private key from jks file.

Any help will be greatly appreciated!!

My question is not able to get the private key. But the mentioned question is the incorrect key

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Selva
  • 1,620
  • 3
  • 33
  • 63
  • 1
    Possible duplicate of [How to retrieve my public and private key from the keystore we created](https://stackoverflow.com/questions/19937890/how-to-retrieve-my-public-and-private-key-from-the-keystore-we-created) – Mansoor Ali Jul 09 '19 at 11:30
  • 1
    The [Javadocs](https://docs.oracle.com/javase/8/docs/api/java/security/KeyStore.html#getKey-java.lang.String-char:A-) tell you the answer: "Returns: the requested key, **or null if the given alias does not exist or does not identify a key-related entry.**". Believe it. – President James K. Polk Jul 09 '19 at 13:04
  • @JamesKPolk, Thanks, I checked the alias name exists by keystore.conatinsAlias("xxx") it returns true only. I have verified in linux also. – Selva Jul 09 '19 at 13:45
  • 1
    "...or does not identify a key-related entry". See [`isKeyEntry`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/security/KeyStore.html#isKeyEntry(java.lang.String)) – President James K. Polk Jul 09 '19 at 13:52
  • @JamesKPolk, yes you are correct. I have created new jks file and tried now I am getting the private key. So my previous jks file has no key related entry so only i am getting null. Thanks for your guidance. – Selva Jul 09 '19 at 14:10

0 Answers0