[OOM-CERT-SERVICE] Refactor CertService API code
[oom/platform/cert-service.git] / certService / src / main / java / org / onap / oom / certservice / certification / model / CsrModel.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Cert Service
4  * ================================================================================
5  * Copyright (C) 2020-2021 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.oom.certservice.certification.model;
22
23 import org.bouncycastle.asn1.x500.X500Name;
24 import org.bouncycastle.asn1.x509.Extension;
25 import org.bouncycastle.asn1.x509.Extensions;
26 import org.bouncycastle.asn1.x509.GeneralName;
27 import org.bouncycastle.asn1.x509.GeneralNames;
28 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
29 import org.bouncycastle.util.io.pem.PemObject;
30 import org.onap.oom.certservice.certification.exception.CsrDecryptionException;
31 import org.onap.oom.certservice.certification.exception.DecryptionException;
32 import org.onap.oom.certservice.certification.exception.KeyDecryptionException;
33
34 import java.io.IOException;
35 import java.security.KeyFactory;
36 import java.security.NoSuchAlgorithmException;
37 import java.security.PrivateKey;
38 import java.security.PublicKey;
39 import java.security.spec.InvalidKeySpecException;
40 import java.security.spec.X509EncodedKeySpec;
41 import java.util.Arrays;
42 import java.util.stream.Collectors;
43
44
45 public class CsrModel {
46
47     private final PKCS10CertificationRequest csr;
48     private final PrivateKey privateKey;
49     private final PublicKey publicKey;
50     private final CertificateData certificateData;
51
52     public CsrModel(PKCS10CertificationRequest csr, X500Name subjectData, PrivateKey privateKey, PublicKey publicKey,
53         GeneralName[] sans) {
54         this.csr = csr;
55         this.privateKey = privateKey;
56         this.publicKey = publicKey;
57         this.certificateData = new CertificateData(subjectData, sans);
58     }
59
60     public PKCS10CertificationRequest getCsr() {
61         return csr;
62     }
63
64     public X500Name getSubjectData() {
65         return certificateData.getSubject();
66     }
67
68     public PrivateKey getPrivateKey() {
69         return privateKey;
70     }
71
72     public PublicKey getPublicKey() {
73         return publicKey;
74     }
75
76     public GeneralName[] getSans() {
77         return certificateData.getSortedSans();
78     }
79
80     public CertificateData getCertificateData() {
81         return certificateData;
82     }
83
84     @Override
85     public String toString() {
86         return "CSR: { Subject: { " + certificateData.getSubject() + " }, SANs: [" + getSansInReadableFormat() + "] }";
87     }
88
89     private String getSansInReadableFormat() {
90         return Arrays.stream(this.certificateData.getSortedSans())
91             .map(generalName -> generalName.getName().toString())
92             .collect(Collectors.joining(", "));
93     }
94
95     public static class CsrModelBuilder {
96         private final PKCS10CertificationRequest csr;
97
98         private final PrivateKey privateKey;
99
100         public CsrModel build() throws DecryptionException {
101
102             X500Name subjectData = getSubjectData();
103             PublicKey javaPublicKey = convertingPemPublicKeyToJavaSecurityPublicKey(getPublicKey());
104             GeneralName[] sans = getSansData();
105
106             return new CsrModel(csr, subjectData, privateKey, javaPublicKey, sans);
107         }
108
109         public CsrModelBuilder(PKCS10CertificationRequest csr, PrivateKey privateKey) {
110             this.csr = csr;
111             this.privateKey = privateKey;
112         }
113
114         private PemObject getPublicKey() throws CsrDecryptionException {
115             try {
116                 return new PemObject("PUBLIC KEY", csr.getSubjectPublicKeyInfo().getEncoded());
117             } catch (IOException e) {
118                 throw new CsrDecryptionException("Reading Public Key from CSR failed", e.getCause());
119             }
120         }
121
122         private X500Name getSubjectData() {
123             return csr.getSubject();
124         }
125
126         private GeneralName[] getSansData() {
127             if (!isAttrsEmpty() && !isAttrsValuesEmpty()) {
128                 Extensions extensions = Extensions.getInstance(csr.getAttributes()[0].getAttrValues().getObjectAt(0));
129                 return GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName).getNames();
130             }
131             return new GeneralName[0];
132         }
133
134         private boolean isAttrsValuesEmpty() {
135             return csr.getAttributes()[0].getAttrValues().size() == 0;
136         }
137
138         private boolean isAttrsEmpty() {
139             return csr.getAttributes().length == 0;
140         }
141
142         private PublicKey convertingPemPublicKeyToJavaSecurityPublicKey(PemObject publicKey)
143             throws KeyDecryptionException {
144             try {
145                 KeyFactory factory = KeyFactory.getInstance("RSA");
146                 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey.getContent());
147                 return factory.generatePublic(keySpec);
148             } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
149                 throw new KeyDecryptionException("Converting Public Key from CSR failed", e.getCause());
150             }
151         }
152
153     }
154 }