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
 
  10  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  20 package org.onap.aaf.certservice.client.certification.conversion;
 
  22 import org.bouncycastle.cert.X509CertificateHolder;
 
  23 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
 
  24 import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
  25 import org.bouncycastle.openssl.PEMParser;
 
  26 import org.onap.aaf.certservice.client.certification.exception.PemConversionException;
 
  27 import org.slf4j.Logger;
 
  28 import org.slf4j.LoggerFactory;
 
  30 import java.io.ByteArrayOutputStream;
 
  31 import java.io.IOException;
 
  32 import java.io.StringReader;
 
  33 import java.security.KeyStore;
 
  34 import java.security.KeyStore.LoadStoreParameter;
 
  35 import java.security.KeyStoreException;
 
  36 import java.security.NoSuchAlgorithmException;
 
  37 import java.security.PrivateKey;
 
  38 import java.security.cert.Certificate;
 
  39 import java.security.cert.CertificateException;
 
  40 import java.util.List;
 
  41 import java.util.Optional;
 
  45     private static final Logger LOGGER = LoggerFactory.getLogger(PemConverter.class);
 
  46     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 (#)";
 
  47     private static final LoadStoreParameter EMPTY_KEYSTORE_CONFIGURATION = null;
 
  48     private final String keyStoreType;
 
  50     public PemConverter(String keyStoreType) {
 
  51         this.keyStoreType = keyStoreType;
 
  54     byte[] convertKeystore(List<String> certificateChain, Password password, String alias, PrivateKey privateKey)
 
  55             throws PemConversionException {
 
  56         LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " keystore");
 
  57         return convert(certificateChain, password, certs -> getKeyStore(alias, password, certs, privateKey));
 
  60     byte[] convertTruststore(List<String> trustAnchors, Password password, String alias)
 
  61             throws PemConversionException {
 
  62         LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " truststore");
 
  63         return convert(trustAnchors, password, certs -> getTrustStore(alias, certs));
 
  66     private byte[] convert(List<String> certificates, Password password, StoreEntryOperation operation)
 
  67             throws PemConversionException {
 
  68         checkPassword(password);
 
  69         final Certificate[] X509Certificates = convertToCertificateArray(certificates);
 
  70         return getKeyStoreBytes(password, operation, X509Certificates);
 
  73     private void checkPassword(Password password) throws PemConversionException {
 
  74         if (!password.isCorrectPasswordPattern()) {
 
  75             LOGGER.error(PASSWORD_ERROR_MSG);
 
  76             throw new PemConversionException(PASSWORD_ERROR_MSG);
 
  80     private byte[] getKeyStoreBytes(Password password, StoreEntryOperation op, Certificate[] x509Certificates)
 
  81             throws PemConversionException {
 
  82         try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
 
  83             KeyStore ks = op.getStore(x509Certificates);
 
  84             ks.store(bos, password.toCharArray());
 
  85             return bos.toByteArray();
 
  86         } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
 
  87             LOGGER.error("Pem to " + keyStoreType + " converter failed, exception message: {}", e.getMessage());
 
  88             throw new PemConversionException(e);
 
  92     private KeyStore getKeyStore(String alias, Password password, Certificate[] certificates, PrivateKey privateKey)
 
  93             throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
 
  94         KeyStore ks = getKeyStoreInstance();
 
  95         ks.setKeyEntry(alias, privateKey, password.toCharArray(), certificates);
 
  99     private KeyStore getTrustStore(String alias, Certificate[] certificates)
 
 100             throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
 
 101         KeyStore ks = getKeyStoreInstance();
 
 103         for (Certificate c : certificates) {
 
 104             ks.setCertificateEntry(alias + index++, c);
 
 109     private KeyStore getKeyStoreInstance()
 
 110             throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
 
 111         KeyStore ks = KeyStore.getInstance(keyStoreType);
 
 112         ks.load(EMPTY_KEYSTORE_CONFIGURATION);
 
 116     private Certificate[] convertToCertificateArray(List<String> certificates)
 
 117             throws PemConversionException {
 
 118         Certificate[] parsedCertificates = new Certificate[certificates.size()];
 
 119         for (String certificate : certificates) {
 
 120             parsedCertificates[certificates.indexOf(certificate)] = parseCertificate(certificate);
 
 122         return parsedCertificates;
 
 125     private Certificate parseCertificate(String certificate) throws PemConversionException {
 
 126         try (PEMParser pem = new PEMParser(new StringReader(certificate))) {
 
 127             X509CertificateHolder certHolder = Optional.ofNullable((X509CertificateHolder) pem.readObject())
 
 129                             () -> new PemConversionException("The certificate couldn't be parsed correctly. " + certificate));
 
 130             return new JcaX509CertificateConverter()
 
 131                     .setProvider(new BouncyCastleProvider())
 
 132                     .getCertificate(certHolder);
 
 133         } catch (IOException | CertificateException e) {
 
 134             LOGGER.error("Certificates conversion failed, exception message: {}", e.getMessage());
 
 135             throw new PemConversionException(e);