JCASSL.java

Exemplo de autenticação TLS v1.2 com um site utilizando autenticação mútua.

Veja Nota sobre os exemplos.
package doxy.examples;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Principal;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
public class JCASSL {
static void printUsage()
{
System.out.println("Usage: <url> <path to host full cert chain> <key alias>");
System.out.println("Ex.: https://nfe.fazenda.sp.gov.br/ws/nfestatusservico2.asmx ./sefaz-sp.p7b mykey");
}
public static void main(String[] args) {
if(3 != args.length)
{
printUsage();
return;
}
try
{
String httpURL = args[0];
String chainPath = args[1];
String keyAlias = args[2];
/* Adiciona provider na JVM, dinamicamente. */
Security.addProvider(new br.com.trueaccess.provider.netdfence.ND());
/*
* O tipo de keystore TACV não remove objetos físicamente do HSM.
* Ele facilitará o "filtro" de chaves do key store.
*/
KeyStore ks = KeyStore.getInstance("TACV", "ND");
ks.load(null, "".toCharArray());
/* Filtra as chaves do keystore, deixando apenas o alias especificado. */
FilterKeyStore(keyAlias, ks);
/*
* Configura key store, trust store e parâmetros de conexão.
* */
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(getTrustKeyStore(chainPath));
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory ssf = sc.getSocketFactory();
URL url = new URL(httpURL);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Java Client 1.0");
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.connect();
/*
* Lista a cadeia de certificados do host.
* Esta é a cadeia enviada pelo próprio host.
*
* */
System.out.println("Host chain(received from host): ");
System.out.println();
Certificate[] serverCertificate = connection.getServerCertificates();
int i = 0;
for (Certificate certificate : serverCertificate) {
if (certificate instanceof X509Certificate) {
X509Certificate x509cert = (X509Certificate) certificate;
Principal principal = x509cert.getSubjectDN();
System.out.println("["+ i + "] " + "Subject: " + principal);
principal = x509cert.getIssuerDN();
System.out.println("Issuer: " + principal);
i++;
}
}
System.out.println();
/*
* Mostra o conteúdo da página acessada.
*/
printContent(connection);
connection.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}
static void printContent(HttpsURLConnection connection)
{
if(null != connection)
{
try {
System.out.println("URL content:");
System.out.println();
BufferedReader buffReader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
String input;
while ((input = buffReader.readLine()) != null)
{
System.out.println(input);
}
buffReader.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
static KeyStore getTrustKeyStore(String chainPath)
{
String pwd = "12345678";
KeyStore kstrusted = null;
try {
kstrusted = KeyStore.getInstance("JKS");
kstrusted.load(null, pwd.toCharArray());
//import client key
FileInputStream fistrusted = new FileInputStream(chainPath);
BufferedInputStream bistrusted = new BufferedInputStream(fistrusted);
CertificateFactory cftrusted = CertificateFactory.getInstance("X.509");
Certificate[] certs = (java.security.cert.Certificate []) cftrusted.generateCertificates(bistrusted).toArray();
int i = 0;
for(Certificate sepCert : certs)
{
kstrusted.setCertificateEntry(""+i++, sepCert);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return kstrusted;
}
static void FilterKeyStore(String keyAlias, KeyStore keyStore)
{
try {
Enumeration<String> keysInHSM = keyStore.aliases();
while(keysInHSM.hasMoreElements())
{
String nextKey = (String)keysInHSM.nextElement();
if(0 != nextKey.compareTo(keyAlias))
{
keyStore.deleteEntry(nextKey);
}
}
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
}