Consume REST API using java - SSLHandshakeException - java

I am trying to consume a REST API using Java. however, when I run the code it shows me this exception.
I didn't understand what does it mean, I try to search for the solution but I can't get it :(
this is the connection code:
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
public class connectToAPI {
public static void main(String[] args) {
try{
URL url = new URL("https://ip:port/rest/path");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userpassword = "user:pass";
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","Basic "+
userpassword);
conn.setRequestProperty("Content-Type","application/json");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
int status = 0;
if( null != conn ){
status = conn.getResponseCode();
}
if( status != 0){
System.out.println("status!=0");
if( status == 200 ){
System.out.println("status==200");
//SUCCESS message
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}else if(status == 401){
System.out.println("status==401");
}else if(status == 501){
System.out.println("status==501");
}else if( status == 503){
System.out.println("status==503");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
when I run the code it shows me this exception:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address ip found
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at alert.connectToBAM.main(connectToBAM.java:77)
Caused by: java.security.cert.CertificateException: No subject
alternative names matching IP address ip found
at sun.security.util.HostnameChecker.matchIP(Unknown Source)
at sun.security.util.HostnameChecker.match(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 14 more
I also tried jersey clinet:
javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://ip:port/rest/path");
System.out.println(
target.request(MediaType.APPLICATION_JSON).get(String.class));
it shows this error:
Exception in thread "main" javax.ws.rs.ProcessingException:
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No subject alternative names
matching IP address ip found
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:284)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
at alert.connectToBAM.main(connectToBAM.java:47)
Any idea? pleaseeee, it is my graduation project :(

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException
Generally these type of exceptions are occurs due to certificate verification issue of the certificate, follow the below steps :
1. Download the certificate from the browser and add it to cacerts file in the jre folder
2. we need to add some java code to verify the certificate using TrustManager.
Code is given below :
public static void trustManager()
{
try
{
TrustManager[] trustAllCerts = new TrustManager[]
{
new X509TrustManager()
{
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
};
//Create an Instance for SSLContext class
SSLContext sc = SSLContext.getInstance("SSL");
//overload init method
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//Use static method setDefaultSSLSocketFactory
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//Create Instance for Hostname verifier and override verify() method
HostnameVerifier allHostsValid = new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1)
{
return true;
}
};
//Verify hostname using static method setDefaultHostnameVerifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
catch(Exception e)
{
e.printStackTrace();
}
}
Whenever you are trying to execute just call this method at first in main method. Hope this will help you :)

Related

SSLHandshakeException while connecting to HTTPS site

I'm creating in Java HttpsURLConnection. I downloaded certificates from website and created file truststore.jks with this certs. My application is getting certs from truststore.jks and connecting to website. And it works... on my PC. But after deploy application on server I got this ugly exception:
Cause: 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
Stack trace:
[sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
sun.security.ssl.Handshaker.processLoop(Unknown Source)
sun.security.ssl.Handshaker.process_record(Unknown Source)
sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
I'm creating HttpsURLConnection in ConnectionFactory class, and running connection.getInputStream() method.
ConnectionFactory.java:
public final class ConnectionFactory {
public HttpsURLConnection getHttpsURLConnection(URL url, String trustStorePath, String trustStorePassword)
throws FileTransferWorkerException {
KeyStore keyStore = loadKeyStore(trustStorePath, trustStorePassword);
TrustManagerFactory trustManagerFactory = initTrustManagerFactory(keyStore);
SSLSocketFactory sslSocketFactory = buildSSLSocketFactory(trustManagerFactory);
return buildConnection(url, sslSocketFactory);
}
private KeyStore loadKeyStore(String path, String password) throws FileTransferWorkerException {
KeyStore keystore;
try {
keystore = KeyStore.getInstance("JKS");
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
try (FileInputStream fileInputStream = new FileInputStream(path)) {
keystore.load(fileInputStream, password.toCharArray());
} catch (IOException | CertificateException | NoSuchAlgorithmException e) {
throw new FileTransferWorkerException("Can not load keyStore from " + path, e);
}
return keystore;
}
private TrustManagerFactory initTrustManagerFactory(KeyStore keyStore) throws FileTransferWorkerException {
TrustManagerFactory trustManagerFactory;
try {
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
trustManagerFactory.init(keyStore);
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
return trustManagerFactory;
}
private SSLSocketFactory buildSSLSocketFactory(TrustManagerFactory trustManagerFactory) throws FileTransferWorkerException {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
} catch (KeyManagementException e) {
throw new FileTransferWorkerException(e);
}
return sslContext.getSocketFactory();
}
private HttpsURLConnection buildConnection(URL url, SSLSocketFactory sslSocketFactory) throws FileTransferWorkerException {
HttpsURLConnection connection;
try {
connection = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
throw new FileTransferWorkerException("Can not connect to " + url.getPath(), e);
}
connection.setSSLSocketFactory(sslSocketFactory);
return connection;
}
}
and invoke method:
private void download(URL url, String trustStorePath, String trustStorePassword, File file)
throws IOException, FileTransferWorkerException {
HttpsURLConnection connection = new ConnectionFactory().getHttpsURLConnection(url, trustStorePath, trustStorePassword);
try (ReadableByteChannel reader = Channels.newChannel(connection.getInputStream()){
...
} finally {
connection.disconnect();
}
}
I need to use my truststor.jks file, not cacerts. Do you have any ideas where I made a mistake? Help.
I figured it. Locally I'm connected to my company's network and I have their certificates (because of proxy). But server isn't using proxy and should have real certificates from endpoint server.

Sending mail in java eclipse not working

I am trying to make a function(in a user password reset class in java in eclipse) that sends an email. This is on a school computer. I am unsure if this is a problem with the computer or the code. It might be the computer because the school has a lot of restrictions on it. But the code also uses port 25 when it should use 587 as seen in the output. My code is as follows.
package Jframet;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Properties;
import java.util.Random;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class serial implements java.io.Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String uc;
private String pc;
private String ec;
public serial()
{
uc = "";
pc = "";
ec = "";
}
public serial(String u, String p, String e)
{
uc = u;
pc = p;
ec = e;
}
public boolean serialize(String s,serial e)
{
boolean b = true;
try {
File f = new File(s+this.uc+".ser");
String pathname = f.getPath();
FileOutputStream fileOut = new FileOutputStream(pathname);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
}catch(IOException i) {
i.printStackTrace();
b = false;
}
return b;
}
public boolean deserial(String u,String p)
{
boolean b = true;
serial e;
File test = new File("H:/classes/" + u + ".ser");
if(!test.exists())
{
b = false;
return b;
}
else
{
try {
FileInputStream fileIn = new FileInputStream(test);
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (serial) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
e = null;
i.printStackTrace();
b = false;
} catch (ClassNotFoundException c) {
e = null;
c.printStackTrace();
b = false;
}
String s1 = u;
String s2 = e.uc;
if(s1.compareTo(s2) == 0)
{
try{
if(!PasswordAuthentication.validatePassword(p,e.pc))
{
b = false;
}
else{}
}catch(NoSuchAlgorithmException i){ i.printStackTrace();
b = false;}
catch(InvalidKeySpecException i){ i.printStackTrace();
b = false;}
}
else
{
b = false;
}
}
return b;
}
public int emailtest(String u,String em)
{
Random r = new Random();
int b = r.nextInt(999999);
serial e;
File test = new File("H:/classes/" + u + ".ser");
if(!test.exists())
{
b = 0;
return b;
}
else
{
try {
FileInputStream fileIn = new FileInputStream(test);
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (serial) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
e = null;
i.printStackTrace();
b = 0;
} catch (ClassNotFoundException c) {
e = null;
c.printStackTrace();
b = 0;
}
if(u.compareTo(e.uc) == 0 && em.compareTo(e.ec) == 0)
{
String to = em;
String from = "168464#mcpsmd.net";
String host = "smtp.mail.com";
String port = "587";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.socketFactory.port", port);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(properties, null);
try {
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Password Reset");
// Now set the actual message
message.setText(Integer.toString(b));
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
else
{
if(u.compareTo(e.uc) != 0)
{
b = -1;
}
else
{
b = 0;
}
}
}
return b;
}
}
and my output is
javax.mail.MessagingException: Could not connect to SMTP host: smtp.mail.com, port: 25;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:295)
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 Jframet.serial.emailtest(serial.java:165)
at Jframet.loginpage$6.mouseClicked(loginpage.java:345)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:319)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:207)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
... 40 more
You need to add PasswordAuthentication like : UPDATED
String to = em;
String from = "168464#mcpsmd.net";
String host = "smtp.mail.com";
String port = "587";
String password = //Your email password
Properties properties = System.getProperties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", "587");
if (from.contains("hotmail")) {
properties.put("mail.smtp.host", "smtp.live.com");
} else if (from.contains("gmail")) {
properties.put("mail.smtp.host", "smtp.gmail.com");
} else if (from.contains("yahoo")) {
properties.put("mail.smtp.host", "smtp.mail.yahoo.com");
} else {
System.out.println("Please use 'Yahoo, Gmail or Hotmail")
}
Session messageSession = Session.getDefaultInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
MimeMessage mimeMessage = new MimeMessage(messageSession);
mimeMessage.setFrom(new InternetAddress(from));
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(subject);
mimeMessage.setText(message);
Transport.send(mimeMessage);
} catch (MessagingException e) {
System.out.println(e.getMessage());
}

Issue in executing SSL TLS client server Java programs

I have just started studying SSL TLS in Java and written the simple client and server programs. I run the server program first, followed by the client program. On execution, the client program gives the following exception stack trace :-
Exception in thread "main" javax.net.ssl.SSLHandshakeException: no cipher suites in common
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ServerHandshaker.chooseCipherSuite(Unknown Source)
at sun.security.ssl.ServerHandshaker.clientHello(Unknown Source)
at sun.security.ssl.ServerHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
at sun.security.ssl.AppInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at SSLServer.main(SSLServer.java:19)
Please let me know the solution to this problem. The server and client programs are as follows :-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
public class SSLServer {
private static final int PORT = 8080;
public static void main(String[] args) throws Exception {
SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket)ssf.createServerSocket(PORT);
SSLSocket s = (SSLSocket)ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while (((line = in.readLine()) != null)) {
System.out.println(line);
}
in.close();
s.close();
}
}
import java.io.OutputStream;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SSLClient {
private static final String HOST = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) throws Exception {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket s = (SSLSocket)sf.createSocket(HOST, PORT);
OutputStream out = s.getOutputStream();
out.write("\nConnection established.\n\n".getBytes());
out.flush();
int theCharacter = 0;
theCharacter = 5;
while (theCharacter != '~') // The '~' is an escape character to exit
{
out.write(theCharacter);
out.flush();
theCharacter = '~';
}
out.close();
s.close();
}
}
Let the client and server agree on a common cipher.
Add below code to both server and client.
String[] enableCipherSuite = {"SSL_DH_anon_WITH_RC4_128_MD5"};
s.setEnabledCipherSuites(enableCipherSuite);

java.net.UnknownHostException not able to connect to ftp

I have ftp port as: ftp://173.201.0.1/
I am trying to connect it through following:
String Ftp_Path = "ftp://173.201.0.1/";
public List<String> GetFileList()
{
String ftpServerIP = Ftp_Path;
String ftpUserID = Ftp_UserName;
String ftpPassword = Ftp_Password;
FTPFile[] downloadFiles = null;
StringBuilder result = new StringBuilder();
FTPClient ftp = new FTPClient();
List<String> xlsFiles = null;
try {
ftp.connect(Ftp_Path);
ftp.login(ftpUserID, ftpPassword);
downloadFiles=ftp.listFiles();
xlsFiles = new ArrayList<String>();
for(FTPFile i : downloadFiles) {
if(i.toString().endsWith(".xls")) {
xlsFiles.add(i.toString());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xlsFiles;
}
But I am getting error on line:
ftp.connect(Ftp_Path);
Following is the error.
java.net.UnknownHostException: ftp://173.201.0.1/
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.apache.commons.net.DefaultSocketFactory.createSocket(DefaultSocketFactory.java:92)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:201)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:289)
at com.amazonaws.mws.samples.ImportRulesPropertyClass.GetFileList(ImportRulesPropertyClass.java:33)
at com.amazonaws.mws.samples.ManageReportScheduleSample.main(ManageReportScheduleSample.java:74)
Plase help me.
I am new with java.
You just need to specify the IP.The FTPClient makes a ftp request.It is not similar to http request.Just change
String Ftp_Path = "ftp://173.201.0.1/";
to
String Ftp_Path = "173.201.0.1";
Also check whether the ftp port is up and accessible through telnet

How to call the https get method on a self signed server and client certificate

I have set up the Apache tomcat 5 to support ssl. Created self signed certificates and imported the client certificate into the trusstore of the server and imported the p12 file into the browser and accessing the page on the https is possible. How to achieve the same using java ?
Following is the code that i am attempting with but without any success...
//reference : http://vafer.org/blog/20061010073725/ http://www.mkyong.com/java/java-//https-client-httpsurlconnection-example/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.security.cert.Certificate;
public class HttpClientTutorial {
#SuppressWarnings("unused")
private static javax.net.ssl.SSLSocketFactory getFactory( File pKeyFile, String pKeyPassword ) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException
{
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream keyInput = new FileInputStream(pKeyFile);
keyStore.load(keyInput, pKeyPassword.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context.getSocketFactory();
}
private static void print_https_cert(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Cipher Suite : " + con.getCipherSuite());
System.out.println("\n");
Certificate[] certs = con.getServerCertificates();
for(Certificate cert : certs){
System.out.println("Cert Type : " + cert.getType());
System.out.println("Cert Hash Code : " + cert.hashCode());
System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
System.out.println("\n");
}
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
private static void print_content(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("****** Content of the URL ********");
BufferedReader br =
new BufferedReader(
new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null){
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException, UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
URL url = new URL("https://localhost:8443/SpringSec2");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(getFactory(new File("src/Client.p12"), "client"));
//dumpl all cert info
print_https_cert(con);
//dump all the content
print_content(con);
}
}
***************************************************************************************
Exception:
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.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
Since you are doing self signed certificate, you need to provide your own TrustManager. The line in your code
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
The second parameter in context.init is the TrustManager to manage which server you can trust. You basically need to create your own extension X509TrustManager. An example of that code can be found at http://www.howardism.org/Technical/Java/SelfSignedCerts.html. Search for NaiveTrustManager, you'll see that checkServerTrusted() is not implemented which implies it trusts everything. Try that first and see if that works. After it does, you might want to consider implementing stronger check.

Categories

Resources