aboutsummaryrefslogtreecommitdiffstats
path: root/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemToPKCS12Converter.java
blob: ef1666dc6f51a2e7de90d866367b6b08d61130b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*============LICENSE_START=======================================================
 * aaf-certservice-client
 * ================================================================================
 * Copyright (C) 2020 Nokia. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.aaf.certservice.client.certification.conversion;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.security.KeyStore;
import java.security.KeyStore.LoadStoreParameter;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.List;
import java.util.Optional;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.onap.aaf.certservice.client.certification.exception.PemToPKCS12ConverterException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class PemToPKCS12Converter {

    private static final Logger LOGGER = LoggerFactory.getLogger(PemToPKCS12Converter.class);
    private static final String PKCS12 = "PKCS12";
    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 (#)";
    private final LoadStoreParameter EMPTY_KEYSTORE_CONFIGURATION = null;

    byte[] convertKeystore(List<String> certificateChain, Password password, String alias, PrivateKey privateKey)
        throws PemToPKCS12ConverterException {
        LOGGER.info("Conversion of PEM certificates to PKCS12 keystore");
        return convert(certificateChain, password, certs -> getKeyStore(alias, password, certs, privateKey));
    }

    byte[] convertTruststore(List<String> trustAnchors, Password password, String alias)
        throws PemToPKCS12ConverterException {
        LOGGER.info("Conversion of PEM certificates to PKCS12 truststore");
        return convert(trustAnchors, password, certs -> getTrustStore(alias, certs));
    }

    private byte[] convert(List<String> certificates, Password password, StoreEntryOperation operation)
        throws PemToPKCS12ConverterException {
        checkPassword(password);
        final Certificate[] X509Certificates = convertToCertificateArray(certificates);
        return getKeyStoreBytes(password, operation, X509Certificates);
    }

    private void checkPassword(Password password) throws PemToPKCS12ConverterException {
        if (!password.isCorrectPasswordPattern()) {
            LOGGER.error(PASSWORD_ERROR_MSG);
            throw new PemToPKCS12ConverterException(PASSWORD_ERROR_MSG);
        }
    }

    private byte[] getKeyStoreBytes(Password password, StoreEntryOperation op, Certificate[] x509Certificates)
        throws PemToPKCS12ConverterException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            KeyStore ks = op.getStore(x509Certificates);
            ks.store(bos, password.toCharArray());
            return bos.toByteArray();
        } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
            LOGGER.error("Pem to PKCS12 converter failed, exception message: {}", e.getMessage());
            throw new PemToPKCS12ConverterException(e);
        }
    }

    private KeyStore getKeyStore(String alias, Password password, Certificate[] certificates, PrivateKey privateKey)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
        KeyStore ks = getKeyStoreInstance();
        ks.setKeyEntry(alias, privateKey, password.toCharArray(), certificates);
        return ks;
    }

    private KeyStore getTrustStore(String alias, Certificate[] certificates)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
        KeyStore ks = getKeyStoreInstance();
        long i = 1L;
        for (Certificate c : certificates) {
            ks.setCertificateEntry(alias + i++, c);
        }
        return ks;
    }

    private KeyStore getKeyStoreInstance()
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
        KeyStore ks = KeyStore.getInstance(PKCS12);
        ks.load(EMPTY_KEYSTORE_CONFIGURATION);
        return ks;
    }

    private Certificate[] convertToCertificateArray(List<String> certificates)
        throws PemToPKCS12ConverterException {
        Certificate[] parsedCertificates = new Certificate[certificates.size()];
        for (String certificate : certificates) {
            parsedCertificates[certificates.indexOf(certificate)] = parseCertificate(certificate);
        }
        return parsedCertificates;
    }

    private Certificate parseCertificate(String certificate) throws PemToPKCS12ConverterException {
        try (PEMParser pem = new PEMParser(new StringReader(certificate))) {
            X509CertificateHolder certHolder = Optional.ofNullable((X509CertificateHolder) pem.readObject())
                .orElseThrow(
                    () -> new PemToPKCS12ConverterException("The certificate couldn't be parsed correctly. " + certificate));
            return new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider())
                .getCertificate(certHolder);
        } catch (IOException | CertificateException e) {
            LOGGER.error("Certificates conversion failed, exception message: {}", e.getMessage());
            throw new PemToPKCS12ConverterException(e);
        }
    }
}