Assignment: Load a remote URL via https, verifying the site certificate against a local root CA certificate.
Java, Android SDK:
1 // Load CAs from an InputStream
2 // (could be from a resource or ByteArrayInputStream or ...)
3 CertificateFactory cf = CertificateFactory.getInstance("X.509");
4 // From https://www.washington.edu/itconnect/security/ca/load-der.crt
5 InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
6 Certificate ca;
7 try {
8 ca = cf.generateCertificate(caInput);
9 System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
10 } finally {
11 caInput.close();
12 }
13
14 // Create a KeyStore containing our trusted CAs
15 String keyStoreType = KeyStore.getDefaultType();
16 KeyStore keyStore = KeyStore.getInstance(keyStoreType);
17 keyStore.load(null, null);
18 keyStore.setCertificateEntry("ca", ca);
19
20 // Create a TrustManager that trusts the CAs in our KeyStore
21 String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
22 TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
23 tmf.init(keyStore);
24
25 // Create an SSLContext that uses our TrustManager
26 SSLContext context = SSLContext.getInstance("TLS");
27 context.init(null, tmf.getTrustManagers(), null);
28
29 // Tell the URLConnection to use a SocketFactory from our SSLContext
30 URL url = new URL("https://certs.cac.washington.edu/CAtest/");
31 HttpsURLConnection urlConnection =
32 (HttpsURLConnection)url.openConnection();
33 urlConnection.setSSLSocketFactory(context.getSocketFactory());
34 InputStream in = urlConnection.getInputStream();
35 copyInputStreamToOutputStream(in, System.out);
1 import requests
2 x = requests.get('https://certs.cac.washington.edu/CAtest/', verify='load-der.crt')
Comments
JS · 23 October 2014
Perai - o código Java tá errado: não tem os imports, nem a declaração de classe, nem declaração de método. São pelo menos mais umas 5 linhas ai.JS · 23 October 2014
Wait - the Java code is incomplete: it lacks the imports, class and and method declarations. Add at least 5 more lines for the set. And before anyone say it is "trivial" - the Python code run as is. The Java code will require these other parts to compile.jminuscula · 25 November 2014
that's definitely not fair. Requests is a third party library, all you'd need to do is encapsulate the java code into a library and then make the import. I'm pretty sure there are libraries that already do that for you. In my opinion you should update the Python example to show how one would get to do it with the standard library… it's still way more beautiful than Java :)Xof · 25 November 2014
requests exists; that theoretical Java library doesn't. Wrapping up the example in a separate function still makes it your code to debug and maintain. There's a deeper question, which is that Java and Python have philosophies about API and library design that run much deeper than this one example; that's a subject for a separate post.