InstallCert.java


002  * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
003  *
004  * Redistribution and use in source and binary forms, with or without
005  * modification, are permitted provided that the following conditions
006  * are met:
007  *
008  *   - Redistributions of source code must retain the above copyright
009  *     notice, this list of conditions and the following disclaimer.
010  *
011  *   - Redistributions in binary form must reproduce the above copyright
012  *     notice, this list of conditions and the following disclaimer in the
013  *     documentation and/or other materials provided with the distribution.
014  *
015  *   - Neither the name of Sun Microsystems nor the names of its
016  *     contributors may be used to endorse or promote products derived
017  *     from this software without specific prior written permission.
018  *
019  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
020  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
021  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
022  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
023  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
024  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
025  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
026  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
027  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
028  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
029  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
030  */
031  
032 import java.io.*;
033 import java.net.URL;
034  
035 import java.security.*;
036 import java.security.cert.*;
037  
038 import javax.net.ssl.*;
039  
040 public class InstallCert {
041  
042     public static void main(String[] args) throws Exception {
043     String host;
044     int port;
045     char[] passphrase;
046     if ((args.length == 1) || (args.length == 2)) {
047         String[] c = args[0].split(":");
048         host = c[0];
049         port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
050         String p = (args.length == 1) ? "changeit" : args[1];
051         passphrase = p.toCharArray();
052     } else {
053         System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
054         return;
055     }
056  
057     File file = new File("jssecacerts");
058     if (file.isFile() == false) {
059         char SEP = File.separatorChar;
060         File dir = new File(System.getProperty("java.home") + SEP
061             + "lib" + SEP + "security");
062         file = new File(dir, "jssecacerts");
063         if (file.isFile() == false) {
064         file = new File(dir, "cacerts");
065         }
066     }
067     System.out.println("Loading KeyStore " + file + "...");
068     InputStream in = new FileInputStream(file);
069     KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
070     ks.load(in, passphrase);
071     in.close();
072  
073     SSLContext context = SSLContext.getInstance("TLS");
074     TrustManagerFactory tmf =
075         TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
076     tmf.init(ks);
077     X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
078     SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
079     context.init(null, new TrustManager[] {tm}, null);
080     SSLSocketFactory factory = context.getSocketFactory();
081  
082     System.out.println("Opening connection to " + host + ":" + port + "...");
083     SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
084     socket.setSoTimeout(10000);
085     try {
086         System.out.println("Starting SSL handshake...");
087         socket.startHandshake();
088         socket.close();
089         System.out.println();
090         System.out.println("No errors, certificate is already trusted");
091     } catch (SSLException e) {
092         System.out.println();
093         e.printStackTrace(System.out);
094     }
095  
096     X509Certificate[] chain = tm.chain;
097     if (chain == null) {
098         System.out.println("Could not obtain server certificate chain");
099         return;
100     }
101  
102     BufferedReader reader =
103         new BufferedReader(new InputStreamReader(System.in));
104  
105     System.out.println();
106     System.out.println("Server sent " + chain.length + " certificate(s):");
107     System.out.println();
108     MessageDigest sha1 = MessageDigest.getInstance("SHA1");
109     MessageDigest md5 = MessageDigest.getInstance("MD5");
110     for (int i = 0; i < chain.length; i++) {
111         X509Certificate cert = chain[i];
112         System.out.println
113             (" " + (i + 1) + " Subject " + cert.getSubjectDN());
114         System.out.println("   Issuer  " + cert.getIssuerDN());
115         sha1.update(cert.getEncoded());
116         System.out.println("   sha1    " + toHexString(sha1.digest()));
117         md5.update(cert.getEncoded());
118         System.out.println("   md5     " + toHexString(md5.digest()));
119         System.out.println();
120     }
121  
122     System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
123     String line = reader.readLine().trim();
124     int k;
125     try {
126         k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
127     } catch (NumberFormatException e) {
128         System.out.println("KeyStore not changed");
129         return;
130     }
131  
132     X509Certificate cert = chain[k];
133     String alias = host + "-" + (k + 1);
134     ks.setCertificateEntry(alias, cert);
135  
136     OutputStream out = new FileOutputStream("jssecacerts");
137     ks.store(out, passphrase);
138     out.close();
139  
140     System.out.println();
141     System.out.println(cert);
142     System.out.println();
143     System.out.println
144         ("Added certificate to keystore 'jssecacerts' using alias '"
145         + alias + "'");
146     }
147  
148     private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
149  
150     private static String toHexString(byte[] bytes) {
151     StringBuilder sb = new StringBuilder(bytes.length * 3);
152     for (int b : bytes) {
153         b &= 0xff;
154         sb.append(HEXDIGITS[b >> 4]);
155         sb.append(HEXDIGITS[b & 15]);
156         sb.append(' ');
157     }
158     return sb.toString();
159     }
160  
161     private static class SavingTrustManager implements X509TrustManager {
162  
163     private final X509TrustManager tm;
164     private X509Certificate[] chain;
165  
166     SavingTrustManager(X509TrustManager tm) {
167         this.tm = tm;
168     }
169  
170     public X509Certificate[] getAcceptedIssuers() {
171         throw new UnsupportedOperationException();
172     }
173  
174     public void checkClientTrusted(X509Certificate[] chain, String authType)
175         throws CertificateException {
176         throw new UnsupportedOperationException();
177     }
178  
179     public void checkServerTrusted(X509Certificate[] chain, String authType)
180         throws CertificateException {
181         this.chain = chain;
182         tm.checkServerTrusted(chain, authType);
183     }
184     }
185  
186 }

你可能感兴趣的:(InstallCert.java)