Import Certificate to Keystore - java

I have generated the keystore using this command :
keytool -genkeypair -alias test -keyalg RSA -keystore keystore.jks
Under this section i have provided the following response:
What is your first and last name?
[Unknown]: myservice.example.com
Now i have generated the certificate with Common Name:myservice.example.com,
How should i import this certificate to my keystore so my client can connect to my service to a specific port and browser shouldn't display the invalid certificate error ?

Related

how to import certificate from the server and generate jks for it?

Some outer service which I use change http to https, and now I can't receive responses to my requests from it. So, I want to configure SSLSettings for my http requests. And as I understand I should "convert" public certificate from outer service (site) to jks file, to use in SSLSettings.
When I request to outer service, I receive an exception:
Caused by: javax.net.ssl.SSLPeerUnverifiedException: peer not
authenticated
I'm novice in ssl.
With command:
openssl s_client -connect some.host:443 | openssl x509 -pubkey -noout
I receive the answer:
depth=3 C = US, O = "The Go Daddy Group, Inc.", OU = Go Daddy Class 2 Certification Authority
verify error:num=19:self signed certificate in certificate chain
verify return:0
-----BEGIN PUBLIC KEY-----
//.....
-----END PUBLIC KEY-----
I don't really understand, in what format I receive this public key and
what should I do next to create jks file?
And I don't really understand, Am I in the right direction?
With keytool you can generate your keystore (.jks file ). you should use a command like :
keytool -keystore clientkeystore -genkey -alias client
for more detailed instructions check this url:
https://docs.oracle.com/cd/E19509-01/820-3503/6nf1il6er/index.html
Not sure if i am getting your question right but to generate a keystore you can use the below comand
keytool -genkeypair -keysize 2048 -keyalg RSA -alias testalias -keystore /test.keystore -ext SAN=dns:localhost,ip:xxx.xxx.xxx.xxx
and later extract the public key from it

Can't connect from JAVA to Mongo SSL Replica Set

I'm trying to set up last version of MongoDB with SSL encryption, I was able to connect from mongo shell but I'm getting an error when I connect from a Java Client.
Works
mongo admin --host mongo1.xxxx.com --ssl --sslPEMKeyFile mongoClient.pem --sslCAFile mongoCA.crt
Doesn't work
public static void main(String args[]){
System.setProperty("javax.net.ssl.trustStore","/home/gasparms/truststore.ts");
System.setProperty("javax.net.ssl.trustStorePassword", "mypasswd");
System.setProperty("javax.net.ssl.keyStore", "/home/gasparms/truststore.ts");
System.setProperty("javax.net.ssl.keyStorePassword", "mypasswd");
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
MongoClientOptions options = MongoClientOptions.builder().sslEnabled(true)
.build();
MongoClient mongoClient = new MongoClient("mongo1.xxxx.com",options);
System.out.println(mongoClient.getDatabaseNames());
}
I get this error from Mongo side:
2015-06-09T15:08:14.431Z I NETWORK [initandlisten] connection
accepted from 192.168.33.1:38944 #585 (3 connections now open)
2015-06-09T15:08:14.445Z E NETWORK [conn585] no SSL certificate
provided by peer; connection rejected 2015-06-09T15:08:14.445Z I
NETWORK [conn585] end connection 192.168.33.1:38944 (2 connections
now open) 2015-06-09T15:08:14.828Z I NETWORK [conn580] end connection
192.168.33.13:39240 (1 connection now open)
and in java client program
INFORMACIÓN: Exception in monitor thread while connecting to server
mongo1.xxxx.com:27017 com.mongodb.MongoSocketReadException:
Prematurely reached end of stream at
com.mongodb.connection.SocketStream.read(SocketStream.java:88) at
com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:491)
at
com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:221)
at
com.mongodb.connection.CommandHelper.receiveReply(CommandHelper.java:134)
at
com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:121)
at
com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at
com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83)
at
com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43)
at
com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at
com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
at java.lang.Thread.run(Thread.java:745)
Creation of Certificates
I have mongoCA.crt and mongoClient.pem that works with mongo shell. Then, I want to import .pem and .crt to a java keystore
openssl x509 -outform der -in certificate.pem -out certificate.der
keytool -import -alias MongoDB-Client -file certificate.der -keystore truststore.ts -noprompt -storepass "mypasswd"
keytool -import -alias "MongoDB-CA" -file mongoCA.crt -keystore truststore.ts -noprompt -storepass "mypasswd"
What I'm doing wrong?
I had the same problem, and for me it turned out to be a problem with the way I created the keystore. I notice that you are using the same file, truststore.ts, for both the truststore and keystore. This can work, but I would suggest using separate files to avoid confusion.
I had already created .pem files for the root CA and for the mongo user, and was able to successfully use them to connect with the mongo shell. From those I created truststore.jks and keystore.jks.
First, to create truststore.jks I ran:
keytool -import -alias root -storepass mypass -keystore truststore.jks -file rootca.pem -noprompt
For keystore.jks you need both the public and private keys so first convert the PEM file to PKCS12 format, and then import to a JKS:
openssl pkcs12 -export -out myuser.pkcs12 -in myuser.pem -password pass:mypass
keytool -importkeystore -srckeystore myuser.pkcs12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS -deststorepass mypass -srcstorepass mypass

