How to use Apache Commons SSLServer / SSLClient with certificate - java

I found a lot of examples for self signed certificates that are working well, but since we purchased a GoDaddy SSL certificate and I have some trouble making it work. I installed the key and certificate files on the server and here's what I have so far:
Server code:
public class SSLTestServer
{
public static void main(String[] args) throws GeneralSecurityException, IOException
{
SSLServer sslServer = new SSLServer();
sslServer.setKeyMaterial(new KeyMaterial("path/to/certificate.crt", "path/to/private-key.key", "changeit".toCharArray()));
//sslServer.setCheckHostname(false);
//sslServer.setCheckExpiry(true);
//sslServer.setCheckCRL(true);
try (ServerSocket serverSocket = sslServer.createServerSocket(5123))
{
try (Socket socket = serverSocket.accept())
{
System.out.println("Opened " + socket.getInetAddress());
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())))
{
System.out.println("Read: " + bufferedReader.readLine());
}
}
}
}
}
Client code:
public class SSLTestClient
{
public static void main(String[] args) throws GeneralSecurityException, IOException
{
SSLClient sslClient = new SSLClient();
sslClient.addTrustMaterial(TrustMaterial.CACERTS);
sslClient.setCheckHostname(true);
sslClient.setCheckExpiry(true);
sslClient.setCheckCRL(true);
try (Socket socket = sslClient.createSocket("mydomain.com", 5123))
{
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())))
{
writer.write("Hello world!\n");
}
}
}
}
What I get on server:
Exception in thread "main" 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:2023)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1125)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:928)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at iao.temp.onetime.SSLTestServer.main(SSLTestServer.java:54)
What I get on client:
Exception in thread "main" javax.net.ssl.SSLException: Connection has been shutdown: 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
at sun.security.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1541)
at sun.security.ssl.AppInputStream.available(AppInputStream.java:60)
at org.apache.commons.ssl.HostnameVerifier$AbstractVerifier.check(HostnameVerifier.java:313)
at org.apache.commons.ssl.HostnameVerifier$AbstractVerifier.check(HostnameVerifier.java:253)
at org.apache.commons.ssl.SSL.doPostConnectSocketStuff(SSL.java:444)
at org.apache.commons.ssl.Java14.buildSocket(Java14.java:158)
at org.apache.commons.ssl.JavaImpl.createSocket(JavaImpl.java:206)
at org.apache.commons.ssl.SSL.createSocket(SSL.java:481)
at org.apache.commons.ssl.SSLClient.createSocket(SSLClient.java:217)
at org.apache.commons.ssl.SSLClient.createSocket(SSLClient.java:197)
at org.apache.commons.ssl.SSLClient.createSocket(SSLClient.java:180)
at iao.temp.onetime.SSLTestClient.main(SSLTestClient.java:51)
Caused by: 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
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
Disconnected from the target VM, address: '127.0.0.1:51568', transport: 'socket'
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.getSession(SSLSocketImpl.java:2267)
at org.apache.commons.ssl.HostnameVerifier$AbstractVerifier.check(HostnameVerifier.java:272)
... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:105)
at org.apache.commons.ssl.Java14TrustManagerWrapper.checkServerTrusted(Java14TrustManagerWrapper.java:74)
at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:922)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
... 17 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 25 more
I also tried to import the certificate with the keytool, but I am not sure how to reference the imported certificate from code.
I am using Java 8.

Related

Resolve the exception generated while sending email using javamail api from java swing

I have written a code for sending email from java swing using javamail api .
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("melbino1992#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("melbino1992#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Hello");
MimeBodyPart messageBodyPart;
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("sent mail");
} catch (Exception e) {
//System.out.println(e);
e.printStackTrace();
}
System.out.println("hello!!!!!!!!");
}
But it shows an exception as javax.mail.MessagingException: Could not convert socket to TLS;
The stack trace is as follows
javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
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
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at workregistration.Send.main(Send.java:59)
Caused by: 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
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1902)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1338)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1032)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:486)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
... 7 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1320)
... 17 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
do this
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
if that fails check your firewall settings
Please check firewall and disable antivirus shield and check again...

smack setKeystorePath not working?

