OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
142 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils;
15
 
16
import java.io.BufferedReader;
17
import java.io.ByteArrayInputStream;
18
import java.io.File;
19
import java.io.FileReader;
20
import java.io.IOException;
177 ilm 21
import java.security.GeneralSecurityException;
142 ilm 22
import java.security.KeyFactory;
23
import java.security.KeyStore;
24
import java.security.NoSuchAlgorithmException;
25
import java.security.PrivateKey;
26
import java.security.cert.CertificateException;
27
import java.security.cert.CertificateFactory;
28
import java.security.cert.X509Certificate;
29
import java.security.interfaces.RSAPrivateKey;
30
import java.security.spec.InvalidKeySpecException;
31
import java.security.spec.PKCS8EncodedKeySpec;
32
import java.util.ArrayList;
33
import java.util.List;
34
 
35
import javax.net.ssl.KeyManager;
36
import javax.net.ssl.KeyManagerFactory;
37
import javax.net.ssl.SSLContext;
38
import javax.net.ssl.SSLServerSocketFactory;
39
import javax.xml.bind.DatatypeConverter;
40
 
41
public class PEMImporter {
42
 
177 ilm 43
    public static SSLServerSocketFactory createSSLFactory(File privateKeyPem, File certificatePem, String password) throws IOException, GeneralSecurityException {
142 ilm 44
        final SSLContext context = SSLContext.getInstance("TLS");
45
        final KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password);
46
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
47
        kmf.init(keystore, password.toCharArray());
48
        final KeyManager[] km = kmf.getKeyManagers();
49
        context.init(km, null, null);
50
        return context.getServerSocketFactory();
51
    }
52
 
53
    /**
54
     * Create a KeyStore from standard PEM files
55
     *
56
     * @param privateKeyPem the private key PEM file
57
     * @param certificatePem the certificate(s) PEM file
58
     * @param the password to set to protect the private key
59
     */
177 ilm 60
    public static KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password) throws IOException, GeneralSecurityException {
180 ilm 61
        if (!privateKeyPem.exists()) {
62
            throw new IllegalArgumentException("private key file missing : " + privateKeyPem.getAbsolutePath());
63
        }
64
        if (!certificatePem.exists()) {
65
            throw new IllegalArgumentException("certificate file missing : " + certificatePem.getAbsolutePath());
66
        }
142 ilm 67
        final X509Certificate[] cert = createCertificates(certificatePem);
68
        final KeyStore keystore = KeyStore.getInstance("JKS");
69
        keystore.load(null);
70
        // Import private key
71
        final PrivateKey key = createPrivateKey(privateKeyPem);
72
        keystore.setKeyEntry(privateKeyPem.getName(), key, password.toCharArray(), cert);
73
        return keystore;
74
    }
75
 
177 ilm 76
    private static PrivateKey createPrivateKey(File privateKeyPem) throws IOException, GeneralSecurityException {
142 ilm 77
        final BufferedReader r = new BufferedReader(new FileReader(privateKeyPem));
78
        String s = r.readLine();
79
        if (s == null || !s.contains("BEGIN PRIVATE KEY")) {
80
            r.close();
81
            throw new IllegalArgumentException("No PRIVATE KEY found");
82
        }
144 ilm 83
        final StringBuilder b = new StringBuilder();
142 ilm 84
        s = "";
85
        while (s != null) {
86
            if (s.contains("END PRIVATE KEY")) {
87
                break;
88
            }
89
            b.append(s);
90
            s = r.readLine();
91
        }
92
        r.close();
93
        final String hexString = b.toString();
94
        final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
95
        return generatePrivateKeyFromDER(bytes);
96
    }
97
 
177 ilm 98
    private static X509Certificate[] createCertificates(File certificatePem) throws IOException, CertificateException {
142 ilm 99
        final List<X509Certificate> result = new ArrayList<X509Certificate>();
100
        final BufferedReader r = new BufferedReader(new FileReader(certificatePem));
101
        String s = r.readLine();
102
        if (s == null || !s.contains("BEGIN CERTIFICATE")) {
103
            r.close();
104
            throw new IllegalArgumentException("No CERTIFICATE found");
105
        }
144 ilm 106
        StringBuilder b = new StringBuilder();
142 ilm 107
        while (s != null) {
108
            if (s.contains("END CERTIFICATE")) {
109
                String hexString = b.toString();
110
                final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
111
                X509Certificate cert = generateCertificateFromDER(bytes);
112
                result.add(cert);
144 ilm 113
                b = new StringBuilder();
142 ilm 114
            } else {
115
                if (!s.startsWith("----")) {
116
                    b.append(s);
117
                }
118
            }
119
            s = r.readLine();
120
        }
121
        r.close();
122
 
123
        return result.toArray(new X509Certificate[result.size()]);
124
    }
125
 
126
    private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
127
        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
128
        final KeyFactory factory = KeyFactory.getInstance("RSA");
129
        return (RSAPrivateKey) factory.generatePrivate(spec);
130
    }
131
 
132
    private static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
133
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
134
        return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
135
    }
136
 
137
}