Import private key and certificates into Java keystore - java

I have been provided with:
A private key (-----BEGIN RSA PRIVATE KEY-----)
Intermediate CA cert (-----BEGIN CERTIFICATE-----)
Root CA cert (-----BEGIN CERTIFICATE-----)
SSL connectivity exists and I have proven this successfully using curl;
curl -vv https://thirdparty.service.com --key private.pem --cert cert.crt
However, I wish to establish this SSL connection using Java. Given this, I know I need to import these certificates and key into my Java keystore.
I initially imported the Intermediate and Root CA certs only into my Java keystore but I could not establish a successful SSL connection to the third party service. Based on my curl command, I realised that I need to somehow import the private key into the Java keystore.
I have tried many openssl/keytool commands and this is the current combination/command I have running. I still cannot establish an SSL connection using Java.
cat cert.crt cachain.crt > import.pem
echo "pazzword" > pazzword.txt
openssl pkcs12 -export -in import.pem -inkey privkey.pem -name my_bundle -passout file:pazzword.txt > server.p12
${JAVA_HOME}/bin/keytool -importkeystore -srckeystore server.p12 -destkeystore ${JAVA_HOME}/jre/lib/security/cacerts -srcstoretype pkcs12 -srcstorepass pazzword -deststorepass changeit
Versions:
openjdk version "1.8.0_345"
OpenSSL 3.0.7 1 Nov 2022 (Library: OpenSSL 3.0.7 1 Nov 2022)
Can someone please help clarify what I should be doing with the certs and key I have above?
A successful SSL connection using my Java

Related

How to create Java JKS file from GoDaddy SSL certificate

I bought an SSL certificate in GoDaddy. I need to use it to start my Spark Java self-contained server through a secure connection. According to the documentation in http://sparkjava.com/documentation#examples-and-faq, I need to do the following:
String keyStoreLocation = "deploy/keystore.jks";
String keyStorePassword = "password";
secure(keyStoreLocation, keyStorePassword, null, null);
But when I download the certificate from GoDaddy I got the files:
11111.pem
11111.crt
bundle-g2-g1.crt
What do I need to do to convert these files is something compatible to use as the first parameter of secure(keyStoreLocation, keyStorePassword, null, null);?
IF the 1111.pem file is your private key (check the first line is 5 hyphens, BEGIN, optionally a word like RSA EC or ENCRYPTED, PRIVATE KEY, and 5 hyphens) then start with
openssl pkcs12 -export -in 1111.crt -inkey 1111.pem -certfile bundle-g2-g1.crt -out my.p12
Nearly all java programs since 2018 can actually use a PKCS12 instead of JKS for a keystore, but if this code really does need a JKS then do
keytool -importkeystore -srckeystore my.p12 -destkeystore my.jks -deststoretype jks
# if using very old Java (below 8u40 or so) add -srcstoretype pkcs12
Mostly dupe (but somewhat updated from)
Combined .pem certificate to truststore/keystore.jsk
convert certificate from pem into jks
How do I generate X.509 certificate from key generated by openssl and more linked there
https://serverfault.com/questions/483465/import-of-pem-certificate-chain-and-key-to-java-keystore

How to add SSH identity file keypair to JKS keystore

