Add creation JKS artifact
[oom/platform/cert-service.git] / certServiceClient / src / main / java / org / onap / aaf / certservice / client / certification / conversion / PemConverter.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.PemConversionException;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 class PemConverter {
43
44     private static final Logger LOGGER = LoggerFactory.getLogger(PemConverter.class);
45     private static final 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 String keyStoreType;
48
49     public PemConverter(String keyStoreType) {
50         this.keyStoreType = keyStoreType;
51     }
52
53     byte[] convertKeystore(List<String> certificateChain, Password password, String alias, PrivateKey privateKey)
54     throws PemConversionException {
55         LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " keystore");
56         return convert(certificateChain, password, certs -> getKeyStore(alias, password, certs, privateKey));
57     }
58
59     byte[] convertTruststore(List<String> trustAnchors, Password password, String alias)
60     throws PemConversionException {
61         LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " truststore");
62         return convert(trustAnchors, password, certs -> getTrustStore(alias, certs));
63     }
64
65     private byte[] convert(List<String> certificates, Password password, StoreEntryOperation operation)
66         throws PemConversionException {
67         checkPassword(password);
68         final Certificate[] X509Certificates = convertToCertificateArray(certificates);
69         return getKeyStoreBytes(password, operation, X509Certificates);
70     }
71
72     private void checkPassword(Password password) throws PemConversionException {
73         if (!password.isCorrectPasswordPattern()) {
74             LOGGER.error(PASSWORD_ERROR_MSG);
75             throw new PemConversionException(PASSWORD_ERROR_MSG);
76         }
77     }
78
79     private byte[] getKeyStoreBytes(Password password, StoreEntryOperation op, Certificate[] x509Certificates)
80         throws PemConversionException {
81         try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
82             KeyStore ks = op.getStore(x509Certificates);
83             ks.store(bos, password.toCharArray());
84             return bos.toByteArray();
85         } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
86             LOGGER.error("Pem to " + keyStoreType + " converter failed, exception message: {}", e.getMessage());
87             throw new PemConversionException(e);
88         }
89     }
90
91     private KeyStore getKeyStore(String alias, Password password, Certificate[] certificates, PrivateKey privateKey)
92         throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
93         KeyStore ks = getKeyStoreInstance();
94         ks.setKeyEntry(alias, privateKey, password.toCharArray(), certificates);
95         return ks;
96     }
97
98     private KeyStore getTrustStore(String alias, Certificate[] certificates)
99         throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
100         KeyStore ks = getKeyStoreInstance();
101         long i = 1L;
102         for (Certificate c : certificates) {
103             ks.setCertificateEntry(alias + i++, c);
104         }
105         return ks;
106     }
107
108     private KeyStore getKeyStoreInstance()
109         throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
110         KeyStore ks = KeyStore.getInstance(keyStoreType);
111         ks.load(EMPTY_KEYSTORE_CONFIGURATION);
112         return ks;
113     }
114
115     private Certificate[] convertToCertificateArray(List<String> certificates)
116         throws PemConversionException {
117         Certificate[] parsedCertificates = new Certificate[certificates.size()];
118         for (String certificate : certificates) {
119             parsedCertificates[certificates.indexOf(certificate)] = parseCertificate(certificate);
120         }
121         return parsedCertificates;
122     }
123
124     private Certificate parseCertificate(String certificate) throws PemConversionException {
125         try (PEMParser pem = new PEMParser(new StringReader(certificate))) {
126             X509CertificateHolder certHolder = Optional.ofNullable((X509CertificateHolder) pem.readObject())
127                 .orElseThrow(
128                     () -> new PemConversionException("The certificate couldn't be parsed correctly. " + certificate));
129             return new JcaX509CertificateConverter()
130                 .setProvider(new BouncyCastleProvider())
131                 .getCertificate(certHolder);
132         } catch (IOException | CertificateException e) {
133             LOGGER.error("Certificates conversion failed, exception message: {}", e.getMessage());
134             throw new PemConversionException(e);
135         }
136     }
137 }