Revision 897

View differences:

org.gvsig.scripting/trunk/org.gvsig.scripting/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/java/org/gvsig/scripting/app/InstallCert.java
1
package org.gvsig.scripting.app;
2

  
3
/*
4
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without
7
 * modification, are permitted provided that the following conditions
8
 * are met:
9
 *
10
 *   - Redistributions of source code must retain the above copyright
11
 *     notice, this list of conditions and the following disclaimer.
12
 *
13
 *   - Redistributions in binary form must reproduce the above copyright
14
 *     notice, this list of conditions and the following disclaimer in the
15
 *     documentation and/or other materials provided with the distribution.
16
 *
17
 *   - Neither the name of Sun Microsystems nor the names of its
18
 *     contributors may be used to endorse or promote products derived
19
 *     from this software without specific prior written permission.
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
22
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
23
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
 */
33
/**
34
 * Originally from:
35
 * http://blogs.sun.com/andreas/resource/InstallCert.java
36
 * Use:
37
 * java InstallCert hostname
38
 * Example:
39
 *% java InstallCert ecc.fedora.redhat.com
40
 */
41

  
42
import java.io.BufferedReader;
43
import java.io.File;
44
import java.io.FileInputStream;
45
import java.io.FileOutputStream;
46
import java.io.InputStream;
47
import java.io.InputStreamReader;
48
import java.io.OutputStream;
49
import java.security.KeyStore;
50
import java.security.MessageDigest;
51
import java.security.cert.CertificateException;
52
import java.security.cert.X509Certificate;
53

  
54
import javax.net.ssl.SSLContext;
55
import javax.net.ssl.SSLException;
56
import javax.net.ssl.SSLSocket;
57
import javax.net.ssl.SSLSocketFactory;
58
import javax.net.ssl.TrustManager;
59
import javax.net.ssl.TrustManagerFactory;
60
import javax.net.ssl.X509TrustManager;
61

  
62
/**
63
 * Class used to add the server's certificate to the KeyStore
64
 * with your trusted certificates.
65
 * 
66
 * NOTE: modified to install the certificate always into the main cacerts
67
 * keystore.
68
 */