One of the tasks of a Java application I am building is to connect to a remote SFTP server. In order to do that I have the certificate of the remote machine and a local identity (id_rsa and id_rsa.pub in the .ssh folder). This is working fine.
I'd like to put the certificate and the identity in a password protected java keystore for easier and more secure configuration. I have this working for the certificate, but I am having problems storing the SSH identity in a JKS or PKCS12 keystore (either one would work).
To isolate the problem I have tried the following steps:
I use ssh-keygen -b 2048 to create the two identity files id_rsa_demo and id_rsa_demo.pub in te local directory. As I understand these are the private and public keys of the identity, so I try to combine those into an identity.p12 file:
openssl pkcs12 -export \
-inkey "id_rsa_demo" \
-in "id_rsa_demo.pub" \
-out "identity.p12" \
-password "pass:topsecret" \
-name "demoalias"
This gives me the error unable to load certificates. I searched around and it seems that openssl expects a certificate with a complete chain for the -in parameter. Since my generated identity does not have that, I tried the -nocerts option, like so:
openssl pkcs12 -export \
-inkey "id_rsa_demo" \
-in "id_rsa_demo.pub" \
-out "identity.p12" \
-password "pass:topsecret" \
-name "demoalias" \
-nocerts
I get no errors, but the -nocerts option lives up to its promise and does not add my public key to the pkcs12 file:
openssl pkcs12 -info -in identity.p12
Enter Import Password:
MAC Iteration 2048
MAC verified OK
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
Bag Attributes
friendlyName: demoalias
Key Attributes: <No Attributes>
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIAOXpzckBb28CAggA
MBQGCCqGSIb3DQMHBAjPq9ibr445xQSCBMi5IlOk5F28kQPB5D97afiUb5d3It46
...
ejwYfHTj6bm+dEOUk68zNrWwKqwuJx5AZv3U8sm1cicVmh9W0HpL5tSmMMpDS1ey
Uos=
-----END ENCRYPTED PRIVATE KEY-----
Is there a way to store an SSH identity into a PKCS12 or JKS keystore?
Supposing you have a private key that looks like this:
id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgQCh3czej+KeEraesxts3xP6kx+cO/Fu8ROc/k4hSl7fO9jFZ6Lm
OsGlzsRsi8VDg9n/fh6iFng/Umgnfd4J0IiLQihSRYnvyOsqqXbIJ8mBtydqO4s+
CjZLLDRSEMx3dw6GhFOcQ7xYYOeUMNY8QFidPn2LjURfMxG9XWOrCww8rwIBJQKB
gGA+sSpjZCajV9P7yx4jxrCqgX99lnlREpSy4lj7ybUqgOQUG6t84dg1wOaYS8dH
erOXGSIbMr3d+L2JHD0v4ntcKqzJm6Nf1FE27V0hvpzZl3fNax4NI/cIXM78zBx4
lBblr5QMYnTSd5eADIcDy7TZHuScRPkPViQ2x9QPayQ9AkEA67lfOXFEJ8iTYHdu
ykvj0Xqcs/peDX5nYXCEJ2XECxgxfKYVbQPazO5ACgp1VsgFMCsd4rDSwahOAgkE
rGfgCwJBAK/KFkSqMCLga8m19uqOftTQ+GhFc0O1lchWQ0A99+b9Rcs0yAe10GCN
SbgrEmMuXEQS1emT6ZHM7KIh2P7kiG0CQQDSPYxH/TzJiWDZf0cjIRdMIT+ncJkS
9DKw2flTkh2NWsRaap1858MleowkoYs/j81Gov76nbUNlhwPpy2uhiivAkByBor8
G11+aA6QrWHkQMD4vuZReSgr62gTPt+DndE74o4i8c3bfNowyllU3asP5rhjgdbc
svheksMBYhA2ohNNAkAiKQdv08UAG77piJi09OFIEcetTiq/wy9Zeb6fmEuMFzsT
2aR6x0d43OXqAgcKFgFuzqdXgxqhP/n9/eIqXdVA
-----END RSA PRIVATE KEY-----
Do two things:
1) Create a certificate to wrap the key and expose the public key as a certificate, so that keytool understands it.
openssl x509 -signkey id_rsa -req -in example.req
2) Create a self-signed certificate from your new request.
openssl x509 -signkey id_rsa -req -in example.req -out example.cer
Then, combine the certificate and private key, and import into keytool.
cat example.cer id_rsa > example.full
keytool -import -keystore example.jks -file example.full
This will get the keys in there. Utilizing the private and public keys and interacting with the SSH/SFTP library of your choice is left as an exercise.

Using a p12 file without a password in Java

Try as I might, I can't figure out how to use a .p12 file without a password in Java. I've tried setting javax.net.ssl.keyStorePassword to "" but whatever I do I get the following SSL error:
HTTP transport error: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
All my googling would suggest that the sun implementation will not allow an empty password and of course the keytool won't let you import any certificate without a password for the store.
The Sun API seems to require a password, so you will instead need to add a password to your .p12 file.
This page says that you can do this with openssl by converting the .p12 to a .pem, then converting back to a .p12 (but I have not tried it):
open­ssl pkcs12 -in cert.p12 -out temp.pem -passin pass: -passout pass:temppassword
open­ssl pkcs12 -export -in temp.pem -out cert-final.p12 -passin pass:temppassword -passout pass:newpa­ssword
rm -f temp.pem
See also this related question.

