View Javadoc
1   package org.kuali.common.http.model;
2   
3   import static com.google.common.io.Files.asByteSource;
4   import static java.util.Arrays.asList;
5   
6   import java.io.File;
7   import java.net.URL;
8   import java.security.KeyFactory;
9   import java.security.KeyStore;
10  import java.security.PrivateKey;
11  import java.security.SecureRandom;
12  import java.security.cert.Certificate;
13  import java.security.cert.CertificateFactory;
14  import java.security.spec.KeySpec;
15  import java.security.spec.PKCS8EncodedKeySpec;
16  import java.util.List;
17  
18  import javax.net.ssl.HttpsURLConnection;
19  import javax.net.ssl.SSLContext;
20  import javax.net.ssl.SSLSocketFactory;
21  import javax.net.ssl.TrustManagerFactory;
22  
23  import org.junit.Test;
24  
25  import com.google.common.io.ByteSource;
26  
27  public class PKCS8Test {
28  
29      private static final Certificate[] EMPTY_CERT_ARRAY = {};
30  
31      @Test
32      public void test() {
33          try {
34              String protocol = "TLS";
35              String certPath = "/Users/jcaddel/.boot2docker/certs/boot2docker-vm/cert.pem";
36              String keyPath = "/Users/jcaddel/.boot2docker/certs/boot2docker-vm/key.pkcs8";
37              URL url = new URL("https://192.168.59.103:2376/version");
38              ByteSource certSource = asByteSource(new File(certPath));
39              ByteSource keySource = asByteSource(new File(keyPath));
40              CertificateFactory cf = CertificateFactory.getInstance("X.509");
41              Certificate cert = cf.generateCertificate(certSource.openStream());
42              List<Certificate> chain = asList(cert);
43              byte[] privateKeyBytes = keySource.read();
44              KeyFactory keyFactory = KeyFactory.getInstance("RSA");
45              KeySpec ks = new PKCS8EncodedKeySpec(privateKeyBytes);
46              PrivateKey privateKey = keyFactory.generatePrivate(ks);
47              KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
48              keystore.load(null);
49              keystore.setKeyEntry("docker", privateKey, "abc".toCharArray(), chain.toArray(EMPTY_CERT_ARRAY));
50              TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
51              tmf.init(keystore);
52              SSLContext ctx = SSLContext.getInstance(protocol);
53              ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
54              SSLSocketFactory factory = ctx.getSocketFactory();
55              HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
56              conn.setSSLSocketFactory(factory);
57              conn.connect();
58          } catch (Throwable e) {
59              e.printStackTrace();
60          }
61      }
62  }