I'm using the smack 4.1.8 libraries to connect to an Openfire 3.10.2 server. The server has a self-signed certificate. If I add the server's certificate to the keystore used by the JVM, I can connect with no problem. But I'd rather have a keystore just for the use of smack in my application.
The code I'm using is below. I've seen some examples that make me think that setKeystorePath is a classpath path not a filesystem path. I've tried it both ways. I've verified the keystore type using type using the keytool command.
Does anyone have a working example of this?
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("bugs", "xxxxxx");
final String l_jabber_hostname = "xxxxxxx";
configBuilder.setServiceName(l_jabber_hostname);
configBuilder.setHost(l_jabber_hostname);
configBuilder.setPort(5222);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
configBuilder.setKeystorePath("/tmp/cacerts");
configBuilder.setKeystoreType("JKS");
configBuilder.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String a_hostname, SSLSession session) {
boolean l_approved = l_jabber_hostname.equalsIgnoreCase(a_hostname);
return l_approved;
}
});
Roster.setRosterLoadedAtLoginDefault(false);
XMPPTCPConnectionConfiguration l_config = configBuilder.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(l_config);
connection.connect();
Here is the error:
<org.jivesoftware.smack.SmackException: 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>org.jivesoftware.smack.SmackException: 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
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1029)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPConnection.java:956)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:971)
at java.lang.Thread.run(Thread.java:745)
Caused by: 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
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.proceedTLSReceived(XMPPTCPConnection.java:769)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.access$1000(XMPPTCPConnection.java:140)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1022)
... 3 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 19 more
Had the same problem. The solution was to create SSLContext:
public void connect() throws SmackException, IOException, XMPPException, UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException
{
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password)
.setServiceName(xmppdomain)
.setHost(host)
.setPort(port)
.setCustomSSLContext(getSSLContext())
.build();
xmppConnection = new XMPPTCPConnection(config);
xmppConnection.connect();
}
private SSLContext getSSLContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
char[] JKS_PASSWORD = "password".toCharArray();
char[] KEY_PASSWORD = "password".toCharArray();
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream is = new FileInputStream("<PATH_TO_JKS>");
keyStore.load(is, JKS_PASSWORD);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, KEY_PASSWORD);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());
return sc;
}

TestNG Email Report - PKIX path building exception