Getting No self-signed cert in chain error while using orapki wallet jks_to_pkcs12 -wallet

I got the CA signed certificates and tried to import into the Oracle Wallet Manager for OHS SSL. Private Key and certificate request is generated using open ssl and so we have to create the pkcs12 cert first using the below -
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12
After that i converted this to JKS using below -
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert
and then imported the Intermediate certs in the JKS. After that when i am trying to convert jks to pkcs12 again using -
mw_home\oracle_common\bin\orapki wallet jks_to_pkcs12 -wallet ./ -pwd "mypassword" -keystore ./mykeystore.jks -jkspwd "mypassword"
I am getting the error - Exception : java.io.IOException: No self-signed cert in chain.
We are not using any self-signed certificate so wondering from where we are getting this issue.
I tried using the p12 keystore that i created in the very first step but there is no certificate request or certificates getting displayed in Oracle Wallet.
Please suggest what is wrong I am doing or is there any best way to import certificates in Oracle Wallet.
why did you use keytool to import intermediate certifcates and not orapki?
orapki wallet add -wallet -cert trustedcerts.crt -trusted_cert
You don't need to bother creating a JKS file. Oracle wallets are valid PKCS12 files. Just create a PEM file with full certificate chain (your private key, your cert, and the full certificate chain in a single file), then run
openssl pkcs12 -export -in certchain.pem -out ewallet.p12
The name 'ewallet.p12' is important. That is Oracle's requirement. Put this file in your wallet directory, then run
orapki wallet create -wallet . -pwd your_pass -auto_login
to create the cwallet.sso file.

java.net.SocketException: Connection reset

I am coding an application where I control the code of both the client and the server.
I am using SSLSockets to implement it.
I have the protocol already running with normal unsecured sockets, but when I try to switch to SSLSockets (using exactly the same protocol), I keep getting the following stack trace:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:782)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:739)
For some reason, the exact same code works perfectly with unsecured sockets. Why could this be?
Any feedback would be appreciated. Thank you.
Pablo
From your post it is not possile to detect the problem.
When you switch to secure sockets the most secure ciphers are used by default.
If you have not configured your truststore/keystore correctly (or have not enabled the non-authenticated suites) then the SSL handshake will fail.
The exception seems to indicate that.
What you can do is run your program using javax.net.debug=ssl,handshake to enable SSL debugging info and post the debugging info and your code if you expect someone to help you.
Depending on what OS you are using, it may require admin/root priveledges to bind to or listen to the SSL port. Trying running your application with admin rights (in Windows) or sudo'd (on Linux).
Reasons can vary, -Djavax.net.debug=ssl is your friend, as suggested by Vladimir Dyuzhev.
Anyway, it may be a certificate problem -- make sure you have correct keystore and trustore. You will require one entry in keystore with:
private key
certificate
complete chain of issuer of the certificate
And a truststore:
complete chain of certificates for server certificate
I have problems generating proper keystore (trustore is easy -- just use keytool). For keystore you need st like this (Linux with openssl + java):
# convert all to PEM
openssl x509 -in ${ca}.der -inform DER -outform PEM -out ${ca}.pem
openssl x509 -in ${subca}.der -inform DER -outform PEM -out ${subca}.pem
# create one large PEM file containing certificate chain
cat ${ca}.pem ${subca}.pem > tmp_cert_chain.pem
# generate PKCS#12 BUNDLE
openssl pkcs12 -export -in ${cert}.pem -inkey ${key}.pem -certfile tmp_cert_chain.pem -out tmp_pkcs12.pfx
# convert PKCS#12 bundle to JKS
keytool -importkeystore -srckeystore tmp_pkcs12.pfx -srcstoretype pkcs12 -srcstorepass ${storepass} -destkeystore $keystore -deststoretype jks -deststorepass ${storepass}
# print out JKS keystore
keytool -list -keystore $keystore -storepass $storepass

Categories

Resources