3

I am facing a weird error when I try to add a certificate to Keystore.

System.out.println(x509Certificate.getPublicKey()); // prints public key, certificate is valid
GlobalStoreManager.getInstance().getSPATruststore().setCertificateEntry(name, x509Certificate); // no error
System.out.println(GlobalStoreManager.getInstance().getSPATruststore().getCertificate(name)); // null

Why is the setCertificateEntry is not throwing any error and still getCertificate returns null?

Update:

I tried to get the certificate alias right after calling setCertificateEntry() and it worked??!, so the problems seems to be with getCertificate() call rather than setCertificateEntry() call?

System.out.println(GlobalStoreManager.getInstance().getSPATruststore().getCertificateAlias(x509Certificate));

Thanks.

Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98
  • what is your key bit size ? – Rookie007 Oct 16 '19 at 04:14
  • @Rookie007 2048 – Sapnesh Naik Oct 16 '19 at 04:18
  • @Rookie007 please see my update also – Sapnesh Naik Oct 16 '19 at 04:20
  • Did install the certificate in ur machine – Naveen Kulkarni Oct 16 '19 at 05:40
  • @SapneshNaik Okay may be this is not the reason, its always better to check, whether your java has bit size more than `256` or not. because when you are trying to set the certificate its not even getting set, so its always `null` – Rookie007 Oct 16 '19 at 06:26
  • You're probably getting two different instances of the `keyStore`, and as you haven't saved the first one the second one doesn't see the update. – user207421 Oct 16 '19 at 07:12
  • @user207421, I checked for that too and can confirm both objects are of same reference – Sapnesh Naik Oct 17 '19 at 03:36
  • @SapneshNaik, did you store the keystore after `GlobalStoreManager.getInstance().getSPATruststore().setCertificateEntry`? `setCertificateEntry` is not persistent. You would need something similtar to `getSPATruststore().store(out, password);` – pedrofb Oct 18 '19 at 10:15
  • @pedrofb I am only using a in memory keystore, I can not save it to any file – Sapnesh Naik Oct 18 '19 at 12:00
  • I have tested your code using an empty keystore and a sample x509certificate and it works perfectly. Look for the error in the keystore implementation that returns `GlobalStoreManager.getInstance().getSPATruststore()` – pedrofb Oct 21 '19 at 08:39
  • try to check your java certificate : https://stackoverflow.com/questions/8980364/how-do-i-find-out-what-keystore-my-jvm-is-using/8980479 then replace your cacerts file. – Jabongg Oct 24 '19 at 12:41

1 Answers1

0

Use the alias in setCertificateEntry(). Try it with keytool.

bbaassssiiee
  • 6,013
  • 2
  • 42
  • 55