OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 144 | 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 {
142 ilm 61
        final X509Certificate[] cert = createCertificates(certificatePem);
62
        final KeyStore keystore = KeyStore.getInstance("JKS");
63
        keystore.load(null);
64
        // Import private key
65
        final PrivateKey key = createPrivateKey(privateKeyPem);
66
        keystore.setKeyEntry(privateKeyPem.getName(), key, password.toCharArray(), cert);
67
        return keystore;
68
    }
69
 
177 ilm 70
    private static PrivateKey createPrivateKey(File privateKeyPem) throws IOException, GeneralSecurityException {
142 ilm 71
        final BufferedReader r = new BufferedReader(new FileReader(privateKeyPem));
72
        String s = r.readLine();
73
        if (s == null || !s.contains("BEGIN PRIVATE KEY")) {
74
            r.close();
75
            throw new IllegalArgumentException("No PRIVATE KEY found");
76
        }
144 ilm 77
        final StringBuilder b = new StringBuilder();
142 ilm 78
        s = "";
79
        while (s != null) {
80
            if (s.contains("END PRIVATE KEY")) {
81
                break;
82
            }
83
            b.append(s);
84
            s = r.readLine();
85
        }
86
        r.close();
87
        final String hexString = b.toString();
88
        final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
89
        return generatePrivateKeyFromDER(bytes);
90
    }
91
 
177 ilm 92
    private static X509Certificate[] createCertificates(File certificatePem) throws IOException, CertificateException {
142 ilm 93
        final List<X509Certificate> result = new ArrayList<X509Certificate>();
94
        final BufferedReader r = new BufferedReader(new FileReader(certificatePem));
95
        String s = r.readLine();
96
        if (s == null || !s.contains("BEGIN CERTIFICATE")) {
97
            r.close();
98
            throw new IllegalArgumentException("No CERTIFICATE found");
99
        }
144 ilm 100
        StringBuilder b = new StringBuilder();
142 ilm 101
        while (s != null) {
102
            if (s.contains("END CERTIFICATE")) {
103
                String hexString = b.toString();
104
                final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
105
                X509Certificate cert = generateCertificateFromDER(bytes);
106
                result.add(cert);
144 ilm 107
                b = new StringBuilder();
142 ilm 108
            } else {
109
                if (!s.startsWith("----")) {
110
                    b.append(s);
111
                }
112
            }
113
            s = r.readLine();
114
        }
115
        r.close();
116
 
117
        return result.toArray(new X509Certificate[result.size()]);
118
    }
119
 
120
    private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
121
        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
122
        final KeyFactory factory = KeyFactory.getInstance("RSA");
123
        return (RSAPrivateKey) factory.generatePrivate(spec);
124
    }
125
 
126
    private static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
127
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
128
        return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
129
    }
130
 
131
}