วันพุธที่ 28 กันยายน พ.ศ. 2554

HTTPS Java

HTTPS server on Windows
1. download "Win32 Binary including OpenSSL 0.9.8r"
(file.key = private key, file.cert = self signed certificate + public key)
3. re-config https, restart apache and verify


HTTPS client by Java
1. Since java truststore does not use the same format, then we have to convert self-signed certificate from server using this command
c:\> keytool -import -file file.cert -storepass $PASS -keystore server.keystore

2. Error:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

3. Add anonymous class :

con.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});

----- java code for https client -----

import java.net.*;
import java.io.*;
import javax.net.ssl.*;

public class HttpsClient {

public static void main(String[] args) throws Exception {
System.setProperty("javax.net.ssl.trustStore", "server.keystore");
String httpsURL = "https://147.127.xxx.xx/serverCertificate";
URL myurl = new URL(httpsURL);


HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
con.connect();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;

while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}

in.close();
}
}

Note: Just use for testing, it is not suitable for real deployment.

ไม่มีความคิดเห็น: