04216ff46ce0822fba61ec0adf9769214de3fb43
[oom/platform/cert-service.git] / certServiceClient / src / main / java / org / onap / oom / certservice / client / certification / CsrFactory.java
1 /*============LICENSE_START=======================================================
2  * oom-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.oom.certservice.client.certification;
21
22 import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.COMMON_NAME;
23 import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.COUNTRY;
24 import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.LOCATION;
25 import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.ORGANIZATION;
26 import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.ORGANIZATION_UNIT;
27 import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.SIGN_ALGORITHM;
28 import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.STATE;
29
30 import java.io.IOException;
31 import java.io.StringWriter;
32 import java.security.KeyPair;
33 import java.util.List;
34 import java.util.Optional;
35 import java.util.stream.Collectors;
36 import javax.security.auth.x500.X500Principal;
37 import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
38 import org.bouncycastle.asn1.x509.Extension;
39 import org.bouncycastle.asn1.x509.Extensions;
40 import org.bouncycastle.asn1.x509.ExtensionsGenerator;
41 import org.bouncycastle.asn1.x509.GeneralName;
42 import org.bouncycastle.asn1.x509.GeneralNames;
43 import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
44 import org.bouncycastle.operator.ContentSigner;
45 import org.bouncycastle.operator.OperatorCreationException;
46 import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
47 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
48 import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
49 import org.onap.oom.certservice.client.certification.exception.CsrGenerationException;
50 import org.onap.oom.certservice.client.configuration.model.CsrConfiguration;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54
55 public class CsrFactory {
56
57     private static final Logger LOGGER = LoggerFactory.getLogger(CsrFactory.class);
58     private final CsrConfiguration configuration;
59
60
61     public CsrFactory(CsrConfiguration configuration) {
62         this.configuration = configuration;
63     }
64
65
66     public String createCsrInPem(KeyPair keyPair) throws CsrGenerationException {
67         LOGGER.info("Creation of CSR has been started with following parameters: {}", configuration.toString());
68         String csrParameters = getMandatoryParameters().append(getOptionalParameters()).toString();
69         X500Principal subject = new X500Principal(csrParameters);
70         PKCS10CertificationRequest request = createPkcs10Csr(subject, keyPair);
71
72         LOGGER.info("Creation of CSR has been completed successfully");
73         return convertPkcs10CsrToPem(request);
74     }
75
76     private StringBuilder getMandatoryParameters() {
77         return new StringBuilder(String.format("%s=%s, %s=%s, %s=%s, %s=%s",
78             COMMON_NAME, configuration.getCommonName(),
79             COUNTRY, configuration.getCountry(),
80             STATE, configuration.getState(),
81             ORGANIZATION, configuration.getOrganization()));
82     }
83
84     private String getOptionalParameters() {
85         StringBuilder optionalParameters = new StringBuilder();
86         Optional.ofNullable(configuration.getOrganizationUnit())
87             .filter(CsrFactory::isParameterPresent)
88             .map(unit -> optionalParameters.append(String.format(", %s=%s", ORGANIZATION_UNIT, unit)));
89         Optional.ofNullable(configuration.getLocation())
90             .filter(CsrFactory::isParameterPresent)
91             .map(location -> optionalParameters.append(String.format(", %s=%s", LOCATION, location)));
92         return optionalParameters.toString();
93     }
94
95     private PKCS10CertificationRequest createPkcs10Csr(X500Principal subject, KeyPair keyPair)
96         throws CsrGenerationException {
97         JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject,
98             keyPair.getPublic());
99
100         if (!configuration.getSans().isEmpty()) {
101             builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, generateSansExtension());
102         }
103
104         return builder.build(getContentSigner(keyPair));
105     }
106
107     private ContentSigner getContentSigner(KeyPair keyPair) throws CsrGenerationException {
108         ContentSigner contentSigner;
109         try {
110             contentSigner = new JcaContentSignerBuilder(SIGN_ALGORITHM).build(keyPair.getPrivate());
111         } catch (OperatorCreationException e) {
112             LOGGER.error("Creation of PKCS10Csr failed, exception message: {}", e.getMessage());
113             throw new CsrGenerationException(e);
114
115         }
116         return contentSigner;
117     }
118
119     private String convertPkcs10CsrToPem(PKCS10CertificationRequest request) throws CsrGenerationException {
120         final StringWriter stringWriter = new StringWriter();
121         try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
122             LOGGER.info("Conversion of CSR to PEM has been started");
123             pemWriter.writeObject(request);
124         } catch (IOException e) {
125             LOGGER.error("Conversion to PEM failed, exception message: {}", e.getMessage());
126             throw new CsrGenerationException(e);
127         }
128         return stringWriter.toString();
129     }
130
131     private Extensions generateSansExtension() throws CsrGenerationException {
132         ExtensionsGenerator generator = new ExtensionsGenerator();
133         try {
134             generator.addExtension(Extension.subjectAlternativeName, false, createGeneralNames());
135         } catch (IOException e) {
136             LOGGER.error("Generation of SANs parameter failed, exception message: {}", e.getMessage());
137             throw new CsrGenerationException(e);
138         }
139         return generator.generate();
140     }
141
142     private GeneralNames createGeneralNames() {
143         List<String> sans = this.configuration.getSans();
144         GeneralName[] generalNames = sans.stream()
145             .map(san -> new GeneralName(GeneralName.dNSName, san))
146             .collect(Collectors.toList())
147             .toArray(GeneralName[]::new);
148         return new GeneralNames(generalNames);
149     }
150
151     private static Boolean isParameterPresent(String parameter) {
152         return parameter != null && !"".equals(parameter);
153     }
154 }