Self Signed Certificate - Can't access relative links from client

I'm running jetty on linux, and using ssl. I have a self signed certificate, and everything works fine in the browser; I just need to tell the browser to trust the certificate since it's from an untrusted source. But if I try to access a link (like an image; https://www.xxxx.com/pictures/picture.jpg) from my web application, it gives me an error:
07/16 08:14:28.708 WARN [log] () EXCEPTION
javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1959)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1077)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:631)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:522)
I think I need to get the client to trust the self signed certificate. I've tried this:
Using keytool, create a certificate for the broker:
keytool -genkey -alias broker -keyalg RSA -keystore broker.ks
Export the broker's certificate so it can be shared with clients:
keytool -export -alias broker -keystore broker.ks -file broker_cert
Create a certificate/keystore for the client:
keytool -genkey -alias client -keyalg RSA -keystore client.ks
Create a truststore for the client, and import the broker's certificate:
keytool -import -alias broker -keystore client.ts -file broker_cert
And I include these when I start Jetty:
javax.net.ssl.keyStore=/path/to/client.ks
javax.net.ssl.keyStorePassword=password
javax.net.ssl.trustStore=/path/to/client.ts
I made sure jetty uses the certificate I generated through browser. What am I missing?
Purchased a certificate for the server, that solved the problem.

sun.security.validator.ValidatorException: PKIX path building failed

I have Created CSR request using this command :
openssl req -out certificatecsr.csr -new -newkey rsa:2048 -keyout certificatekey.key
After that CA has shared certificate(.cer) file with me.
Now after that i have converted .cer file to .p12 using key.
Creating a .p12 certificate using cer sent by CA and private key
C:\Java\jdk1.6.0_38\jre\bin>openssl pkcs12 -export -in C:\Users\asharma1\cert.cer -inkey certificatekey.key -out
certi.p12
Creating JKS keystore :
keytool -genkey -alias quid -keystore quid.jks
importing .p12 certificate into jks keystore
C:\Java\jdk1.6.0_38\jre\bin>keytool -v -importkeystore -srckeystore C:\OpenSSL-Win64\bin\certi.p12 -srcstoretype PKCS12
-destkeystore quid.jks -deststoretype JKS
but when i am referring this JKS from my java code i am getting this error :
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I have also added cer file to cacerts.but still getting the same error.
As far as JAVA code is concerned i am refering this link to refer my own created keystore :
http://jcalcote.wordpress.com/2010/06/22/managing-a-dynamic-java-trust-store/
public SSLContext getSSLContext(String tspath)
throws Exception {
TrustManager[] trustManagers = new TrustManager[] {
new ReloadableX509TrustManager(tspath)
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, null);
return sslContext;
}
SSLContext sslContext=getSSLContext("C:\\Java\\jdk1.6.0_38\\jre\\bin\\quid.jks");
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
URL pickUrl = new URL(pickupLocation);
URLConnection urlConn = pickUrl.openConnection();
HttpsURLConnection httpsURLConn = (HttpsURLConnection)urlConn;
httpsURLConn.setSSLSocketFactory(socketFactory);
String encoding = urlConn.getContentEncoding();
InputStream is = urlConn.getInputStream();
InputStreamReader streamReader = new InputStreamReader(is, encoding != null
? encoding : "UTF-8");
Please note i am not using any server. I am trying ti run above written code thorugh main method only.
Please let me know what need to be done.
Why do i need to convert my .cer file to .p12 file ?
I would suggest you import CA certificate (or whole chain of CA and intermediate CAs) to keystore.
I think that p12 was imported fine. What I am suggesting is import of the chain to keystore. At least that is what the error message is saying.
I presume that:
the root CA in the chain is not trusted so chain building fails or
there is no AIA section in certificates in the chain so no certificates up to trusted root CA can be fetched so chain building fails or
the certificates are not being fetched based on AIA because it is not implemented in java (I am not a java programmer) so chain building fails
You could use portecle to import missing trusted CA certificates (not end entity cartificate that you have in .p12 or in separate .cer file that you received from issuing CA). It is more user friendly than keytool. Just follow this guide.
I would suggest you use the *.der format instead of the .p12 format.
Here's an overall summary of how to import certificates to fix the following error:
Error while trying to execute request.
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target
How to import certificates
Go to URL in your browser, click on HTTPS certificate chain (little lock symbol next to URL address) to export the certificate
Click "more info" > "security" > "show certificate" > "details" > "export..".
Save as .der
Repeat for any certificates you need to import
Locate $JAVA_HOME/jre/lib/security/cacerts
Import all *.der files into the cacerts file using the following:
sudo keytool -import -alias mysitestaging -keystore $JAVA_HOME/jre/lib/security/cacerts -file staging.der
sudo keytool -import -alias mysiteprod -keystore $JAVA_HOME/jre/lib/security/cacerts -file prod.der
sudo keytool -import -alias mysitedev -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev.der
The default keystore password is 'changeit'
You can view the change that you made with this command that shows the Certificate fingerprint.
keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts
If this doesn't solve the problem, try adding these java options as arguments:
-Djavax.net.ssl.trustStore="$JAVA_HOME/jre/lib/security/cacerts"
-Djavax.net.ssl.trustStorePassword="changeit"

