I am trying to connect the MongoDB which is having SSL/TLS enabled along with self signed certificates. I have loaded the self-signed certificate in my local machine cacerts. But getting the exception
SSL is enabled but the socket is not an instance of javax.net.ssl.SSLSocket
References: Connecting to MongoDb with SSL from JAVA app
Problem with below code, it accepts all the certificates. I wanted it to be restricted with self-signed certificate that's jvm trust certificates
public static void main(String args[]) throws Exception {
String JAVA_HOME="C:\\Program Files\\Java\\jre1.8.0_211";
System.setProperty ("javax.net.ssl.trustStore",JAVA_HOME + "\\lib\\security\\cacerts");
System.setProperty ("javax.net.ssl.trustStorePassword","yyyy");
System.setProperty ("javax.net.ssl.keyStore",JAVA_HOME + "\\lib\\security\\mongo.pkcs12");
System.setProperty ("javax.net.ssl.keyStorePassword","xxxx");
MongoClientURI connectionString;
String uri = "mongodb://ttt:[email protected]:17017/db?authMechanism=SCRAM-SHA-1";
MongoClientOptions.Builder optionsBuilder;
optionsBuilder = MongoClientOptions.builder()
.sslEnabled(true)
.sslInvalidHostNameAllowed(true)
.socketFactory(getSSF());
connectionString = new MongoClientURI(uri, optionsBuilder);
MongoClient m = new MongoClient(connectionString);
DB db = m.getDB( "db" );
DBCollection c = db.getCollection( "mongostudent");
System.out.println( c.findOne() );
}
private static SSLSocketFactory getSSF() throws NoSuchAlgorithmException, KeyManagementException{
SSLContext sslContext;
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init((KeyManager[])null, new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
System.out.println("Certificate:"+x509Certificates[0]);
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
System.out.println("Certificate:"+x509Certificates[0]);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
return sslContext.getSocketFactory();
}
}
Keytool command used:
keytool -import -trustcacerts -file C:/certificateauth.pem -keystore cacertskeystore.jks -storepass "xxxx"placed the pkcs file in security folder
I need to configure it in a way so that it accepts only trusted certificate.
javax.net.ssl.SSLSocket'. Proof? What is it an instance of? and what does that have to do with your question? Solution: remove the insecureTrustManager. Importing the self-signed certificate into your truststore is sufficient.TrustManager. I don't see that you even need the explicitSSLContext: just use the default one. You haven't answered my question.