I am suddenly running in a problem scenario is
I've TestNG project in selenium when I execute a test case after the execution of test case I call the SendMail function written in another class "SendMail.java" using gmail smpt & port 465 it automatically attach the "emailable-report" from output folder after execution of test case it went successfully initially for several number of times but suddenly I am getting the exception shown below
DEBUG: setDebug: JavaMail version 1.4.7
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
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
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at automationframework.SendMail.sendMail(SendMail.java:134)
at automationframework.SendMail.execute(SendMail.java:22)
at automationframework.Iparkit_Login.sendReportMail(Iparkit_Login.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:308)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: 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
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1439)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:878)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:814)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
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 com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:211)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
... 24 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1421)
... 35 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
here is my SendMail.java class
package automationframework;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
//reportFileName = TestExecutionResultFileName
public static void execute(String reportFileName) throws Exception
{
String path="D:\\K - Selenium\\SeleniumWorkspace\\iParkit-copy\\test-output\\emailable-report.html";
String[] to={"receipient#gmail.com"};
String[] cc={};
String[] bcc={};//"<AutomationTester>"};
SendMail.sendMail("sender#gmail.com",
"*******",
"smtp.gmail.com",
"465",
"true",
"true",
true,
"javax.net.ssl.SSLSocketFactory",
"false",
to,
cc,
bcc,
"Test Execution Reports",
"Please find attached Test Suite Execution Report",
path,
reportFileName);
}
public static boolean sendMail(String userName,
String passWord,
String host,
String port,
String starttls,
String auth,
boolean debug,
String socketFactoryClass,
String fallback,
String[] to,
String[] cc,
String[] bcc,
String subject,
String text,
String attachmentPath,
String attachmentName){
//Object Instantiation of a properties file.
Properties props = new Properties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port)){
props.put("mail.smtp.port", port);
}
if(!"".equals(starttls)){
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
}
if(debug){
props.put("mail.smtp.debug", "true");
}else{
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port)){
props.put("mail.smtp.socketFactory.port", port);
}
if(!"".equals(socketFactoryClass)){
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
}
if(!"".equals(fallback)){
props.put("mail.smtp.socketFactory.fallback", fallback);
}
try{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
msg.setFrom(new InternetAddress(userName));
for(int i=0;i<to.length;i++){
msg.addRecipient(Message.RecipientType.TO, new
InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++){
msg.addRecipient(Message.RecipientType.CC, new
InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++){
msg.addRecipient(Message.RecipientType.BCC, new
InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
} catch (Exception mex){
mex.printStackTrace();
return false;
}
}
}
Please help I am struggling on it since 2 days but no solution is working for me
Finally I got the solution of my problem at my own, I had running Avast Anti Virus, I turned it off and now its working like charm...

How do I setup a CXF/SOAP client connection over https with username/password (no certificate)

We have a SOAP-webservice which we are trying to acquire a connection to through a https-connection setup with username / password connection, no certificate should be involved. It seems that Java is still attempting and failing a certificate handshake. How do I setup the connection such that it manages to use the username/password?
Error generated on attempting a query-call on MyWeb:
2012-08-29 13:31:19,918 WARN (LogUtils.java:371) - Interceptor for {http://myaddress/}MyWebService#{http://myqname/}getStatus has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:64)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:510)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:440)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:343)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:295)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)
at $Proxy55.getTccStatus(Unknown Source)
at se.transrail.cato.monitor.server.MonitorWsClient.readTccStatus(MonitorWsClient.java:65)
at se.transrail.cato.monitor.server.WebServicePoller.run(WebServicePoller.java:73)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.net.ssl.SSLHandshakeException: SSLHandshakeException invoking https://myaddress/: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.mapException(HTTPConduit.java:1404)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1389)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:623)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
... 18 more
Caused by: 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
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1868)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1338)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:998)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1294)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1321)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1305)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:515)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1090)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleHeadersTrustCaching(HTTPConduit.java:1337)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.onFirstWrite(HTTPConduit.java:1283)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:42)
at org.apache.cxf.io.AbstractThresholdOutputStream.write(AbstractThresholdOutputStream.java:69)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1361)
... 21 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1320)
... 37 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
... 43 more
MyWeb and MyWebService are generated by Apache CXF 2.4.8 wsdl2java. MyWeb is interface of MyWebService.
In myweb.wsdl I have replaced
Setup:
private MyWeb preparePort() {
MyWebService ss = new MyWebService(
// locally stored wsdl to avoid connection at this time
getClass().getClassLoader().getResource("myweb.wsdl");,
new QName("http://qname/", "MyWebService"));
MyWeb port = ss.getMonitorWebServicePort();
Client cl = ClientProxy.getClient(port);
HTTPConduit http = (HTTPConduit) cl.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(connectionTimeout);
httpClientPolicy.setReceiveTimeout(receiveTimeout);
httpClientPolicy.setConnection(ConnectionType.CLOSE);
httpClientPolicy.setMaxRetransmits(1);
http.setClient(httpClientPolicy);
((BindingProvider) port).getRequestContext().putAll(of(
USERNAME_PROPERTY, username,
PASSWORD_PROPERTY, password,
ENDPOINT_ADDRESS_PROPERTY, "https://mywebaddress/"));
return port;
From myweb.wsdl
<wsdl:service name="MyWebService">
<wsdl:port binding="tns:MyWebServiceSoapBinding" name="MyWebPort">
<soap:address location="https://mywebaddress/"/>
</wsdl:port>
</wsdl:service>
Attempted fixes found on the net that didn't work:
// AuthorizationPolicy authorizationPolicy = new AuthorizationPolicy();
// authorizationPolicy.setUserName(username);
// authorizationPolicy.setPassword(password);
// authorizationPolicy.setAuthorizationType("Basic");
// http.setAuthorization(authorizationPolicy);
// Authenticator myAuth = new Authenticator()
// {
// #Override
// protected PasswordAuthentication getPasswordAuthentication()
// {
// return new PasswordAuthentication(username, password.toCharArray());
// }
// };
// Authenticator.setDefault(myAuth);
Found a working solution here http://techpolesen.blogspot.se/2007/08/using-ssl-with-xfirecxf-battling.html which overrides the TrustManager to make it accept the connection without the existance of a certificate:
String targetAddr = http.getTarget().getAddress().getValue();
if (targetAddr.toLowerCase().startsWith("https:")) {
TrustManager[] simpleTrustManager = new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
TLSClientParameters tlsParams = new TLSClientParameters();
tlsParams.setTrustManagers(simpleTrustManager);
tlsParams.setDisableCNCheck(true);
http.setTlsClientParameters(tlsParams);
}

Soap SSL handshake Exception

I am trying to connect to HTTPS server through java code for the testing purpose.I am not really worried about serurity.I have added trustmanager for accepting all certs.As below
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
} };
try {
System.out.println("inside Try2");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
catch (Exception e) {
System.out.println("Exception11");
}
Even after adding this code as suggested on many forums I am getting SSL handshake exception.
Exception Trace:
[testng] Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
[testng] at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
[testng] at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
[testng] at sun.security.validator.Validator.validate(Validator.java:260)
[testng] at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
[testng] at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
[testng] at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
[testng] at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
[testng] ... 56 more
[testng] Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
[testng] at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
[testng] at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
[testng] at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
[testng] ... 62 more

Resources