Skip to content

Instantly share code, notes, and snippets.

@dilnei
Created March 28, 2016 15:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dilnei/86f19fe2261589c21303 to your computer and use it in GitHub Desktop.
Classe utilitária da Oracle para instalar certificados x509
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
/**
* Classe que gera arquivo truststore para qualquer URL.
*
* @author Dilnei Cunha.
*/
public class InstallCert {
private static final String JSSECACERTS = "cacerts";
private static final int TIMEOUT_WS = 30;
public static void main(String[] args) {
try {
char[] passphrase = "changeit".toCharArray();
File file = new File(JSSECACERTS);
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
file = new File(dir, JSSECACERTS);
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
info("| Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
get("efinanc.receita.fazenda.gov.br", 443, ks);
File cafile = new File(JSSECACERTS);
OutputStream out = new FileOutputStream(cafile);
ks.store(out, passphrase);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void get(String host, int port, KeyStore ks) throws Exception {
SSLContext context = SSLContext.getInstance("TLSv1");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
info("| Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(TIMEOUT_WS * 1000);
try {
info("| Starting SSL handshake...");
socket.startHandshake();
socket.close();
info("| No errors, certificate is already trusted");
} catch (SSLHandshakeException e) {
/**
* PKIX path building failed:
* sun.security.provider.certpath.SunCertPathBuilderException:
* unable to find valid certification path to requested target Não
* tratado, pois sempre ocorre essa excecao quando o cacerts nao
* esta gerado.
*/
} catch (SSLException e) {
error("| " + e.toString());
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
info("| Could not obtain server certificate chain");
}
info("| Server sent " + chain.length + " certificate(s):");
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
sha1.update(cert.getEncoded());
md5.update(cert.getEncoded());
String alias = host + "-" + (i);
ks.setCertificateEntry(alias, cert);
info("| Added certificate to keystore '" + JSSECACERTS + "' using alias '" + alias + "'");
}
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
private static void info(String log) {
System.out.println("INFO: " + log);
}
private static void error(String log) {
System.out.println("ERROR: " + log);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment