Luke_Skywalker007
Luke_Skywalker007

Reputation: 145

Java casting error when retrieving private key from keystore

I am currently in the process of attempting to digitally sign a SOAP message and I'm following the guide from Oracle at the below link:

Programming With the Java XML Digital Signature API

When I initially ran my code I got the following error:

java.lang.UnsupportedOperationException: trusted certificate entries are not password-protected

I then amended the following line from:

KeyStore.PrivateKeyEntry keyEntry =
(KeyStore.PrivateKeyEntry) ks.getEntry
    ("mykey", new KeyStore.PasswordProtection("changeit".toCharArray()));

to:

KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry("mykey", null);

However, I am now getting the following error message:

 java.lang.ClassCastException: java.security.KeyStore$TrustedCertificateEntry cannot be cast to java.security.KeyStore$PrivateKeyEntry

Im going to assume the code explained at the above guide is correct therefore Im thinking there could be something wrong with my keystore certificates?

I did the following when importing my certificates into the keystore:

1) Created .pem from .pfx file using the following command:

 openssl pkcs12 -in myfile.pfx -out myfile.pem -clcerts

2) I then converted the .pem to a .der file due to the .pem format not importing into the keystore. I used the following command to convert from .pem to .der:

 openssl x509 -outform der -in myfile.pem -out myfile.der

3) Lastly, I imported my .der file by running the following command:

keytool -import -alias mykey -keystore "C:\Program Files\Java\jdk1.8.0_131\jre\lib\security\cacerts" -file myfile.der

Any help with this issue would be really appreciated. Thanks.

Upvotes: 1

Views: 2377

Answers (2)

Luke_Skywalker007
Luke_Skywalker007

Reputation: 145

Per the above feedback from @pedrofb, I directly converted the .pfx file to a jks file using the following command:

keytool -importkeystore -srckeystore "myfile.pfx" -srcstoretype pkcs12 -destkeystore "newkeystore.jks" -deststoretype JKS

I then ran the following command to obtain the alias from the new keystore which I added to the code allowing me digitally sign my XML:

keytool -list -v -keystore "newkeystore.jks" | findstr "Alias Creation"

Upvotes: 0

pedrofb
pedrofb

Reputation: 39291

You would need to import the private key of the certificate into the keystore, and not only the public key. It is not recommended to update the standard cacerts of JVM. Use a new file

But your three steps are not really needed. Just use directly the pfx file as PKCS12 keystore instead of JKS

Upvotes: 3

Related Questions