Keytool error: Failed to establish chain from reply

I'm having an error in importing the trial SSL certificate from CA. Below is my steps in creating the keystore. Please correct me if I'm wrong. Thank you in advance!
1.First, I created a keystore to be put in the server.
keytool -keystore server_keystore.jks -genkey -alias server -keyalg rsa -keysize 2048
2.Created a CSR.
keytool -keystore server_keystore.jks -certreq -alias server -keyalg rsa -file server.csr
Sent the CSR to CA (Thawte) and replied with three trial certificate namely, CA root, CA intermediate and trial SSL. Saved it to a text file with file extension .cer. (trial_ca_ssl.cer, trial_ca_root.cer, trial_ca_intermediate.cer)
3.Tried to import the trial_ca_ssl.cer in server_keystore.jks but I received an error.
keytool -import -keystore server_keystore.jks -file trial_ca_ssl.cer -alias server
Error:
keytool error: java.lang.Exception: Failed to establish chain from reply
You should keep your trial_ca_ssl.cer text on top of top server.cer. This will make a hierarchy of two certificate like this. Then you should import it.
-----BEGIN CERTIFICATE----- MIIDSjCCAjKgAwIBAgIIEvabM2CgLZcwDQYJKoZIhvcNAQEFBQAwMzETMBEGA1UE
AxMKV2FsdGVyIENBMTEPMA0GA1UEChMGV2FsdGVyMQswCQYDVQQGEwJTRTAeFw0w
MzA5MjkwOTI2MzRaFw0wNDA5MjgwOTM2MzRaMDMxEzARBgNVBAMTCldhbHRlciBD
QTExDzANBgNVBAoTBldhbHRlcjELMAkGA1UEBhMCU0UwggEgMA0GCSqGSIb3DQEB
AQUAA4IBDQAwggEIAoIBAQC3hXksEud68WwPWWHLJQQkTCuX/K32KHPPn/uPUzab
Cpc/FnaTmF9yEHmpFdAUr0v5ZPnxVQpcuwrDZc4YfaTLfyUHicQbkftsPAj/2hE4
UukS2j+nQQcJEnIY0vSZOAOLU3j4bf/RlS6Jl7TPFFfWTxuQF8AruQ+YhaE52JFi
SapGGXKQJxhsvKT91rLaWSFWNMTTLSDPaB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5e286PYptZIST77B9vOdQdl
PA+dFKFIaEwdzcS7H3Lf38WTE4D1OnyRX5jsiUe+YIQRtjv/Bmem+kSR84G9TwIB
EaNkMGIwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwYAMB0GA1UdDgQW
BBTDrXZGYXS9GyIUBOZrglhwNjjcnTAfBgNVHSMEGDAWgBTYRzrQMKPDDhP5yM84
PshcQmLPGDANBgkqhkiG9w0BAQUFAAOCAQEAdmTP1qVUcAKOf+/zvb2lcLKvFwKT
6KqDlO5NofjqCIfNgCjO2mO176cslnFIbEZQqgGIUnJ3AwfHKHj+U3kM3n5T29kF
xiLKxIDfjsY6qC03KHeGAgxI92XZyPsO1is6Y6qUnAmiwhIp5HS6E0+xIP1shmtJ
ZvqU8bueKUWSjx3JDzq+UNLX5pFkK0P0R90TCUEkBx1FNWqoWwb8zfAuO5zcNTEj
5E9esLjwxJQnIVPiA2l3FfZN9yomK+q7kTZJkX2kMx7G850lPR8CneXZT6bIOfck
Dw3PqQiroMNx2+gzC/f/wTXsF92aujyG+IZx1FIcNg/MoHXBWG7T8YrjnQ==
-----END CERTIFICATE-----
For details read the User Guide of EJBCA.
one possibility is that you use the default openssl tool in Mac, but you copy \openssl\apps\ca-cert.srl from a newer version openssl.

Categories