Remove CSRMeta class dependency
[oom/platform/cert-service.git] / certService / src / main / java / org / onap / aaf / certservice / certification / adapter / Cmpv2ClientAdapter.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Cert Service
4  * ================================================================================
5  * Copyright (C) 2020 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aaf.certservice.certification.adapter;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.StringWriter;
26 import java.security.NoSuchProviderException;
27 import java.security.PrivateKey;
28 import java.security.cert.CertificateException;
29 import java.security.cert.X509Certificate;
30 import java.util.List;
31 import java.util.stream.Collectors;
32
33 import org.bouncycastle.cert.X509CertificateHolder;
34 import org.bouncycastle.cert.X509v3CertificateBuilder;
35 import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator;
36 import org.bouncycastle.operator.ContentSigner;
37 import org.bouncycastle.operator.OperatorCreationException;
38 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
39 import org.bouncycastle.util.io.pem.PemObjectGenerator;
40 import org.bouncycastle.util.io.pem.PemWriter;
41 import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
42 import org.onap.aaf.certservice.certification.exception.Cmpv2ClientAdapterException;
43 import org.onap.aaf.certservice.certification.model.CertificationModel;
44 import org.onap.aaf.certservice.certification.model.CsrModel;
45 import org.onap.aaf.certservice.cmpv2client.api.CmpClient;
46 import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.stereotype.Component;
51
52 @Component
53 public class Cmpv2ClientAdapter {
54
55     private static final Logger LOGGER = LoggerFactory.getLogger(Cmpv2ClientAdapter.class);
56
57     private final CmpClient cmpClient;
58     private final RsaContentSignerBuilder rsaContentSignerBuilder;
59     private final X509CertificateBuilder x509CertificateBuilder;
60     private final CertificateFactoryProvider certificateFactoryProvider;
61
62     @Autowired
63     public Cmpv2ClientAdapter(CmpClient cmpClient, RsaContentSignerBuilder rsaContentSignerBuilder,
64                               X509CertificateBuilder x509CertificateBuilder,
65                               CertificateFactoryProvider certificateFactoryProvider) {
66         this.cmpClient = cmpClient;
67         this.rsaContentSignerBuilder = rsaContentSignerBuilder;
68         this.x509CertificateBuilder = x509CertificateBuilder;
69         this.certificateFactoryProvider = certificateFactoryProvider;
70     }
71
72     /**
73      * Uses CmpClient to call to Cmp Server and gather certificates data
74      *
75      * @param csrModel Certificate Signing Request from Service external  API
76      * @param server   Cmp Server configuration from cmpServers.json
77      * @return container for returned certificates
78      * @throws CmpClientException          Exceptions which comes from Cmp Client
79      * @throws Cmpv2ClientAdapterException Exceptions which comes from Adapter itself
80      */
81     public CertificationModel callCmpClient(CsrModel csrModel, Cmpv2Server server)
82             throws CmpClientException, Cmpv2ClientAdapterException {
83         List<List<X509Certificate>> certificates = cmpClient.createCertificate(server.getCaName(),
84                 server.getCaMode().getProfile(), csrModel, server,
85                 convertCsrToX509Certificate(csrModel.getCsr(), csrModel.getPrivateKey()));
86         return new CertificationModel(convertFromX509CertificateListToPemList(certificates.get(0)),
87                 convertFromX509CertificateListToPemList(certificates.get(1)));
88     }
89
90     private String convertFromX509CertificateToPem(X509Certificate certificate) {
91         StringWriter sw = new StringWriter();
92         try (PemWriter pw = new PemWriter(sw)) {
93             PemObjectGenerator gen = new JcaMiscPEMGenerator(certificate);
94             pw.writeObject(gen);
95         } catch (IOException e) {
96             LOGGER.error("Exception occurred during convert of X509 certificate", e);
97         }
98         return sw.toString();
99     }
100
101     private X509Certificate convertCsrToX509Certificate(PKCS10CertificationRequest csr, PrivateKey privateKey)
102             throws Cmpv2ClientAdapterException {
103         try {
104             X509v3CertificateBuilder certificateGenerator = x509CertificateBuilder.build(csr);
105             ContentSigner signer = rsaContentSignerBuilder.build(csr, privateKey);
106             X509CertificateHolder holder = certificateGenerator.build(signer);
107             return certificateFactoryProvider
108                     .generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded()));
109         } catch (IOException | CertificateException | OperatorCreationException | NoSuchProviderException e) {
110             throw new Cmpv2ClientAdapterException(e);
111         }
112     }
113
114     private List<String> convertFromX509CertificateListToPemList(List<X509Certificate> certificates) {
115         return certificates.stream().map(this::convertFromX509CertificateToPem).filter(cert -> !cert.isEmpty())
116                 .collect(Collectors.toList());
117     }
118
119 }