69
public class InstallCert {
70

  
71
    public static void install(String host, Integer port, String passphrase) throws Exception {
72
        if( passphrase==null ) {
73
            passphrase = "changeit";
74
        }
75
        if( port == null || port <1) {
76
            port = 443;
77
        }
78
        main(
79
            new String[] {
80
                host +":"+port,
81
                passphrase
82
            }
83
        );
84
    }
85
    
86
    public static void main(String[] args) throws Exception {
87
        String host;
88
        int port;
89
        char[] passphrase;
90
        if ((args.length == 1) || (args.length == 2)) {
91
            String[] c = args[0].split(":");
92
            host = c[0];
93
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
94
            String p = (args.length == 1) ? "changeit" : args[1];
95
            passphrase = p.toCharArray();
96
        } else {
97
            System.out.println("Usage: java InstallCert [:port] [passphrase]");
98
            return;
99
        }
100

  
101
        File file = null;
102
        // File file = new File("jssecacerts");
103
        // if (file.isFile() == false) {
104
        char SEP = File.separatorChar;
105
        File dir =
106
            new File(System.getProperty("java.home") + SEP + "lib" + SEP
107
                + "security");
108
        // file = new File(dir, "jssecacerts");
109
        // if (file.isFile() == false) {
110
                file = new File(dir, "cacerts");
111

  
112
        if (!file.canWrite()) {
113
            System.err
114
                .println("Unable to write in the file "
115
                    + file
116
                + ".\nRun InstallCert as an administrator or a user with "
117
                + "privileges to write in the cacerts file");
118

  
119
            System.exit(-1);
120
        }
121
        // }
122
        // }
123
        System.out.println("Loading KeyStore " + file + "...");
124
        InputStream in = new FileInputStream(file);
125
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
126
        ks.load(in, passphrase);
127
        in.close();
128

  
129
        SSLContext context = SSLContext.getInstance("TLS");
130
        TrustManagerFactory tmf =
131
            TrustManagerFactory.getInstance(TrustManagerFactory
132
                .getDefaultAlgorithm());
133
        tmf.init(ks);
134
        X509TrustManager defaultTrustManager =
135
            (X509TrustManager) tmf.getTrustManagers()[0];
136
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
137
        context.init(null, new TrustManager[] { tm }, null);
138
        SSLSocketFactory factory = context.getSocketFactory();
139

  
140
        System.out
141
            .println("Opening connection to " + host + ":" + port + "...");
142
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
143
        socket.setSoTimeout(10000);
144
        try {
145
            System.out.println("Starting SSL handshake...");
146
            socket.startHandshake();
147
            socket.close();
148
            System.out.println();
149
            System.out.println("No errors, certificate is already trusted");
150
        } catch (SSLException e) {
151
            System.out.println();
152
            e.printStackTrace(System.out);
153
        }
154

  
155
        X509Certificate[] chain = tm.chain;
156
        if (chain == null) {
157
            System.out.println("Could not obtain server certificate chain");
158
            return;
159
        }
160

  
161
        BufferedReader reader =
162
            new BufferedReader(new InputStreamReader(System.in));
163

  
164
        System.out.println();
165
        System.out.println("Server sent " + chain.length + " certificate(s):");
166
        System.out.println();
167
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
168
        MessageDigest md5 = MessageDigest.getInstance("MD5");
169
        for (int i = 0; i < chain.length; i++) {
170
            X509Certificate cert = chain[i];
171
            System.out.println(" " + (i + 1) + " Subject "
172
                + cert.getSubjectDN());
173
            System.out.println("   Issuer  " + cert.getIssuerDN());
174
            sha1.update(cert.getEncoded());
175
            System.out.println("   sha1    " + toHexString(sha1.digest()));
176
            md5.update(cert.getEncoded());
177
            System.out.println("   md5     " + toHexString(md5.digest()));
178
            System.out.println();
179
        }
180

  
181
//        int k=0;
182
//        System.out
183
//            .println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
184
//        String line = reader.readLine().trim();
185
//        try {
186
//            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
187
//        } catch (NumberFormatException e) {
188
//            System.out.println("KeyStore not changed");
189
//            return;
190
//        }
191

  
192
        for( int k=0; k<chain.length; k++ ) {
193
            X509Certificate cert = chain[k];
194
            String alias = host + "-" + (k + 1);
195
            ks.setCertificateEntry(alias, cert);
196

  
197
            // OutputStream out = new FileOutputStream("jssecacerts");
198
            OutputStream out = new FileOutputStream(file);
199
            ks.store(out, passphrase);
200
            out.close();
201

  
202
            System.out.println();
203
            System.out.println(cert);
204
            System.out.println();
205
            System.out
206
                .println("Added certificate to keystore '" +
207
                        file + "' using alias '" + alias + "'");
208
        }
209
    }
210

  
211
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
212

  
213
    private static String toHexString(byte[] bytes) {
214
        StringBuilder sb = new StringBuilder(bytes.length * 3);
215
        for (int b : bytes) {
216
            b &= 0xff;
217
            sb.append(HEXDIGITS[b >> 4]);
218
            sb.append(HEXDIGITS[b & 15]);
219
            sb.append(' ');
220
        }
221
        return sb.toString();
222
    }
223

  
224
    private static class SavingTrustManager implements X509TrustManager {
225

  
226
        private final X509TrustManager tm;
227
        private X509Certificate[] chain;
228

  
229
        SavingTrustManager(X509TrustManager tm) {
230
            this.tm = tm;
231
        }
232

  
233
        public X509Certificate[] getAcceptedIssuers() {
234
            throw new UnsupportedOperationException();
235
        }
236

  
237
        public void checkClientTrusted(X509Certificate[] chain, String authType)
238
            throws CertificateException {
239
            throw new UnsupportedOperationException();
240
        }
241

  
242
        public void checkServerTrusted(X509Certificate[] chain, String authType)
243
            throws CertificateException {
244
            this.chain = chain;
245
            tm.checkServerTrusted(chain, authType);
246
        }
247
    }
248
}

Also available in: Unified diff