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