eab9bf7c150e656b4d211ec4caa248872daab48b
[oom/platform/cert-service.git] / certServiceClient / src / main / java / org / onap / aaf / certservice / client / certification / conversion / PemToPKCS12Converter.java
1 /*============LICENSE_START=======================================================
2  * aaf-certservice-client
3  * ================================================================================
4  * Copyright (C) 2020 Nokia. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  */
19
20 package org.onap.aaf.certservice.client.certification.conversion;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.StringReader;
25 import java.security.KeyStore;
26 import java.security.KeyStore.LoadStoreParameter;
27 import java.security.KeyStoreException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.PrivateKey;
30 import java.security.cert.Certificate;
31 import java.security.cert.CertificateException;
32 import java.util.List;
33 import java.util.Optional;
34 import org.bouncycastle.cert.X509CertificateHolder;
35 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
36 import org.bouncycastle.jce.provider.BouncyCastleProvider;
37 import org.bouncycastle.openssl.PEMParser;
38 import org.onap.aaf.certservice.client.certification.exception.PemToPKCS12ConverterException;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 class PemToPKCS12Converter {
43
44     private final static String PKCS12 = "PKCS12";
45     private final static String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)";
46     private final LoadStoreParameter EMPTY_KEYSTORE_CONFIGURATION = null;
47     private final Logger LOGGER = LoggerFactory.getLogger(PemToPKCS12Converter.class);
48
49     byte[] convertKeystore(List<String> certificateChain, Password password, String alias, PrivateKey privateKey)
50         throws PemToPKCS12ConverterException {
51         LOGGER.debug("Converting PEM certificates to PKCS12 keystore.");
52         return convert(certificateChain, password, certs -> getKeyStore(alias, password, certs, privateKey));
53     }
54
55     byte[] convertTruststore(List<String> trustAnchors, Password password, String alias)
56         throws PemToPKCS12ConverterException {
57         LOGGER.debug("Converting PEM certificates to PKCS12 truststore.");
58         return convert(trustAnchors, password, certs -> getTrustStore(alias, certs));
59     }
60
61     private byte[] convert(List<String> certificates, Password password, StoreEntryOperation operation)
62         throws PemToPKCS12ConverterException {
63         checkPassword(password);
64         final Certificate[] X509Certificates = convertToCertificateArray(certificates);
65         return getKeyStoreBytes(password, operation, X509Certificates);
66     }
67
68     private void checkPassword(Password password) throws PemToPKCS12ConverterException {
69         if (!password.isCorrectPasswordPattern()) {
70             LOGGER.error(PASSWORD_ERROR_MSG);
71             throw new PemToPKCS12ConverterException(PASSWORD_ERROR_MSG);
72         }
73     }
74
75     private byte[] getKeyStoreBytes(Password password, StoreEntryOperation op, Certificate[] x509Certificates)
76         throws PemToPKCS12ConverterException {
77         try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
78             KeyStore ks = op.getStore(x509Certificates);
79             ks.store(bos, password.toCharArray());
80             return bos.toByteArray();
81         } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
82             LOGGER.error("Pem to PKCS12 converter failed", e);
83             throw new PemToPKCS12ConverterException(e);
84         }
85     }
86
87     private KeyStore getKeyStore(String alias, Password password, Certificate[] certificates, PrivateKey privateKey)
88         throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
89         KeyStore ks = getKeyStoreInstance();
90         ks.setKeyEntry(alias, privateKey, password.toCharArray(), certificates);
91         return ks;
92     }
93
94     private KeyStore getTrustStore(String alias, Certificate[] certificates)
95         throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
96         KeyStore ks = getKeyStoreInstance();
97         long i = 1L;
98         for (Certificate c : certificates) {
99             ks.setCertificateEntry(alias + i++, c);
100         }
101         return ks;
102     }
103
104     private KeyStore getKeyStoreInstance()
105         throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
106         KeyStore ks = KeyStore.getInstance(PKCS12);
107         ks.load(EMPTY_KEYSTORE_CONFIGURATION);
108         return ks;
109     }
110
111     private Certificate[] convertToCertificateArray(List<String> certificates)
112         throws PemToPKCS12ConverterException {
113         Certificate[] parsedCertificates = new Certificate[certificates.size()];
114         for (String certificate : certificates) {
115             parsedCertificates[certificates.indexOf(certificate)] = parseCertificate(certificate);
116         }
117         return parsedCertificates;
118     }
119
120     private Certificate parseCertificate(String certificate) throws PemToPKCS12ConverterException {
121         try (PEMParser pem = new PEMParser(new StringReader(certificate))) {
122             X509CertificateHolder certHolder = Optional.ofNullable((X509CertificateHolder) pem.readObject())
123                 .orElseThrow(
124                     () -> new PemToPKCS12ConverterException("The certificate couldn't be parsed correctly. " + certificate));
125             return new JcaX509CertificateConverter()
126                 .setProvider(new BouncyCastleProvider())
127                 .getCertificate(certHolder);
128         } catch (IOException | CertificateException e) {
129             LOGGER.error("Certificates conversion failed", e);
130             throw new PemToPKCS12ConverterException(e);
131         }
132     }
133 }