Resolve all checkstyle warnings
authorBartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Wed, 18 Mar 2020 08:38:27 +0000 (09:38 +0100)
committerBartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Wed, 18 Mar 2020 08:38:27 +0000 (09:38 +0100)
Issue-ID: AAF-1107
Signed-off-by: Bartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Change-Id: I28cfc2b82f1a4800a984e30f59ff36fe90bebb38

64 files changed:
certService/checkstyle-suppressions.xml [new file with mode: 0644]
certService/pom.xml
certService/src/main/java/org/onap/aaf/certservice/CertServiceApplication.java
certService/src/main/java/org/onap/aaf/certservice/api/CertificationController.java
certService/src/main/java/org/onap/aaf/certservice/api/ReadinessController.java
certService/src/main/java/org/onap/aaf/certservice/api/ReloadConfigController.java
certService/src/main/java/org/onap/aaf/certservice/api/advice/CertificationExceptionAdvice.java
certService/src/main/java/org/onap/aaf/certservice/api/advice/ReloadConfigExceptionAdvice.java
certService/src/main/java/org/onap/aaf/certservice/api/configuration/OpenApiConfig.java
certService/src/main/java/org/onap/aaf/certservice/certification/CertificationData.java
certService/src/main/java/org/onap/aaf/certservice/certification/CsrModelFactory.java
certService/src/main/java/org/onap/aaf/certservice/certification/Pkcs10CertificationRequestFactory.java [moved from certService/src/main/java/org/onap/aaf/certservice/certification/PKCS10CertificationRequestFactory.java with 91% similarity]
certService/src/main/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapter.java
certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilder.java [moved from certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CSRMetaBuilder.java with 80% similarity]
certService/src/main/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilder.java [moved from certService/src/main/java/org/onap/aaf/certservice/certification/adapter/RSAContentSignerBuilder.java with 98% similarity]
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/CmpClientConfig.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigLoader.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/model/Authentication.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/model/CaMode.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/model/Cmpv2Server.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2Url.java [moved from certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2URL.java with 92% similarity]
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2UrlValidator.java [moved from certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2URLValidator.java with 76% similarity]
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/PortNumberViolation.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/RequestTypeViolation.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/UrlServerViolation.java [moved from certService/src/main/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/URLServerViolation.java with 96% similarity]
certService/src/main/java/org/onap/aaf/certservice/certification/exception/CsrDecryptionException.java
certService/src/main/java/org/onap/aaf/certservice/certification/exception/DecryptionException.java
certService/src/main/java/org/onap/aaf/certservice/certification/exception/KeyDecryptionException.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/api/CmpClient.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/exceptions/CmpClientException.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/exceptions/PkiErrorException.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/CsrMeta.java [moved from certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/CSRMeta.java with 96% similarity]
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/Factory.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/Rdn.java [moved from certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/RDN.java with 85% similarity]
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpClientImpl.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpMessageBuilder.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpMessageHelper.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpResponseHelper.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpResponseValidationHelper.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpUtil.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/Cmpv2HttpClient.java
certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CreateCertRequest.java
certService/src/test/java/org/onap/aaf/certservice/CertServiceApplicationTests.java
certService/src/test/java/org/onap/aaf/certservice/api/CertificationControllerTest.java
certService/src/test/java/org/onap/aaf/certservice/api/ReadinessControllerTest.java
certService/src/test/java/org/onap/aaf/certservice/api/ReloadConfigControllerTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/CertificationModelFactoryTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/CsrModelFactoryTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilderTest.java [moved from certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CSRMetaBuilderTest.java with 80% similarity]
certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilderTest.java [moved from certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RSAContentSignerBuilderTest.java with 93% similarity]
certService/src/test/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilderTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigLoaderTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/Cmpv2ServerProviderTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/Cmpv2ServerConfigurationValidatorTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2UrlValidatorTest.java [moved from certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2URLValidatorTest.java with 69% similarity]
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/PortNumberViolationTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/RequestTypeViolationTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/model/CsrModelTest.java
certService/src/test/java/org/onap/aaf/certservice/cmpv2Client/Cmpv2ClientTest.java [deleted file]
certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java [new file with mode: 0644]
certService/src/test/java/org/onap/aaf/certservice/cmpv2client/external/RdnTest.java [moved from certService/src/test/java/org/onap/aaf/certservice/cmpv2client/external/RDNTest.java with 83% similarity]

diff --git a/certService/checkstyle-suppressions.xml b/certService/checkstyle-suppressions.xml
new file mode 100644 (file)
index 0000000..8b530a0
--- /dev/null
@@ -0,0 +1,32 @@
+<?xml version="1.0"?>
+<!--
+    ============LICENSE_START=======================================================
+    Copyright (C) 2020 Nokia. All rights reserved.
+    ================================================================================
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+         http://www.apache.org/licenses/LICENSE-2.0
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+    SPDX-License-Identifier: Apache-2.0
+    ============LICENSE_END=========================================================
+-->
+
+<!DOCTYPE suppressions PUBLIC
+        "-//Checkstyle//DTD SuppressionFilter Configuration 1.0//EN"
+        "https://checkstyle.org/dtds/suppressions_1_0.dtd">
+
+<suppressions>
+    <suppress checks="javadoc" files="\.java"/>
+    <suppress checks="LineLength" files="\.java"/>
+    <suppress checks="HiddenField" files="\.java"/>
+    <suppress checks="FinalParameters" files="\.java"/>
+    <suppress checks="DesignForExtension" files="\.java"/>
+    <suppress checks="CustomImportOrder" files="\.java"/>
+    <suppress checks="Indentation" files="\.java"/>
+    <suppress checks="HideUtilityClassConstructor" files="CertServiceApplication.java"/>
+</suppressions>
index c61501b..eebc004 100644 (file)
 
     <build>
         <plugins>
+            <plugin>
+                <artifactId>maven-checkstyle-plugin</artifactId>
+                <configuration>
+                    <suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation>
+                </configuration>
+            </plugin>
+
             <plugin>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-maven-plugin</artifactId>
index 087cf25..1147896 100644 (file)
@@ -25,7 +25,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.context.annotation.PropertySource;
 
 @SpringBootApplication
-@PropertySource(value={"classpath:application.properties"})
+@PropertySource(value = {"classpath:application.properties"})
 public class CertServiceApplication {
 
     // We are excluding this line in Sonar due to fact that
index fe941f5..74f6406 100644 (file)
@@ -60,9 +60,8 @@ public class CertificationController {
     /**
      * Request for signing certificate by given CA.
      *
-     *
-     * @param caName the name of Certification Authority that will sign root certificate
-     * @param encodedCsr Certificate Sign Request encoded in Base64 form
+     * @param caName            the name of Certification Authority that will sign root certificate
+     * @param encodedCsr        Certificate Sign Request encoded in Base64 form
      * @param encodedPrivateKey Private key for CSR, needed for PoP, encoded in Base64 form
      * @return JSON containing trusted certificates and certificate chain
      */
@@ -79,13 +78,13 @@ public class CertificationController {
     @Operation(
             summary = "sign certificate",
             description = "Web endpoint for requesting certificate signing. Used by system components to gain certificate signed by CA.",
-            tags = { "CertificationService" })
+            tags = {"CertificationService"})
     public ResponseEntity<CertificationModel> signCertificate(
-            @Parameter(description="Name of certification authority that will sign CSR.")
+            @Parameter(description = "Name of certification authority that will sign CSR.")
             @PathVariable String caName,
-            @Parameter(description="Certificate signing request in form of PEM object encoded in Base64 (with header and footer).")
+            @Parameter(description = "Certificate signing request in form of PEM object encoded in Base64 (with header and footer).")
             @RequestHeader("CSR") String encodedCsr,
-            @Parameter(description="Private key in form of PEM object encoded in Base64 (with header and footer).")
+            @Parameter(description = "Private key in form of PEM object encoded in Base64 (with header and footer).")
             @RequestHeader("PK") String encodedPrivateKey
     ) throws DecryptionException, CmpClientException, Cmpv2ClientAdapterException {
         caName = caName.replaceAll("[\n|\r|\t]", "_");
index 288957c..f900edf 100644 (file)
@@ -33,7 +33,7 @@ import org.springframework.web.bind.annotation.RestController;
 
 @RestController
 @Tag(name = "CertificationService")
-public class ReadinessController {
+public final class ReadinessController {
 
     private final CmpServersConfig cmpServersConfig;
 
@@ -50,7 +50,7 @@ public class ReadinessController {
     @Operation(
             summary = "check is container is ready",
             description = "Web endpoint for checking if service is ready to be used.",
-            tags = { "CertificationService" })
+            tags = {"CertificationService"})
     public ResponseEntity<String> checkReady() {
         if (cmpServersConfig.isReady()) {
             return new ResponseEntity<>(HttpStatus.OK);
index c52cf4f..e812ce0 100644 (file)
@@ -37,7 +37,7 @@ import org.springframework.web.bind.annotation.RestController;
 
 @RestController
 @Tag(name = "CertificationService")
-public class ReloadConfigController {
+public final class ReloadConfigController {
 
     private final CmpServersConfig cmpServersConfig;
 
@@ -55,7 +55,7 @@ public class ReloadConfigController {
     @Operation(
             summary = "reload service configuration from file",
             description = "Web endpoint for performing configuration reload. Used to reload configuration file from file.",
-            tags = { "CertificationService" })
+            tags = {"CertificationService"})
     public ResponseEntity<String> reloadConfiguration() throws CmpServersConfigLoadingException {
         cmpServersConfig.reloadConfiguration();
         return new ResponseEntity<>(HttpStatus.OK);
index f75e93c..a40fea8 100644 (file)
@@ -35,7 +35,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.RestControllerAdvice;
 
 @RestControllerAdvice(assignableTypes = CertificationController.class)
-public class CertificationExceptionAdvice {
+public final class CertificationExceptionAdvice {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(CertificationExceptionAdvice.class);
 
@@ -92,7 +92,7 @@ public class CertificationExceptionAdvice {
     private ResponseEntity<ErrorResponseModel> getErrorResponseEntity(String errorMessage, HttpStatus status) {
         ErrorResponseModel errorResponse = new ErrorResponseModel(errorMessage);
         return new ResponseEntity<>(
-               errorResponse,
+                errorResponse,
                 status
         );
     }
index bf83ece..4a4073f 100644 (file)
@@ -30,7 +30,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.RestControllerAdvice;
 
 @RestControllerAdvice(assignableTypes = ReloadConfigController.class)
-public class ReloadConfigExceptionAdvice {
+public final class ReloadConfigExceptionAdvice {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(ReloadConfigExceptionAdvice.class);
 
index 1832704..503b281 100644 (file)
@@ -30,7 +30,7 @@ import org.springframework.context.annotation.Configuration;
 public class OpenApiConfig {
 
     @Bean
-    public OpenAPI customOpenAPI() {
+    public OpenAPI customOpenApi() {
         return new OpenAPI()
                 .components(new Components())
                 .info(
index a347762..bce7297 100644 (file)
@@ -23,7 +23,8 @@ package org.onap.aaf.certservice.certification;
 
 final class CertificationData {
 
-    private CertificationData() {}
+    private CertificationData() {
+    }
 
     private static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n";
     private static final String END_CERTIFICATE = "-----END CERTIFICATE-----";
index 501ed6d..b4f94b9 100644 (file)
@@ -40,8 +40,8 @@ public class CsrModelFactory {
 
     private final PemObjectFactory pemObjectFactory
             = new PemObjectFactory();
-    private final PKCS10CertificationRequestFactory certificationRequestFactory
-            = new PKCS10CertificationRequestFactory();
+    private final Pkcs10CertificationRequestFactory certificationRequestFactory
+            = new Pkcs10CertificationRequestFactory();
 
 
     public CsrModel createCsrModel(StringBase64 csr, StringBase64 privateKey)
@@ -57,15 +57,15 @@ public class CsrModelFactory {
         return privateKey.asString()
                 .flatMap(pemObjectFactory::createPemObject)
                 .orElseThrow(
-                () -> new KeyDecryptionException("Incorrect Key, decryption failed")
-        );
+                        () -> new KeyDecryptionException("Incorrect Key, decryption failed")
+                );
     }
 
     private PKCS10CertificationRequest decodeCsr(StringBase64 csr)
             throws CsrDecryptionException {
         return csr.asString()
                 .flatMap(pemObjectFactory::createPemObject)
-                .flatMap(certificationRequestFactory::createKCS10CertificationRequest)
+                .flatMap(certificationRequestFactory::createPkcs10CertificationRequest)
                 .orElseThrow(
                         () -> new CsrDecryptionException("Incorrect CSR, decryption failed")
                 );
@@ -84,20 +84,28 @@ public class CsrModelFactory {
             try {
                 String decodedString = new String(decoder.decode(value));
                 return Optional.of(decodedString);
-            } catch(RuntimeException e) {
+            } catch (RuntimeException e) {
                 LOGGER.error("Exception occurred during decoding:", e);
                 return Optional.empty();
             }
         }
 
         @Override
-        public boolean equals(Object o) {
-            if (this == o) return true;
-            if (o == null || getClass() != o.getClass()) return false;
-            StringBase64 that = (StringBase64) o;
+        public boolean equals(Object otherObject) {
+            if (this == otherObject) {
+                return true;
+            }
+            if (otherObject == null || getClass() != otherObject.getClass()) {
+                return false;
+            }
+            StringBase64 that = (StringBase64) otherObject;
             return Objects.equals(value, that.value);
         }
 
+        @Override
+        public int hashCode() {
+            return value.hashCode();
+        }
     }
 
 }
@@ -29,11 +29,11 @@ import org.slf4j.LoggerFactory;
 import java.io.IOException;
 import java.util.Optional;
 
-public class PKCS10CertificationRequestFactory {
+public class Pkcs10CertificationRequestFactory {
 
-    private static final Logger LOGGER = LoggerFactory.getLogger(PKCS10CertificationRequestFactory.class);
+    private static final Logger LOGGER = LoggerFactory.getLogger(Pkcs10CertificationRequestFactory.class);
 
-    public Optional<PKCS10CertificationRequest>  createKCS10CertificationRequest(PemObject pemObject) {
+    public Optional<PKCS10CertificationRequest> createPkcs10CertificationRequest(PemObject pemObject) {
         try {
             LOGGER.debug("Creating certification request from pem object");
             return Optional.of(new PKCS10CertificationRequest(pemObject.getContent()));
index be39f1f..c9e61b0 100644 (file)
@@ -54,15 +54,15 @@ public class Cmpv2ClientAdapter {
     private static final Logger LOGGER = LoggerFactory.getLogger(Cmpv2ClientAdapter.class);
 
     private final CmpClient cmpClient;
-    private final CSRMetaBuilder csrMetaBuilder;
-    private final RSAContentSignerBuilder rsaContentSignerBuilder;
+    private final CsrMetaBuilder csrMetaBuilder;
+    private final RsaContentSignerBuilder rsaContentSignerBuilder;
     private final X509CertificateBuilder x509CertificateBuilder;
     private final CertificateFactoryProvider certificateFactoryProvider;
 
     @Autowired
-    public Cmpv2ClientAdapter(CmpClient cmpClient, CSRMetaBuilder csrMetaBuilder,
-            RSAContentSignerBuilder rsaContentSignerBuilder, X509CertificateBuilder x509CertificateBuilder,
-            CertificateFactoryProvider certificateFactoryProvider) {
+    public Cmpv2ClientAdapter(CmpClient cmpClient, CsrMetaBuilder csrMetaBuilder,
+                              RsaContentSignerBuilder rsaContentSignerBuilder, X509CertificateBuilder x509CertificateBuilder,
+                              CertificateFactoryProvider certificateFactoryProvider) {
         this.cmpClient = cmpClient;
         this.csrMetaBuilder = csrMetaBuilder;
         this.rsaContentSignerBuilder = rsaContentSignerBuilder;
@@ -83,12 +83,12 @@ public class Cmpv2ClientAdapter {
             throws CmpClientException, Cmpv2ClientAdapterException {
         List<List<X509Certificate>> certificates = cmpClient.createCertificate(server.getCaName(),
                 server.getCaMode().getProfile(), csrMetaBuilder.build(csrModel, server),
-                convertCSRToX509Certificate(csrModel.getCsr(), csrModel.getPrivateKey()));
-        return new CertificationModel(convertFromX509CertificateListToPEMList(certificates.get(0)),
-                convertFromX509CertificateListToPEMList(certificates.get(1)));
+                convertCsrToX509Certificate(csrModel.getCsr(), csrModel.getPrivateKey()));
+        return new CertificationModel(convertFromX509CertificateListToPemList(certificates.get(0)),
+                convertFromX509CertificateListToPemList(certificates.get(1)));
     }
 
-    private String convertFromX509CertificateToPEM(X509Certificate certificate) {
+    private String convertFromX509CertificateToPem(X509Certificate certificate) {
         StringWriter sw = new StringWriter();
         try (PemWriter pw = new PemWriter(sw)) {
             PemObjectGenerator gen = new JcaMiscPEMGenerator(certificate);
@@ -99,7 +99,7 @@ public class Cmpv2ClientAdapter {
         return sw.toString();
     }
 
-    private X509Certificate convertCSRToX509Certificate(PKCS10CertificationRequest csr, PrivateKey privateKey)
+    private X509Certificate convertCsrToX509Certificate(PKCS10CertificationRequest csr, PrivateKey privateKey)
             throws Cmpv2ClientAdapterException {
         try {
             X509v3CertificateBuilder certificateGenerator = x509CertificateBuilder.build(csr);
@@ -112,8 +112,8 @@ public class Cmpv2ClientAdapter {
         }
     }
 
-    private List<String> convertFromX509CertificateListToPEMList(List<X509Certificate> certificates) {
-        return certificates.stream().map(this::convertFromX509CertificateToPEM).filter(cert -> !cert.isEmpty())
+    private List<String> convertFromX509CertificateListToPemList(List<X509Certificate> certificates) {
+        return certificates.stream().map(this::convertFromX509CertificateToPem).filter(cert -> !cert.isEmpty())
                        .collect(Collectors.toList());
     }
 
@@ -31,16 +31,16 @@ import org.bouncycastle.asn1.x500.style.IETFUtils;
 import org.bouncycastle.cert.CertException;
 import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
 import org.onap.aaf.certservice.certification.model.CsrModel;
-import org.onap.aaf.certservice.cmpv2client.external.CSRMeta;
-import org.onap.aaf.certservice.cmpv2client.external.RDN;
+import org.onap.aaf.certservice.cmpv2client.external.CsrMeta;
+import org.onap.aaf.certservice.cmpv2client.external.Rdn;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
 @Component
-class CSRMetaBuilder {
+class CsrMetaBuilder {
 
-    private static final Logger LOGGER = LoggerFactory.getLogger(CSRMetaBuilder.class);
+    private static final Logger LOGGER = LoggerFactory.getLogger(CsrMetaBuilder.class);
 
     /**
      * Creates CSRMeta from CsrModel and Cmpv2Server
@@ -49,8 +49,8 @@ class CSRMetaBuilder {
      * @param server   Cmp Server configuration from cmpServers.json
      * @return AAF native model  for CSR metadata
      */
-    CSRMeta build(CsrModel csrModel, Cmpv2Server server) {
-        CSRMeta csrMeta = createCsrMeta(csrModel);
+    CsrMeta build(CsrModel csrModel, Cmpv2Server server) {
+        CsrMeta csrMeta = createCsrMeta(csrModel);
         addSans(csrModel, csrMeta);
         csrMeta.setKeyPair(new KeyPair(csrModel.getPublicKey(), csrModel.getPrivateKey()));
         csrMeta.setPassword(server.getAuthentication().getIak());
@@ -61,30 +61,30 @@ class CSRMetaBuilder {
         return csrMeta;
     }
 
-    private CSRMeta createCsrMeta(CsrModel csrModel) {
-        return new CSRMeta((Arrays.stream(csrModel.getSubjectData().getRDNs()).map(this::convertFromBcRDN)
+    private CsrMeta createCsrMeta(CsrModel csrModel) {
+        return new CsrMeta((Arrays.stream(csrModel.getSubjectData().getRDNs()).map(this::convertFromBcRdn)
                                     .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList())));
     }
 
-    private void addSans(CsrModel csrModel, CSRMeta csrMeta) {
+    private void addSans(CsrModel csrModel, CsrMeta csrMeta) {
         csrModel.getSans().forEach(csrMeta::addSan);
     }
 
-    private Optional<RDN> convertFromBcRDN(org.bouncycastle.asn1.x500.RDN rdn) {
-        RDN result = null;
+    private Optional<Rdn> convertFromBcRdn(org.bouncycastle.asn1.x500.RDN rdn) {
+        Rdn result = null;
         try {
-            result = convertRDN(rdn);
+            result = convertRdn(rdn);
         } catch (CertException e) {
             LOGGER.error("Exception occurred during convert of RDN", e);
         }
         return Optional.ofNullable(result);
     }
 
-    private RDN convertRDN(org.bouncycastle.asn1.x500.RDN rdn) throws CertException {
+    private Rdn convertRdn(org.bouncycastle.asn1.x500.RDN rdn) throws CertException {
         AttributeTypeAndValue rdnData = rdn.getFirst();
         String tag = BCStyle.INSTANCE.oidToDisplayName(rdnData.getType());
         String value = IETFUtils.valueToString(rdnData.getValue());
-        return new RDN(tag, value);
+        return new Rdn(tag, value);
     }
 
 }
@@ -17,6 +17,7 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
+
 package org.onap.aaf.certservice.certification.adapter;
 
 import java.io.IOException;
@@ -31,7 +32,7 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequest;
 import org.springframework.stereotype.Component;
 
 @Component
-public class RSAContentSignerBuilder {
+public class RsaContentSignerBuilder {
 
     ContentSigner build(PKCS10CertificationRequest csr, PrivateKey privateKey)
             throws IOException, OperatorCreationException {
index 21b873e..329098a 100644 (file)
@@ -17,6 +17,7 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
+
 package org.onap.aaf.certservice.certification.configuration;
 
 import org.apache.http.impl.client.CloseableHttpClient;
@@ -31,18 +32,18 @@ import org.springframework.web.context.annotation.RequestScope;
 public class CmpClientConfig {
 
     @Bean
-    CmpClient cmpClient(CloseableHttpClient closeableHttpClient){
+    CmpClient cmpClient(CloseableHttpClient closeableHttpClient) {
         return new CmpClientImpl(closeableHttpClient);
     }
 
     @Bean
     @RequestScope
-    CloseableHttpClient closeableHttpClient(HttpClientBuilder httpClientBuilder){
+    CloseableHttpClient closeableHttpClient(HttpClientBuilder httpClientBuilder) {
         return httpClientBuilder.build();
     }
 
     @Bean
-    HttpClientBuilder httpClientBuilder(){
+    HttpClientBuilder httpClientBuilder() {
         return HttpClientBuilder.create();
     }
 
index 1072d63..696ae56 100644 (file)
@@ -40,7 +40,7 @@ class CmpServersConfigLoader {
     private final Cmpv2ServerConfigurationValidator validator;
 
     @Autowired
-    public CmpServersConfigLoader(Cmpv2ServerConfigurationValidator validator) {
+    CmpServersConfigLoader(Cmpv2ServerConfigurationValidator validator) {
         this.validator = validator;
     }
 
index 3785cf8..e4c1551 100644 (file)
@@ -25,11 +25,13 @@ import org.hibernate.validator.constraints.Length;
 
 public class Authentication {
 
+    private static final int MAX_IAK_RV_LENGTH = 256;
+
     @NotNull
-    @Length(min = 1, max = 256)
+    @Length(min = 1, max = MAX_IAK_RV_LENGTH)
     private String iak;
     @NotNull
-    @Length(min = 1, max = 256)
+    @Length(min = 1, max = MAX_IAK_RV_LENGTH)
     private String rv;
 
     public String getIak() {
@@ -50,9 +52,9 @@ public class Authentication {
 
     @Override
     public String toString() {
-        return "Authentication{" +
-                "  iak=*****" +
-                ", rv=*****" +
-                '}';
+        return "Authentication{"
+                + "  iak=*****"
+                + ", rv=*****"
+                '}';
     }
 }
index 20b83b8..51d9196 100644 (file)
@@ -22,23 +22,26 @@ package org.onap.aaf.certservice.certification.configuration.model;
 
 import javax.validation.Valid;
 import javax.validation.constraints.NotNull;
+
 import org.bouncycastle.asn1.x500.X500Name;
 import org.hibernate.validator.constraints.Length;
-import org.onap.aaf.certservice.certification.configuration.validation.constraints.Cmpv2URL;
+import org.onap.aaf.certservice.certification.configuration.validation.constraints.Cmpv2Url;
 
 public class Cmpv2Server {
 
+    private static final int MAX_CA_NAME_LENGTH = 128;
+
     @NotNull
     @Valid
     private Authentication authentication;
     @NotNull
     private CaMode caMode;
     @NotNull
-    @Length(min = 1, max = 128)
+    @Length(min = 1, max = MAX_CA_NAME_LENGTH)
     private String caName;
     @NotNull
     private X500Name issuerDN;
-    @Cmpv2URL
+    @Cmpv2Url
     private String url;
 
     public Authentication getAuthentication() {
@@ -83,13 +86,13 @@ public class Cmpv2Server {
 
     @Override
     public String toString() {
-        return "Cmpv2Server{" +
-                "authentication=" + authentication +
-                ", caMode=" + caMode +
-                ", caName='" + caName + '\'' +
-                ", issuerDN='" + issuerDN + '\'' +
-                ", url='" + url + '\'' +
-                '}';
+        return "Cmpv2Server{"
+                + "authentication=" + authentication
+                + ", caMode=" + caMode
+                + ", caName='" + caName + '\''
+                + ", issuerDN='" + issuerDN + '\''
+                + ", url='" + url + '\''
+                '}';
     }
 
 }
@@ -29,11 +29,13 @@ import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
 import static java.lang.annotation.ElementType.FIELD;
 import static java.lang.annotation.RetentionPolicy.RUNTIME;
 
-@Target( { FIELD, ANNOTATION_TYPE })
+@Target({FIELD, ANNOTATION_TYPE})
 @Retention(RUNTIME)
-@Constraint(validatedBy = Cmpv2URLValidator.class)
-public @interface Cmpv2URL {
+@Constraint(validatedBy = Cmpv2UrlValidator.class)
+public @interface Cmpv2Url {
     String message() default "Server URL is invalid.";
+
     Class<?>[] groups() default {};
+
     Class<? extends Payload>[] payload() default {};
 }
@@ -23,7 +23,7 @@ package org.onap.aaf.certservice.certification.configuration.validation.constrai
 
 import org.onap.aaf.certservice.certification.configuration.validation.constraints.violations.PortNumberViolation;
 import org.onap.aaf.certservice.certification.configuration.validation.constraints.violations.RequestTypeViolation;
-import org.onap.aaf.certservice.certification.configuration.validation.constraints.violations.URLServerViolation;
+import org.onap.aaf.certservice.certification.configuration.validation.constraints.violations.UrlServerViolation;
 
 import javax.validation.ConstraintValidator;
 import javax.validation.ConstraintValidatorContext;
@@ -31,25 +31,25 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicBoolean;
 
-class Cmpv2URLValidator implements ConstraintValidator<Cmpv2URL, String> {
+class Cmpv2UrlValidator implements ConstraintValidator<Cmpv2Url, String> {
 
-   private final List<URLServerViolation> violations;
+    private final List<UrlServerViolation> violations;
 
-   public Cmpv2URLValidator() {
+    Cmpv2UrlValidator() {
       this.violations = Arrays.asList(
               new PortNumberViolation(),
               new RequestTypeViolation()
       );
    }
 
-   @Override
-   public boolean isValid(String url, ConstraintValidatorContext context) {
-      AtomicBoolean isValid = new AtomicBoolean(true);
-      violations.forEach(violation -> {
-         if (!violation.validate(url)) {
-            isValid.set(false);
-         }
-      });
-      return isValid.get();
-   }
+    @Override
+    public boolean isValid(String url, ConstraintValidatorContext context) {
+        AtomicBoolean isValid = new AtomicBoolean(true);
+        violations.forEach(violation -> {
+            if (!violation.validate(url)) {
+                isValid.set(false);
+            }
+        });
+        return isValid.get();
+    }
 }
index acde041..96f3014 100644 (file)
@@ -23,7 +23,7 @@ package org.onap.aaf.certservice.certification.configuration.validation.constrai
 import java.net.MalformedURLException;
 import java.net.URL;
 
-public class PortNumberViolation implements URLServerViolation {
+public class PortNumberViolation implements UrlServerViolation {
 
     private static final int MIN_PORT = 1;
     private static final int MAX_PORT = 65535;
index 7fbbdf3..67a5c3c 100644 (file)
@@ -27,9 +27,9 @@ import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicBoolean;
 
-public class RequestTypeViolation implements URLServerViolation {
+public class RequestTypeViolation implements UrlServerViolation {
 
-    private final static List<String> VALID_REQUESTS = Collections.singletonList("http");
+    private static final List<String> VALID_REQUESTS = Collections.singletonList("http");
 
     @Override
     public boolean validate(String serverUrl) {
index 0bb4625..ed434e0 100644 (file)
@@ -24,6 +24,7 @@ public class CsrDecryptionException extends DecryptionException {
     public CsrDecryptionException(String message, Throwable cause) {
         super(message, cause);
     }
+
     public CsrDecryptionException(String message) {
         super(message);
     }
index ee0fb20..6d8f707 100644 (file)
 package org.onap.aaf.certservice.certification.exception;
 
 public class DecryptionException extends Exception {
+
     public DecryptionException(String message, Throwable cause) {
         super(message, cause);
     }
+
     public DecryptionException(String message) {
         super(message);
     }
+
 }
index 7970c39..d4814d6 100644 (file)
@@ -24,6 +24,7 @@ public class KeyDecryptionException extends DecryptionException {
     public KeyDecryptionException(String message, Throwable cause) {
         super(message, cause);
     }
+
     public KeyDecryptionException(String message) {
         super(message);
     }
index 150f15d..8f9d20b 100644 (file)
@@ -23,8 +23,9 @@ package org.onap.aaf.certservice.cmpv2client.api;
 import java.security.cert.X509Certificate;
 import java.util.Date;
 import java.util.List;
+
 import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
-import org.onap.aaf.certservice.cmpv2client.external.CSRMeta;
+import org.onap.aaf.certservice.cmpv2client.external.CsrMeta;
 
 /**
  * This class represent CmpV2Client Interface for obtaining X.509 Digital Certificates in a Public
@@ -33,53 +34,53 @@ import org.onap.aaf.certservice.cmpv2client.external.CSRMeta;
  */
 public interface CmpClient {
 
-  /**
-   * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped
-   * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using
-   * IAK/RV, Verification of the signature (proof-of-possession) on the request is performed and an
-   * Exception thrown if verification fails or issue encountered in fetching certificate from CA.
-   *
-   * @param caName Information about the External Root Certificate Authority (CA) performing the
-   *     event CA Name. Could be {@code null}.
-   * @param profile Profile on CA server Client/RA Mode configuration on Server. Could be {@code
-   *     null}.
-   * @param csrMeta Certificate Signing Request Meta Data. Must not be {@code null}.
-   * @param csr Certificate Signing Request {.cer} file. Must not be {@code null}.
-   * @param notBefore An optional validity to set in the created certificate, Certificate not valid
-   *     before this date.
-   * @param notAfter An optional validity to set in the created certificate, Certificate not valid
-   *     after this date.
-   * @return {@link X509Certificate} The newly created Certificate.
-   * @throws CmpClientException if client error occurs.
-   */
-  List<List<X509Certificate>> createCertificate(
-      String caName,
-      String profile,
-      CSRMeta csrMeta,
-      X509Certificate csr,
-      Date notBefore,
-      Date notAfter)
-      throws CmpClientException;
+    /**
+     * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped
+     * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using
+     * IAK/RV, Verification of the signature (proof-of-possession) on the request is performed and an
+     * Exception thrown if verification fails or issue encountered in fetching certificate from CA.
+     *
+     * @param caName    Information about the External Root Certificate Authority (CA) performing the
+     *                  event CA Name. Could be {@code null}.
+     * @param profile   Profile on CA server Client/RA Mode configuration on Server. Could be {@code
+     *                  null}.
+     * @param csrMeta   Certificate Signing Request Meta Data. Must not be {@code null}.
+     * @param csr       Certificate Signing Request {.cer} file. Must not be {@code null}.
+     * @param notBefore An optional validity to set in the created certificate, Certificate not valid
+     *                  before this date.
+     * @param notAfter  An optional validity to set in the created certificate, Certificate not valid
+     *                  after this date.
+     * @return {@link X509Certificate} The newly created Certificate.
+     * @throws CmpClientException if client error occurs.
+     */
+    List<List<X509Certificate>> createCertificate(
+            String caName,
+            String profile,
+            CsrMeta csrMeta,
+            X509Certificate csr,
+            Date notBefore,
+            Date notAfter)
+            throws CmpClientException;
 
-  /**
-   * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped
-   * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using
-   * IAK/RV, Verification of the signature (proof-of-possession) on the request is performed and an
-   * Exception thrown if verification fails or issue encountered in fetching certificate from CA.
-   *
-   * @param caName Information about the External Root Certificate Authority (CA) performing the
-   *     event CA Name. Could be {@code null}.
-   * @param profile Profile on CA server Client/RA Mode configuration on Server. Could be {@code
-   *     null}.
-   * @param csrMeta Certificate Signing Request Meta Data. Must not be {@code null}.
-   * @param csr Certificate Signing Request {.cer} file. Must not be {@code null}.
-   * @return {@link X509Certificate} The newly created Certificate.
-   * @throws CmpClientException if client error occurs.
-   */
-  List<List<X509Certificate>> createCertificate(
-      String caName,
-      String profile,
-      CSRMeta csrMeta,
-      X509Certificate csr)
-      throws CmpClientException;
+    /**
+     * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped
+     * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using
+     * IAK/RV, Verification of the signature (proof-of-possession) on the request is performed and an
+     * Exception thrown if verification fails or issue encountered in fetching certificate from CA.
+     *
+     * @param caName  Information about the External Root Certificate Authority (CA) performing the
+     *                event CA Name. Could be {@code null}.
+     * @param profile Profile on CA server Client/RA Mode configuration on Server. Could be {@code
+     *                null}.
+     * @param csrMeta Certificate Signing Request Meta Data. Must not be {@code null}.
+     * @param csr     Certificate Signing Request {.cer} file. Must not be {@code null}.
+     * @return {@link X509Certificate} The newly created Certificate.
+     * @throws CmpClientException if client error occurs.
+     */
+    List<List<X509Certificate>> createCertificate(
+            String caName,
+            String profile,
+            CsrMeta csrMeta,
+            X509Certificate csr)
+            throws CmpClientException;
 }
index 06bdfd8..2a04306 100644 (file)
 
 package org.onap.aaf.certservice.cmpv2client.exceptions;
 
-/** The CmpClientException wraps all exceptions occur internally to Cmpv2Client Api code. */
+/**
+ * The CmpClientException wraps all exceptions occur internally to Cmpv2Client Api code.
+ */
 public class CmpClientException extends Exception {
 
-  private static final long serialVersionUID = 1L;
+    private static final long serialVersionUID = 1L;
 
-  /** Creates a new instance with detail message. */
-  public CmpClientException(String message) {
-    super(message);
-  }
+    /**
+     * Creates a new instance with detail message.
+     */
+    public CmpClientException(String message) {
+        super(message);
+    }
 
-  /** Creates a new instance with detail Throwable cause. */
-  public CmpClientException(Throwable cause) {
-    super(cause);
-  }
+    /**
+     * Creates a new instance with detail Throwable cause.
+     */
+    public CmpClientException(Throwable cause) {
+        super(cause);
+    }
 
-  /** Creates a new instance with detail message and Throwable cause. */
-  public CmpClientException(String message, Throwable cause) {
-    super(message, cause);
-  }
+    /**
+     * Creates a new instance with detail message and Throwable cause.
+     */
+    public CmpClientException(String message, Throwable cause) {
+        super(message, cause);
+    }
 }
index 9e6b928..62411fb 100644 (file)
@@ -22,20 +22,26 @@ package org.onap.aaf.certservice.cmpv2client.exceptions;
 
 public class PkiErrorException extends Exception {
 
-  private static final long serialVersionUID = 1L;
+    private static final long serialVersionUID = 1L;
 
-  /** Creates a new instance with detail message. */
-  public PkiErrorException(String message) {
-    super(message);
-  }
+    /**
+     * Creates a new instance with detail message.
+     */
+    public PkiErrorException(String message) {
+        super(message);
+    }
 
-  /** Creates a new instance with detail Throwable cause. */
-  public PkiErrorException(Throwable cause) {
-    super(cause);
-  }
+    /**
+     * Creates a new instance with detail Throwable cause.
+     */
+    public PkiErrorException(Throwable cause) {
+        super(cause);
+    }
 
-  /** Creates a new instance with detail message and Throwable cause. */
-  public PkiErrorException(String message, Throwable cause) {
-    super(message, cause);
-  }
+    /**
+     * Creates a new instance with detail message and Throwable cause.
+     */
+    public PkiErrorException(String message, Throwable cause) {
+        super(message, cause);
+    }
 }
  * ============LICENSE_END====================================================
  *
  */
+
 package org.onap.aaf.certservice.cmpv2client.external;
 
 import java.security.KeyPair;
 import java.util.ArrayList;
 import java.util.List;
+
 import org.bouncycastle.asn1.x500.X500Name;
 import org.bouncycastle.asn1.x500.X500NameBuilder;
 import org.bouncycastle.asn1.x500.style.BCStyle;
 import org.bouncycastle.asn1.x509.Certificate;
 
-public class CSRMeta {
+public class CsrMeta {
 
     private String cn;
     private String mechID;
@@ -41,7 +43,7 @@ public class CSRMeta {
     private String issuerEmail;
     private String password;
     private String caUrl;
-    private List<RDN> rdns;
+    private List<Rdn> rdns;
     private ArrayList<String> sanList = new ArrayList<>();
     private KeyPair keyPair;
     private X500Name name;
@@ -49,7 +51,7 @@ public class CSRMeta {
     private Certificate certificate;
     private String senderKid;
 
-    public CSRMeta(List<RDN> rdns) {
+    public CsrMeta(List<Rdn> rdns) {
         this.rdns = rdns;
     }
 
@@ -65,7 +67,7 @@ public class CSRMeta {
                     nameBuilder.addRDN(BCStyle.OU, mechID + ':' + environment);
                 }
             }
-            for (RDN rdn : rdns) {
+            for (Rdn rdn : rdns) {
                 nameBuilder.addRDN(rdn.getAoi(), rdn.getValue());
             }
             name = nameBuilder.build();
@@ -85,8 +87,8 @@ public class CSRMeta {
         return issuerName;
     }
 
-    public void addSan(String v) {
-        sanList.add(v);
+    public void addSan(String san) {
+        sanList.add(san);
     }
 
     public List<String> getSans() {
index e570f9a..9e95ab2 100644 (file)
@@ -20,6 +20,7 @@
  * ============LICENSE_END====================================================
  *
  */
+
 package org.onap.aaf.certservice.cmpv2client.external;
 
 import org.slf4j.Logger;
@@ -30,30 +31,31 @@ import java.security.KeyPairGenerator;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
 
-public class Factory {
+public final class Factory {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(Factory.class);
-    private static final KeyPairGenerator keygen;
-    private static final SecureRandom random;
+    private static final KeyPairGenerator KEY_PAIR_GENERATOR;
+    private static final SecureRandom SECURE_RANDOM;
     private static final String KEY_ALGORITHM = "RSA";
     private static final int KEY_LENGTH = 2048;
 
     static {
-        random = new SecureRandom();
+        SECURE_RANDOM = new SecureRandom();
         KeyPairGenerator tempKeygen;
         try {
             tempKeygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
-            tempKeygen.initialize(KEY_LENGTH, random);
+            tempKeygen.initialize(KEY_LENGTH, SECURE_RANDOM);
         } catch (NoSuchAlgorithmException e) {
             tempKeygen = null;
             LOGGER.error("Given KEY_ALGORITHM is invalid.", e);
         }
-        keygen = tempKeygen;
+        KEY_PAIR_GENERATOR = tempKeygen;
     }
 
-    private Factory() { }
+    private Factory() {
+    }
 
     public static KeyPair generateKeyPair() {
-        return keygen.generateKeyPair();
+        return KEY_PAIR_GENERATOR.generateKeyPair();
     }
 }
@@ -20,6 +20,7 @@
  * ============LICENSE_END====================================================
  *
  */
+
 package org.onap.aaf.certservice.cmpv2client.external;
 
 import java.util.ArrayList;
@@ -31,7 +32,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier;
 import org.bouncycastle.asn1.x500.style.BCStyle;
 import org.bouncycastle.cert.CertException;
 
-public class RDN {
+public class Rdn {
 
     private String tag;
     private String value;
@@ -41,18 +42,14 @@ public class RDN {
         return value;
     }
 
-    public ASN1ObjectIdentifier getAoi() {
-        return aoi;
-    }
-
-    public RDN(final String tag, final String value) throws CertException {
+    public Rdn(final String tag, final String value) throws CertException {
         this.tag = tag;
         this.value = value;
         this.aoi = getAoi(tag);
     }
 
-    public RDN(final String tagValue) throws CertException {
-        List<String> tv = parseRDN("=", tagValue);
+    public Rdn(final String tagValue) throws CertException {
+        List<String> tv = parseRdn("=", tagValue);
         this.tag = tv.get(0);
         this.value = tv.get(1);
         this.aoi = getAoi(this.tag);
@@ -65,7 +62,7 @@ public class RDN {
      * @param value Value to be splitted
      * @return List of splitted and trimmed strings
      */
-    public static List<String> parseRDN(String splitBy, String value) {
+    static List<String> parseRdn(String splitBy, String value) {
         String[] splitted = value.split(splitBy);
         return Arrays.stream(splitted)
                 .map(String::trim)
@@ -80,24 +77,24 @@ public class RDN {
      * @throws CertException
      */
 
-    public static List<RDN> parse(final char delim, final String dnString) throws CertException {
-        List<RDN> lrnd = new ArrayList<>();
+    public static List<Rdn> parse(final char delim, final String dnString) throws CertException {
+        List<Rdn> lrnd = new ArrayList<>();
         StringBuilder sb = new StringBuilder();
         boolean inQuotes = false;
         for (int i = 0; i < dnString.length(); ++i) {
-            char c = dnString.charAt(i);
+            char currentCharacter = dnString.charAt(i);
             if (inQuotes) {
-                if ('"' == c) {
+                if ('"' == currentCharacter) {
                     inQuotes = false;
                 } else {
                     sb.append(dnString.charAt(i));
                 }
             } else {
-                if ('"' == c) {
+                if ('"' == currentCharacter) {
                     inQuotes = true;
-                } else if (delim == c) {
+                } else if (delim == currentCharacter) {
                     if (sb.length() > 0) {
-                        lrnd.add(new RDN(sb.toString()));
+                        lrnd.add(new Rdn(sb.toString()));
                         sb.setLength(0);
                     }
                 } else {
@@ -106,7 +103,7 @@ public class RDN {
             }
         }
         if (sb.indexOf("=") > 0) {
-            lrnd.add(new RDN(sb.toString()));
+            lrnd.add(new Rdn(sb.toString()));
         }
         return lrnd;
     }
@@ -116,6 +113,10 @@ public class RDN {
         return tag + '=' + value;
     }
 
+    ASN1ObjectIdentifier getAoi() {
+        return aoi;
+    }
+
     ASN1ObjectIdentifier getAoi(String tag) throws CertException {
         switch (tag.toLowerCase()) {
             case "cn":
index e77e8b0..39a0877 100644 (file)
@@ -21,6 +21,7 @@
 package org.onap.aaf.certservice.cmpv2client.impl;
 
 import java.security.PublicKey;
+
 import static org.onap.aaf.certservice.cmpv2client.impl.CmpResponseHelper.checkIfCmpResponseContainsError;
 import static org.onap.aaf.certservice.cmpv2client.impl.CmpResponseHelper.getCertfromByteArray;
 import static org.onap.aaf.certservice.cmpv2client.impl.CmpResponseHelper.verifyAndReturnCertChainAndTrustSTore;
@@ -37,6 +38,7 @@ import java.util.Date;
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
+
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.bouncycastle.asn1.cmp.CMPCertificate;
 import org.bouncycastle.asn1.cmp.CertRepMessage;
@@ -47,7 +49,7 @@ import org.bouncycastle.asn1.cmp.PKIMessage;
 import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
 import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
 import org.onap.aaf.certservice.cmpv2client.api.CmpClient;
-import org.onap.aaf.certservice.cmpv2client.external.CSRMeta;
+import org.onap.aaf.certservice.cmpv2client.external.CsrMeta;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -57,190 +59,190 @@ import org.slf4j.LoggerFactory;
  */
 public class CmpClientImpl implements CmpClient {
 
-  private static final Logger LOG = LoggerFactory.getLogger(CmpClientImpl.class);
-  private final CloseableHttpClient httpClient;
-
-  private static final String DEFAULT_PROFILE = "RA";
-  private static final String DEFAULT_CA_NAME = "Certification Authority";
-
-  public CmpClientImpl(CloseableHttpClient httpClient) {
-    this.httpClient = httpClient;
-  }
-
-  @Override
-  public List<List<X509Certificate>> createCertificate(
-      String caName,
-      String profile,
-      CSRMeta csrMeta,
-      X509Certificate cert,
-      Date notBefore,
-      Date notAfter)
-      throws CmpClientException {
-    // Validate inputs for Certificate Request
-    validate(csrMeta, cert, caName, profile, httpClient, notBefore, notAfter);
-
-    final CreateCertRequest certRequest =
-        CmpMessageBuilder.of(CreateCertRequest::new)
-            .with(CreateCertRequest::setIssuerDn, csrMeta.getIssuerX500Name())
-            .with(CreateCertRequest::setSubjectDn, csrMeta.getX500Name())
-            .with(CreateCertRequest::setSansList, csrMeta.getSans())
-            .with(CreateCertRequest::setSubjectKeyPair, csrMeta.getKeyPair())
-            .with(CreateCertRequest::setNotBefore, notBefore)
-            .with(CreateCertRequest::setNotAfter, notAfter)
-            .with(CreateCertRequest::setInitAuthPassword, csrMeta.getPassword())
-            .with(CreateCertRequest::setSenderKid, csrMeta.getSenderKid())
-            .build();
-
-    final PKIMessage pkiMessage = certRequest.generateCertReq();
-    Cmpv2HttpClient cmpv2HttpClient = new Cmpv2HttpClient(httpClient);
-    return retrieveCertificates(caName, csrMeta, pkiMessage, cmpv2HttpClient);
-  }
-
-  @Override
-  public List<List<X509Certificate>> createCertificate(
-      String caName, String profile, CSRMeta csrMeta, X509Certificate csr)
-      throws CmpClientException {
-    return createCertificate(caName, profile, csrMeta, csr, null, null);
-  }
-
-  private void checkCmpResponse(
-      final PKIMessage respPkiMessage, final PublicKey publicKey, final String initAuthPassword)
-      throws CmpClientException {
-    final PKIHeader header = respPkiMessage.getHeader();
-    final AlgorithmIdentifier protectionAlgo = header.getProtectionAlg();
-    verifySignatureWithPublicKey(respPkiMessage, publicKey);
-    verifyProtectionWithProtectionAlgo(respPkiMessage, initAuthPassword, header, protectionAlgo);
-  }
-
-  private void verifySignatureWithPublicKey(PKIMessage respPkiMessage, PublicKey publicKey)
-      throws CmpClientException {
-    if (Objects.nonNull(publicKey)) {
-      LOG.debug("Verifying signature of the response.");
-      verifySignature(respPkiMessage, publicKey);
-    } else {
-      LOG.error("Public Key is not available, therefore cannot verify signature");
-      throw new CmpClientException(
-          "Public Key is not available, therefore cannot verify signature");
+    private static final Logger LOG = LoggerFactory.getLogger(CmpClientImpl.class);
+    private final CloseableHttpClient httpClient;
+
+    private static final String DEFAULT_PROFILE = "RA";
+    private static final String DEFAULT_CA_NAME = "Certification Authority";
+
+    public CmpClientImpl(CloseableHttpClient httpClient) {
+        this.httpClient = httpClient;
     }
-  }
-
-  private void verifyProtectionWithProtectionAlgo(
-      PKIMessage respPkiMessage,
-      String initAuthPassword,
-      PKIHeader header,
-      AlgorithmIdentifier protectionAlgo)
-      throws CmpClientException {
-    if (Objects.nonNull(protectionAlgo)) {
-      LOG.debug("Verifying PasswordBased Protection of the Response.");
-      verifyPasswordBasedProtection(respPkiMessage, initAuthPassword, protectionAlgo);
-      checkImplicitConfirm(header);
-    } else {
-      LOG.error(
-          "Protection Algorithm is not available when expecting PBE protected response containing protection algorithm");
-      throw new CmpClientException(
-          "Protection Algorithm is not available when expecting PBE protected response containing protection algorithm");
+
+    @Override
+    public List<List<X509Certificate>> createCertificate(
+            String caName,
+            String profile,
+            CsrMeta csrMeta,
+            X509Certificate cert,
+            Date notBefore,
+            Date notAfter)
+            throws CmpClientException {
+        // Validate inputs for Certificate Request
+        validate(csrMeta, cert, caName, profile, httpClient, notBefore, notAfter);
+
+        final CreateCertRequest certRequest =
+                CmpMessageBuilder.of(CreateCertRequest::new)
+                        .with(CreateCertRequest::setIssuerDn, csrMeta.getIssuerX500Name())
+                        .with(CreateCertRequest::setSubjectDn, csrMeta.getX500Name())
+                        .with(CreateCertRequest::setSansList, csrMeta.getSans())
+                        .with(CreateCertRequest::setSubjectKeyPair, csrMeta.getKeyPair())
+                        .with(CreateCertRequest::setNotBefore, notBefore)
+                        .with(CreateCertRequest::setNotAfter, notAfter)
+                        .with(CreateCertRequest::setInitAuthPassword, csrMeta.getPassword())
+                        .with(CreateCertRequest::setSenderKid, csrMeta.getSenderKid())
+                        .build();
+
+        final PKIMessage pkiMessage = certRequest.generateCertReq();
+        Cmpv2HttpClient cmpv2HttpClient = new Cmpv2HttpClient(httpClient);
+        return retrieveCertificates(caName, csrMeta, pkiMessage, cmpv2HttpClient);
     }
-  }
-
-  private List<List<X509Certificate>> checkCmpCertRepMessage(final PKIMessage respPkiMessage)
-      throws CmpClientException {
-    final PKIBody pkiBody = respPkiMessage.getBody();
-    if (Objects.nonNull(pkiBody) && pkiBody.getContent() instanceof CertRepMessage) {
-      final CertRepMessage certRepMessage = (CertRepMessage) pkiBody.getContent();
-      if (Objects.nonNull(certRepMessage)) {
-        final CertResponse certResponse =
-            getCertificateResponseContainingNewCertificate(certRepMessage);
-        try {
-          return verifyReturnCertChainAndTrustStore(respPkiMessage, certRepMessage, certResponse);
-        } catch (IOException | CertificateParsingException ex) {
-          CmpClientException cmpClientException =
-              new CmpClientException(
-                  "Exception occurred while retrieving Certificates from response", ex);
-          LOG.error("Exception occurred while retrieving Certificates from response", ex);
-          throw cmpClientException;
+
+    @Override
+    public List<List<X509Certificate>> createCertificate(
+            String caName, String profile, CsrMeta csrMeta, X509Certificate csr)
+            throws CmpClientException {
+        return createCertificate(caName, profile, csrMeta, csr, null, null);
+    }
+
+    private void checkCmpResponse(
+            final PKIMessage respPkiMessage, final PublicKey publicKey, final String initAuthPassword)
+            throws CmpClientException {
+        final PKIHeader header = respPkiMessage.getHeader();
+        final AlgorithmIdentifier protectionAlgo = header.getProtectionAlg();
+        verifySignatureWithPublicKey(respPkiMessage, publicKey);
+        verifyProtectionWithProtectionAlgo(respPkiMessage, initAuthPassword, header, protectionAlgo);
+    }
+
+    private void verifySignatureWithPublicKey(PKIMessage respPkiMessage, PublicKey publicKey)
+            throws CmpClientException {
+        if (Objects.nonNull(publicKey)) {
+            LOG.debug("Verifying signature of the response.");
+            verifySignature(respPkiMessage, publicKey);
+        } else {
+            LOG.error("Public Key is not available, therefore cannot verify signature");
+            throw new CmpClientException(
+                    "Public Key is not available, therefore cannot verify signature");
+        }
+    }
+
+    private void verifyProtectionWithProtectionAlgo(
+            PKIMessage respPkiMessage,
+            String initAuthPassword,
+            PKIHeader header,
+            AlgorithmIdentifier protectionAlgo)
+            throws CmpClientException {
+        if (Objects.nonNull(protectionAlgo)) {
+            LOG.debug("Verifying PasswordBased Protection of the Response.");
+            verifyPasswordBasedProtection(respPkiMessage, initAuthPassword, protectionAlgo);
+            checkImplicitConfirm(header);
+        } else {
+            LOG.error(
+                    "Protection Algorithm is not available when expecting PBE protected response containing protection algorithm");
+            throw new CmpClientException(
+                    "Protection Algorithm is not available when expecting PBE protected response containing protection algorithm");
+        }
+    }
+
+    private List<List<X509Certificate>> checkCmpCertRepMessage(final PKIMessage respPkiMessage)
+            throws CmpClientException {
+        final PKIBody pkiBody = respPkiMessage.getBody();
+        if (Objects.nonNull(pkiBody) && pkiBody.getContent() instanceof CertRepMessage) {
+            final CertRepMessage certRepMessage = (CertRepMessage) pkiBody.getContent();
+            if (Objects.nonNull(certRepMessage)) {
+                final CertResponse certResponse =
+                        getCertificateResponseContainingNewCertificate(certRepMessage);
+                try {
+                    return verifyReturnCertChainAndTrustStore(respPkiMessage, certRepMessage, certResponse);
+                } catch (IOException | CertificateParsingException ex) {
+                    CmpClientException cmpClientException =
+                            new CmpClientException(
+                                    "Exception occurred while retrieving Certificates from response", ex);
+                    LOG.error("Exception occurred while retrieving Certificates from response", ex);
+                    throw cmpClientException;
+                }
+            } else {
+                return new ArrayList<>(Collections.emptyList());
+            }
         }
-      } else {
         return new ArrayList<>(Collections.emptyList());
-      }
     }
-    return new ArrayList<>(Collections.emptyList());
-  }
-
-  private List<List<X509Certificate>> verifyReturnCertChainAndTrustStore(
-      PKIMessage respPkiMessage, CertRepMessage certRepMessage, CertResponse certResponse)
-      throws CertificateParsingException, CmpClientException, IOException {
-    LOG.info("Verifying certificates returned as part of CertResponse.");
-    final CMPCertificate cmpCertificate =
-        certResponse.getCertifiedKeyPair().getCertOrEncCert().getCertificate();
-    final Optional<X509Certificate> leafCertificate =
-        getCertfromByteArray(cmpCertificate.getEncoded(), X509Certificate.class);
-    if (leafCertificate.isPresent()) {
-      return verifyAndReturnCertChainAndTrustSTore(
-          respPkiMessage, certRepMessage, leafCertificate.get());
+
+    private List<List<X509Certificate>> verifyReturnCertChainAndTrustStore(
+            PKIMessage respPkiMessage, CertRepMessage certRepMessage, CertResponse certResponse)
+            throws CertificateParsingException, CmpClientException, IOException {
+        LOG.info("Verifying certificates returned as part of CertResponse.");
+        final CMPCertificate cmpCertificate =
+                certResponse.getCertifiedKeyPair().getCertOrEncCert().getCertificate();
+        final Optional<X509Certificate> leafCertificate =
+                getCertfromByteArray(cmpCertificate.getEncoded(), X509Certificate.class);
+        if (leafCertificate.isPresent()) {
+            return verifyAndReturnCertChainAndTrustSTore(
+                    respPkiMessage, certRepMessage, leafCertificate.get());
+        }
+        return Collections.emptyList();
     }
-    return Collections.emptyList();
-  }
-
-  private CertResponse getCertificateResponseContainingNewCertificate(
-      CertRepMessage certRepMessage) {
-    return certRepMessage.getResponse()[0];
-  }
-
-  /**
-   * Validate inputs for Certificate Creation.
-   *
-   * @param csrMeta CSRMeta Object containing variables for creating a Certificate Request.
-   * @param cert Certificate object needed to validate response from CA server.
-   * @param incomingCaName Date specifying certificate is not valid before this date.
-   * @param incomingProfile Date specifying certificate is not valid after this date.
-   * @throws IllegalArgumentException if Before Date is set after the After Date.
-   */
-  private void validate(
-      final CSRMeta csrMeta,
-      final X509Certificate cert,
-      final String incomingCaName,
-      final String incomingProfile,
-      final CloseableHttpClient httpClient,
-      final Date notBefore,
-      final Date notAfter) {
-
-    String caName;
-    String caProfile;
-    caName = CmpUtil.isNullOrEmpty(incomingCaName) ? incomingCaName : DEFAULT_CA_NAME;
-    caProfile = CmpUtil.isNullOrEmpty(incomingProfile) ? incomingProfile : DEFAULT_PROFILE;
-    LOG.info(
-        "Validate before creating Certificate Request for CA :{} in Mode {} ", caName, caProfile);
-
-    CmpUtil.notNull(csrMeta, "CSRMeta Instance");
-    CmpUtil.notNull(csrMeta.getX500Name(), "Subject DN");
-    CmpUtil.notNull(csrMeta.getIssuerX500Name(), "Issuer DN");
-    CmpUtil.notNull(csrMeta.getPassword(), "IAK/RV Password");
-    CmpUtil.notNull(cert, "Certificate Signing Request (CSR)");
-    CmpUtil.notNull(csrMeta.getCaUrl(), "External CA URL");
-    CmpUtil.notNull(csrMeta.getKeyPairOrGenerateIfNull(), "Subject KeyPair");
-    CmpUtil.notNull(httpClient, "Closeable Http Client");
-
-    if (notBefore != null && notAfter != null && notBefore.compareTo(notAfter) > 0) {
-      throw new IllegalArgumentException("Before Date is set after the After Date");
+
+    private CertResponse getCertificateResponseContainingNewCertificate(
+            CertRepMessage certRepMessage) {
+        return certRepMessage.getResponse()[0];
     }
-  }
-
-  private List<List<X509Certificate>> retrieveCertificates(
-      String caName, CSRMeta csrMeta, PKIMessage pkiMessage, Cmpv2HttpClient cmpv2HttpClient)
-      throws CmpClientException {
-    final byte[] respBytes = cmpv2HttpClient.postRequest(pkiMessage, csrMeta.getCaUrl(), caName);
-    try {
-      final PKIMessage respPkiMessage = PKIMessage.getInstance(respBytes);
-      LOG.info("Received response from Server");
-      checkIfCmpResponseContainsError(respPkiMessage);
-      checkCmpResponse(respPkiMessage, csrMeta.getKeyPairOrGenerateIfNull().getPublic(), csrMeta.getPassword());
-      return checkCmpCertRepMessage(respPkiMessage);
-    } catch (IllegalArgumentException iae) {
-      CmpClientException cmpClientException =
-          new CmpClientException(
-              "Error encountered while processing response from CA server ", iae);
-      LOG.error("Error encountered while processing response from CA server ", iae);
-      throw cmpClientException;
+
+    /**
+     * Validate inputs for Certificate Creation.
+     *
+     * @param csrMeta         CSRMeta Object containing variables for creating a Certificate Request.
+     * @param cert            Certificate object needed to validate response from CA server.
+     * @param incomingCaName  Date specifying certificate is not valid before this date.
+     * @param incomingProfile Date specifying certificate is not valid after this date.
+     * @throws IllegalArgumentException if Before Date is set after the After Date.
+     */
+    private void validate(
+            final CsrMeta csrMeta,
+            final X509Certificate cert,
+            final String incomingCaName,
+            final String incomingProfile,
+            final CloseableHttpClient httpClient,
+            final Date notBefore,
+            final Date notAfter) {
+
+        String caName;
+        String caProfile;
+        caName = CmpUtil.isNullOrEmpty(incomingCaName) ? incomingCaName : DEFAULT_CA_NAME;
+        caProfile = CmpUtil.isNullOrEmpty(incomingProfile) ? incomingProfile : DEFAULT_PROFILE;
+        LOG.info(
+                "Validate before creating Certificate Request for CA :{} in Mode {} ", caName, caProfile);
+
+        CmpUtil.notNull(csrMeta, "CSRMeta Instance");
+        CmpUtil.notNull(csrMeta.getX500Name(), "Subject DN");
+        CmpUtil.notNull(csrMeta.getIssuerX500Name(), "Issuer DN");
+        CmpUtil.notNull(csrMeta.getPassword(), "IAK/RV Password");
+        CmpUtil.notNull(cert, "Certificate Signing Request (CSR)");
+        CmpUtil.notNull(csrMeta.getCaUrl(), "External CA URL");
+        CmpUtil.notNull(csrMeta.getKeyPairOrGenerateIfNull(), "Subject KeyPair");
+        CmpUtil.notNull(httpClient, "Closeable Http Client");
+
+        if (notBefore != null && notAfter != null && notBefore.compareTo(notAfter) > 0) {
+            throw new IllegalArgumentException("Before Date is set after the After Date");
+        }
+    }
+
+    private List<List<X509Certificate>> retrieveCertificates(
+            String caName, CsrMeta csrMeta, PKIMessage pkiMessage, Cmpv2HttpClient cmpv2HttpClient)
+            throws CmpClientException {
+        final byte[] respBytes = cmpv2HttpClient.postRequest(pkiMessage, csrMeta.getCaUrl(), caName);
+        try {
+            final PKIMessage respPkiMessage = PKIMessage.getInstance(respBytes);
+            LOG.info("Received response from Server");
+            checkIfCmpResponseContainsError(respPkiMessage);
+            checkCmpResponse(respPkiMessage, csrMeta.getKeyPairOrGenerateIfNull().getPublic(), csrMeta.getPassword());
+            return checkCmpCertRepMessage(respPkiMessage);
+        } catch (IllegalArgumentException iae) {
+            CmpClientException cmpClientException =
+                    new CmpClientException(
+                            "Error encountered while processing response from CA server ", iae);
+            LOG.error("Error encountered while processing response from CA server ", iae);
+            throw cmpClientException;
+        }
     }
-  }
 }
index 2ab9b2c..1f370f9 100644 (file)
@@ -26,30 +26,32 @@ import java.util.function.BiConsumer;
 import java.util.function.Consumer;
 import java.util.function.Supplier;
 
-/** Generic Builder Class for creating CMP Message. */
-public class CmpMessageBuilder<T> {
-
-  private final Supplier<T> instantiator;
-  private final List<Consumer<T>> instanceModifiers = new ArrayList<>();
-
-  public CmpMessageBuilder(Supplier<T> instantiator) {
-    this.instantiator = instantiator;
-  }
-
-  public static <T> CmpMessageBuilder<T> of(Supplier<T> instantiator) {
-    return new CmpMessageBuilder<>(instantiator);
-  }
-
-  public <U> CmpMessageBuilder<T> with(BiConsumer<T, U> consumer, U value) {
-    Consumer<T> c = instance -> consumer.accept(instance, value);
-    instanceModifiers.add(c);
-    return this;
-  }
-
-  public T build() {
-    T value = instantiator.get();
-    instanceModifiers.forEach(modifier -> modifier.accept(value));
-    instanceModifiers.clear();
-    return value;
-  }
+/**
+ * Generic Builder Class for creating CMP Message.
+ */
+public final class CmpMessageBuilder<T> {
+
+    private final Supplier<T> instantiator;
+    private final List<Consumer<T>> instanceModifiers = new ArrayList<>();
+
+    public CmpMessageBuilder(Supplier<T> instantiator) {
+        this.instantiator = instantiator;
+    }
+
+    public static <T> CmpMessageBuilder<T> of(Supplier<T> instantiator) {
+        return new CmpMessageBuilder<>(instantiator);
+    }
+
+    public <U> CmpMessageBuilder<T> with(BiConsumer<T, U> consumer, U value) {
+        Consumer<T> valueConsumer = instance -> consumer.accept(instance, value);
+        instanceModifiers.add(valueConsumer);
+        return this;
+    }
+
+    public T build() {
+        T value = instantiator.get();
+        instanceModifiers.forEach(modifier -> modifier.accept(value));
+        instanceModifiers.clear();
+        return value;
+    }
 }
index 48b2336..6fcc5f1 100644 (file)
@@ -37,6 +37,7 @@ import java.util.List;
 import javax.crypto.Mac;
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
+
 import org.bouncycastle.asn1.ASN1EncodableVector;
 import org.bouncycastle.asn1.ASN1Integer;
 import org.bouncycastle.asn1.ASN1ObjectIdentifier;
@@ -69,176 +70,177 @@ import org.slf4j.LoggerFactory;
 
 public final class CmpMessageHelper {
 
-  private static final Logger LOG = LoggerFactory.getLogger(CmpMessageHelper.class);
-  private static final AlgorithmIdentifier OWF_ALGORITHM =
-      new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"));
-  private static final AlgorithmIdentifier MAC_ALGORITHM =
-      new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.9"));
-  private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC =
-      new ASN1ObjectIdentifier("1.2.840.113533.7.66.13");
-
-  private CmpMessageHelper() {}
-
-  /**
-   * Creates an Optional Validity, which is used to specify how long the returned cert should be
-   * valid for.
-   *
-   * @param notBefore Date specifying certificate is not valid before this date.
-   * @param notAfter Date specifying certificate is not valid after this date.
-   * @return {@link OptionalValidity} that can be set for certificate on external CA.
-   */
-  public static OptionalValidity generateOptionalValidity(
-      final Date notBefore, final Date notAfter) {
-    LOG.info("Generating Optional Validity from Date objects");
-    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
-    if (notBefore != null) {
-      Time nb = new Time(notBefore);
-      optionalValidityV.add(new DERTaggedObject(true, 0, nb));
+    private static final Logger LOG = LoggerFactory.getLogger(CmpMessageHelper.class);
+    private static final AlgorithmIdentifier OWF_ALGORITHM =
+            new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"));
+    private static final AlgorithmIdentifier MAC_ALGORITHM =
+            new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.9"));
+    private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC =
+            new ASN1ObjectIdentifier("1.2.840.113533.7.66.13");
+
+    private CmpMessageHelper() {
     }
-    if (notAfter != null) {
-      Time na = new Time(notAfter);
-      optionalValidityV.add(new DERTaggedObject(true, 1, na));
+
+    /**
+     * Creates an Optional Validity, which is used to specify how long the returned cert should be
+     * valid for.
+     *
+     * @param notBefore Date specifying certificate is not valid before this date.
+     * @param notAfter  Date specifying certificate is not valid after this date.
+     * @return {@link OptionalValidity} that can be set for certificate on external CA.
+     */
+    public static OptionalValidity generateOptionalValidity(
+            final Date notBefore, final Date notAfter) {
+        LOG.info("Generating Optional Validity from Date objects");
+        ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
+        if (notBefore != null) {
+            Time nb = new Time(notBefore);
+            optionalValidityV.add(new DERTaggedObject(true, 0, nb));
+        }
+        if (notAfter != null) {
+            Time na = new Time(notAfter);
+            optionalValidityV.add(new DERTaggedObject(true, 1, na));
+        }
+        return OptionalValidity.getInstance(new DERSequence(optionalValidityV));
     }
-    return OptionalValidity.getInstance(new DERSequence(optionalValidityV));
-  }
-
-  /**
-   * Create Extensions from Subject Alternative Names.
-   *
-   * @return {@link Extensions}.
-   */
-  public static Extensions generateExtension(final List<String> sansList)
-      throws CmpClientException {
-    LOG.info("Generating Extensions from Subject Alternative Names");
-    final ExtensionsGenerator extGenerator = new ExtensionsGenerator();
-    final GeneralName[] sansGeneralNames = getGeneralNames(sansList);
-    // KeyUsage
-    try {
-      final KeyUsage keyUsage =
-          new KeyUsage(
-              KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation);
-      extGenerator.addExtension(Extension.keyUsage, false, new DERBitString(keyUsage));
-      extGenerator.addExtension(
-          Extension.subjectAlternativeName, false, new GeneralNames(sansGeneralNames));
-    } catch (IOException ioe) {
-      CmpClientException cmpClientException =
-          new CmpClientException(
-              "Exception occurred while creating extensions for PKIMessage", ioe);
-      LOG.error("Exception occurred while creating extensions for PKIMessage");
-      throw cmpClientException;
+
+    /**
+     * Create Extensions from Subject Alternative Names.
+     *
+     * @return {@link Extensions}.
+     */
+    public static Extensions generateExtension(final List<String> sansList)
+            throws CmpClientException {
+        LOG.info("Generating Extensions from Subject Alternative Names");
+        final ExtensionsGenerator extGenerator = new ExtensionsGenerator();
+        final GeneralName[] sansGeneralNames = getGeneralNames(sansList);
+        // KeyUsage
+        try {
+            final KeyUsage keyUsage =
+                    new KeyUsage(
+                            KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation);
+            extGenerator.addExtension(Extension.keyUsage, false, new DERBitString(keyUsage));
+            extGenerator.addExtension(
+                    Extension.subjectAlternativeName, false, new GeneralNames(sansGeneralNames));
+        } catch (IOException ioe) {
+            CmpClientException cmpClientException =
+                    new CmpClientException(
+                            "Exception occurred while creating extensions for PKIMessage", ioe);
+            LOG.error("Exception occurred while creating extensions for PKIMessage");
+            throw cmpClientException;
+        }
+        return extGenerator.generate();
     }
-    return extGenerator.generate();
-  }
 
-  public static GeneralName[] getGeneralNames(List<String> sansList) {
-    final List<GeneralName> nameList = new ArrayList<>();
-    for (String san : sansList) {
-      nameList.add(new GeneralName(GeneralName.dNSName, san));
+    public static GeneralName[] getGeneralNames(List<String> sansList) {
+        final List<GeneralName> nameList = new ArrayList<>();
+        for (String san : sansList) {
+            nameList.add(new GeneralName(GeneralName.dNSName, san));
+        }
+        final GeneralName[] sansGeneralNames = new GeneralName[nameList.size()];
+        nameList.toArray(sansGeneralNames);
+        return sansGeneralNames;
     }
-    final GeneralName[] sansGeneralNames = new GeneralName[nameList.size()];
-    nameList.toArray(sansGeneralNames);
-    return sansGeneralNames;
-  }
-
-  /**
-   * Method generates Proof-of-Possession (POP) of Private Key. To allow a CA/RA to properly
-   * validity binding between an End Entity and a Key Pair, the PKI Operations specified here make
-   * it possible for an End Entity to prove that it has possession of the Private Key corresponding
-   * to the Public Key for which a Certificate is requested.
-   *
-   * @param certRequest Certificate request that requires proof of possession
-   * @param keypair keypair associated with the subject sending the certificate request
-   * @return {@link ProofOfPossession}.
-   * @throws CmpClientException A general-purpose Cmp client exception.
-   */
-  public static ProofOfPossession generateProofOfPossession(
-      final CertRequest certRequest, final KeyPair keypair) throws CmpClientException {
-    ProofOfPossession proofOfPossession;
-    try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
-      final DEROutputStream derOutputStream = new DEROutputStream(byteArrayOutputStream);
-      derOutputStream.writeObject(certRequest);
-
-      byte[] popoProtectionBytes = byteArrayOutputStream.toByteArray();
-      final String sigalg = PKCSObjectIdentifiers.sha256WithRSAEncryption.getId();
-      final Signature signature = Signature.getInstance(sigalg, BouncyCastleProvider.PROVIDER_NAME);
-      signature.initSign(keypair.getPrivate());
-      signature.update(popoProtectionBytes);
-      DERBitString bs = new DERBitString(signature.sign());
-
-      proofOfPossession =
-          new ProofOfPossession(
-              new POPOSigningKey(
-                  null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs));
-    } catch (IOException
-        | NoSuchProviderException
-        | NoSuchAlgorithmException
-        | InvalidKeyException
-        | SignatureException ex) {
-      CmpClientException cmpClientException =
-          new CmpClientException(
-              "Exception occurred while creating proof of possession for PKIMessage", ex);
-      LOG.error("Exception occurred while creating proof of possession for PKIMessage");
-      throw cmpClientException;
+
+    /**
+     * Method generates Proof-of-Possession (POP) of Private Key. To allow a CA/RA to properly
+     * validity binding between an End Entity and a Key Pair, the PKI Operations specified here make
+     * it possible for an End Entity to prove that it has possession of the Private Key corresponding
+     * to the Public Key for which a Certificate is requested.
+     *
+     * @param certRequest Certificate request that requires proof of possession
+     * @param keypair     keypair associated with the subject sending the certificate request
+     * @return {@link ProofOfPossession}.
+     * @throws CmpClientException A general-purpose Cmp client exception.
+     */
+    public static ProofOfPossession generateProofOfPossession(
+            final CertRequest certRequest, final KeyPair keypair) throws CmpClientException {
+        ProofOfPossession proofOfPossession;
+        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
+            final DEROutputStream derOutputStream = new DEROutputStream(byteArrayOutputStream);
+            derOutputStream.writeObject(certRequest);
+
+            byte[] popoProtectionBytes = byteArrayOutputStream.toByteArray();
+            final String sigalg = PKCSObjectIdentifiers.sha256WithRSAEncryption.getId();
+            final Signature signature = Signature.getInstance(sigalg, BouncyCastleProvider.PROVIDER_NAME);
+            signature.initSign(keypair.getPrivate());
+            signature.update(popoProtectionBytes);
+            DERBitString bs = new DERBitString(signature.sign());
+
+            proofOfPossession =
+                    new ProofOfPossession(
+                            new POPOSigningKey(
+                                    null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs));
+        } catch (IOException
+                | NoSuchProviderException
+                | NoSuchAlgorithmException
+                | InvalidKeyException
+                | SignatureException ex) {
+            CmpClientException cmpClientException =
+                    new CmpClientException(
+                            "Exception occurred while creating proof of possession for PKIMessage", ex);
+            LOG.error("Exception occurred while creating proof of possession for PKIMessage");
+            throw cmpClientException;
+        }
+        return proofOfPossession;
     }
-    return proofOfPossession;
-  }
-
-  /**
-   * Generic code to create Algorithm Identifier for protection of PKIMessage.
-   *
-   * @return Algorithm Identifier
-   */
-  public static AlgorithmIdentifier protectionAlgoIdentifier(int iterations, byte[] salt) {
-    ASN1Integer iteration = new ASN1Integer(iterations);
-    DEROctetString derSalt = new DEROctetString(salt);
-
-    PBMParameter pp = new PBMParameter(derSalt, OWF_ALGORITHM, iteration, MAC_ALGORITHM);
-    return new AlgorithmIdentifier(PASSWORD_BASED_MAC, pp);
-  }
-
-  /**
-   * Adds protection to the PKIMessage via a specified protection algorithm.
-   *
-   * @param password password used to authenticate PkiMessage with external CA
-   * @param pkiHeader Header of PKIMessage containing generic details for any PKIMessage
-   * @param pkiBody Body of PKIMessage containing specific details for certificate request
-   * @return Protected Pki Message
-   * @throws CmpClientException Wraps several exceptions into one general-purpose exception.
-   */
-  public static PKIMessage protectPkiMessage(
-      PKIHeader pkiHeader, PKIBody pkiBody, String password, int iterations, byte[] salt)
-      throws CmpClientException {
-
-    byte[] raSecret = password.getBytes();
-    byte[] basekey = new byte[raSecret.length + salt.length];
-    System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
-    System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
-    byte[] out;
-    try {
-      MessageDigest dig =
-          MessageDigest.getInstance(
-              OWF_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
-      for (int i = 0; i < iterations; i++) {
-        basekey = dig.digest(basekey);
-        dig.reset();
-      }
-      byte[] protectedBytes = generateProtectedBytes(pkiHeader, pkiBody);
-      Mac mac =
-          Mac.getInstance(MAC_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
-      SecretKey key = new SecretKeySpec(basekey, MAC_ALGORITHM.getAlgorithm().getId());
-      mac.init(key);
-      mac.reset();
-      mac.update(protectedBytes, 0, protectedBytes.length);
-      out = mac.doFinal();
-    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException ex) {
-      CmpClientException cmpClientException =
-          new CmpClientException(
-              "Exception occurred while generating proof of possession for PKIMessage", ex);
-      LOG.error("Exception occured while generating the proof of possession for PKIMessage");
-      throw cmpClientException;
+
+    /**
+     * Generic code to create Algorithm Identifier for protection of PKIMessage.
+     *
+     * @return Algorithm Identifier
+     */
+    public static AlgorithmIdentifier protectionAlgoIdentifier(int iterations, byte[] salt) {
+        ASN1Integer iteration = new ASN1Integer(iterations);
+        DEROctetString derSalt = new DEROctetString(salt);
+
+        PBMParameter pp = new PBMParameter(derSalt, OWF_ALGORITHM, iteration, MAC_ALGORITHM);
+        return new AlgorithmIdentifier(PASSWORD_BASED_MAC, pp);
     }
-    DERBitString bs = new DERBitString(out);
 
-    return new PKIMessage(pkiHeader, pkiBody, bs);
-  }
+    /**
+     * Adds protection to the PKIMessage via a specified protection algorithm.
+     *
+     * @param password  password used to authenticate PkiMessage with external CA
+     * @param pkiHeader Header of PKIMessage containing generic details for any PKIMessage
+     * @param pkiBody   Body of PKIMessage containing specific details for certificate request
+     * @return Protected Pki Message
+     * @throws CmpClientException Wraps several exceptions into one general-purpose exception.
+     */
+    public static PKIMessage protectPkiMessage(
+            PKIHeader pkiHeader, PKIBody pkiBody, String password, int iterations, byte[] salt)
+            throws CmpClientException {
+
+        byte[] raSecret = password.getBytes();
+        byte[] basekey = new byte[raSecret.length + salt.length];
+        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
+        System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
+        byte[] out;
+        try {
+            MessageDigest dig =
+                    MessageDigest.getInstance(
+                            OWF_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
+            for (int i = 0; i < iterations; i++) {
+                basekey = dig.digest(basekey);
+                dig.reset();
+            }
+            byte[] protectedBytes = generateProtectedBytes(pkiHeader, pkiBody);
+            Mac mac =
+                    Mac.getInstance(MAC_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
+            SecretKey key = new SecretKeySpec(basekey, MAC_ALGORITHM.getAlgorithm().getId());
+            mac.init(key);
+            mac.reset();
+            mac.update(protectedBytes, 0, protectedBytes.length);
+            out = mac.doFinal();
+        } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException ex) {
+            CmpClientException cmpClientException =
+                    new CmpClientException(
+                            "Exception occurred while generating proof of possession for PKIMessage", ex);
+            LOG.error("Exception occured while generating the proof of possession for PKIMessage");
+            throw cmpClientException;
+        }
+        DERBitString bs = new DERBitString(out);
+
+        return new PKIMessage(pkiHeader, pkiBody, bs);
+    }
 }
index 60d91c5..b2a7b29 100644 (file)
@@ -43,6 +43,7 @@ import java.util.Date;
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
+
 import org.bouncycastle.asn1.cmp.CMPCertificate;
 import org.bouncycastle.asn1.cmp.CertRepMessage;
 import org.bouncycastle.asn1.cmp.ErrorMsgContent;
@@ -54,318 +55,319 @@ import org.onap.aaf.certservice.cmpv2client.exceptions.PkiErrorException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class CmpResponseHelper {
-
-  private static final Logger LOG = LoggerFactory.getLogger(CmpResponseHelper.class);
+public final class CmpResponseHelper {
 
-  private CmpResponseHelper() {}
+    private static final Logger LOG = LoggerFactory.getLogger(CmpResponseHelper.class);
 
-  public static void checkIfCmpResponseContainsError(PKIMessage respPkiMessage)
-      throws CmpClientException {
-    if (respPkiMessage.getBody().getType() == PKIBody.TYPE_ERROR) {
-      final ErrorMsgContent errorMsgContent =
-          (ErrorMsgContent) respPkiMessage.getBody().getContent();
-      PkiErrorException pkiErrorException =
-          new PkiErrorException(
-              errorMsgContent.getPKIStatusInfo().getStatusString().getStringAt(0).getString());
-      CmpClientException cmpClientException =
-          new CmpClientException("Error in the PkiMessage response", pkiErrorException);
-      LOG.error("Error in the PkiMessage response: {} ", pkiErrorException.getMessage());
-      throw cmpClientException;
+    private CmpResponseHelper() {
     }
-  }
-
-  /**
-   * @param cert byte array that contains certificate
-   * @param returnType the type of Certificate to be returned, for example X509Certificate.class.
-   *     Certificate.class can be used if certificate type is unknown.
-   * @throws CertificateParsingException if the byte array does not contain a proper certificate.
-   */
-  public static <T extends Certificate> Optional<X509Certificate> getCertfromByteArray(
-      byte[] cert, Class<T> returnType) throws CertificateParsingException, CmpClientException {
-    LOG.debug("Retrieving certificate of type {} from byte array.", returnType);
-    return getCertfromByteArray(cert, BouncyCastleProvider.PROVIDER_NAME, returnType);
-  }
 
-  /**
-   * @param cert byte array that contains certificate
-   * @param provider provider used to generate certificate from bytes
-   * @param returnType the type of Certificate to be returned, for example X509Certificate.class.
-   *     Certificate.class can be used if certificate type is unknown.
-   * @throws CertificateParsingException if the byte array does not contain a proper certificate.
-   */
-  public static <T extends Certificate> Optional<X509Certificate> getCertfromByteArray(
-      byte[] cert, String provider, Class<T> returnType)
-      throws CertificateParsingException, CmpClientException {
-    String prov = provider;
-    if (provider == null) {
-      prov = BouncyCastleProvider.PROVIDER_NAME;
+    public static void checkIfCmpResponseContainsError(PKIMessage respPkiMessage)
+            throws CmpClientException {
+        if (respPkiMessage.getBody().getType() == PKIBody.TYPE_ERROR) {
+            final ErrorMsgContent errorMsgContent =
+                    (ErrorMsgContent) respPkiMessage.getBody().getContent();
+            PkiErrorException pkiErrorException =
+                    new PkiErrorException(
+                            errorMsgContent.getPKIStatusInfo().getStatusString().getStringAt(0).getString());
+            CmpClientException cmpClientException =
+                    new CmpClientException("Error in the PkiMessage response", pkiErrorException);
+            LOG.error("Error in the PkiMessage response: {} ", pkiErrorException.getMessage());
+            throw cmpClientException;
+        }
     }
 
-    if (returnType.equals(X509Certificate.class)) {
-      return parseX509Certificate(prov, cert);
+    /**
+     * @param cert       byte array that contains certificate
+     * @param returnType the type of Certificate to be returned, for example X509Certificate.class.
+     *                   Certificate.class can be used if certificate type is unknown.
+     * @throws CertificateParsingException if the byte array does not contain a proper certificate.
+     */
+    public static <T extends Certificate> Optional<X509Certificate> getCertfromByteArray(
+            byte[] cert, Class<T> returnType) throws CertificateParsingException, CmpClientException {
+        LOG.debug("Retrieving certificate of type {} from byte array.", returnType);
+        return getCertfromByteArray(cert, BouncyCastleProvider.PROVIDER_NAME, returnType);
     }
-    return Optional.empty();
-  }
 
-  /**
-   * Check the certificate with CA certificate.
-   *
-   * @param caCertChain Collection of X509Certificates. May not be null, an empty list or a
-   *     Collection with null entries.
-   * @throws CmpClientException if verification failed
-   */
-  public static void verify(List<X509Certificate> caCertChain) throws CmpClientException {
-    int iterator = 1;
-    while (iterator < caCertChain.size()) {
-      verify(caCertChain.get(iterator - 1), caCertChain.get(iterator), null);
-      iterator += 1;
+    /**
+     * @param cert       byte array that contains certificate
+     * @param provider   provider used to generate certificate from bytes
+     * @param returnType the type of Certificate to be returned, for example X509Certificate.class.
+     *                   Certificate.class can be used if certificate type is unknown.
+     * @throws CertificateParsingException if the byte array does not contain a proper certificate.
+     */
+    public static <T extends Certificate> Optional<X509Certificate> getCertfromByteArray(
+            byte[] cert, String provider, Class<T> returnType)
+            throws CertificateParsingException, CmpClientException {
+        String prov = provider;
+        if (provider == null) {
+            prov = BouncyCastleProvider.PROVIDER_NAME;
+        }
+
+        if (returnType.equals(X509Certificate.class)) {
+            return parseX509Certificate(prov, cert);
+        }
+        return Optional.empty();
     }
-  }
 
-  /**
-   * Check the certificate with CA certificate.
-   *
-   * @param certificate X.509 certificate to verify. May not be null.
-   * @param caCertChain Collection of X509Certificates. May not be null, an empty list or a
-   *     Collection with null entries.
-   * @param date Date to verify at, or null to use current time.
-   * @param pkixCertPathCheckers optional PKIXCertPathChecker implementations to use during cert
-   *     path validation
-   * @throws CmpClientException if certificate could not be validated
-   */
-  public static void verify(
-      X509Certificate certificate,
-      X509Certificate caCertChain,
-      Date date,
-      PKIXCertPathChecker... pkixCertPathCheckers)
-      throws CmpClientException {
-    try {
-      verifyCertificates(certificate, caCertChain, date, pkixCertPathCheckers);
-    } catch (CertPathValidatorException cpve) {
-      CmpClientException cmpClientException =
-          new CmpClientException(
-              "Invalid certificate or certificate not issued by specified CA: ", cpve);
-      LOG.error("Invalid certificate or certificate not issued by specified CA: ", cpve);
-      throw cmpClientException;
-    } catch (CertificateException ce) {
-      CmpClientException cmpClientException =
-          new CmpClientException("Something was wrong with the supplied certificate", ce);
-      LOG.error("Something was wrong with the supplied certificate", ce);
-      throw cmpClientException;
-    } catch (NoSuchProviderException nspe) {
-      CmpClientException cmpClientException =
-          new CmpClientException("BouncyCastle provider not found.", nspe);
-      LOG.error("BouncyCastle provider not found.", nspe);
-      throw cmpClientException;
-    } catch (NoSuchAlgorithmException nsae) {
-      CmpClientException cmpClientException =
-          new CmpClientException("Algorithm PKIX was not found.", nsae);
-      LOG.error("Algorithm PKIX was not found.", nsae);
-      throw cmpClientException;
-    } catch (InvalidAlgorithmParameterException iape) {
-      CmpClientException cmpClientException =
-          new CmpClientException(
-              "Either ca certificate chain was empty,"
-                  + " or the certificate was on an inappropriate type for a PKIX path checker.",
-              iape);
-      LOG.error(
-          "Either ca certificate chain was empty, "
-              + "or the certificate was on an inappropriate type for a PKIX path checker.",
-          iape);
-      throw cmpClientException;
+    /**
+     * Check the certificate with CA certificate.
+     *
+     * @param caCertChain Collection of X509Certificates. May not be null, an empty list or a
+     *                    Collection with null entries.
+     * @throws CmpClientException if verification failed
+     */
+    public static void verify(List<X509Certificate> caCertChain) throws CmpClientException {
+        int iterator = 1;
+        while (iterator < caCertChain.size()) {
+            verify(caCertChain.get(iterator - 1), caCertChain.get(iterator), null);
+            iterator += 1;
+        }
     }
-  }
 
-  public static void verifyCertificates(
-      X509Certificate certificate,
-      X509Certificate caCertChain,
-      Date date,
-      PKIXCertPathChecker[] pkixCertPathCheckers)
-      throws CertificateException, NoSuchProviderException, InvalidAlgorithmParameterException,
-          NoSuchAlgorithmException, CertPathValidatorException {
-    LOG.debug(
-        "Verifying certificate {} as part of cert chain with certificate {}",
-        certificate.getSubjectDN().getName(),
-        caCertChain.getSubjectDN().getName());
-    CertPath cp = getCertPath(certificate);
-    PKIXParameters params = getPkixParameters(caCertChain, date, pkixCertPathCheckers);
-    CertPathValidator cpv =
-        CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
-    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
-    if (LOG.isDebugEnabled()) {
-      LOG.debug("Certificate verify result:{} ", result);
+    /**
+     * Check the certificate with CA certificate.
+     *
+     * @param certificate          X.509 certificate to verify. May not be null.
+     * @param caCertChain          Collection of X509Certificates. May not be null, an empty list or a
+     *                             Collection with null entries.
+     * @param date                 Date to verify at, or null to use current time.
+     * @param pkixCertPathCheckers optional PKIXCertPathChecker implementations to use during cert
+     *                             path validation
+     * @throws CmpClientException if certificate could not be validated
+     */
+    public static void verify(
+            X509Certificate certificate,
+            X509Certificate caCertChain,
+            Date date,
+            PKIXCertPathChecker... pkixCertPathCheckers)
+            throws CmpClientException {
+        try {
+            verifyCertificates(certificate, caCertChain, date, pkixCertPathCheckers);
+        } catch (CertPathValidatorException cpve) {
+            CmpClientException cmpClientException =
+                    new CmpClientException(
+                            "Invalid certificate or certificate not issued by specified CA: ", cpve);
+            LOG.error("Invalid certificate or certificate not issued by specified CA: ", cpve);
+            throw cmpClientException;
+        } catch (CertificateException ce) {
+            CmpClientException cmpClientException =
+                    new CmpClientException("Something was wrong with the supplied certificate", ce);
+            LOG.error("Something was wrong with the supplied certificate", ce);
+            throw cmpClientException;
+        } catch (NoSuchProviderException nspe) {
+            CmpClientException cmpClientException =
+                    new CmpClientException("BouncyCastle provider not found.", nspe);
+            LOG.error("BouncyCastle provider not found.", nspe);
+            throw cmpClientException;
+        } catch (NoSuchAlgorithmException nsae) {
+            CmpClientException cmpClientException =
+                    new CmpClientException("Algorithm PKIX was not found.", nsae);
+            LOG.error("Algorithm PKIX was not found.", nsae);
+            throw cmpClientException;
+        } catch (InvalidAlgorithmParameterException iape) {
+            CmpClientException cmpClientException =
+                    new CmpClientException(
+                            "Either ca certificate chain was empty,"
+                                    + " or the certificate was on an inappropriate type for a PKIX path checker.",
+                            iape);
+            LOG.error(
+                    "Either ca certificate chain was empty, "
+                            + "or the certificate was on an inappropriate type for a PKIX path checker.",
+                    iape);
+            throw cmpClientException;
+        }
     }
-  }
 
-  public static PKIXParameters getPkixParameters(
-      X509Certificate caCertChain, Date date, PKIXCertPathChecker[] pkixCertPathCheckers)
-      throws InvalidAlgorithmParameterException {
-    TrustAnchor anchor = new TrustAnchor(caCertChain, null);
-    PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
-    for (final PKIXCertPathChecker pkixCertPathChecker : pkixCertPathCheckers) {
-      params.addCertPathChecker(pkixCertPathChecker);
+    public static void verifyCertificates(
+            X509Certificate certificate,
+            X509Certificate caCertChain,
+            Date date,
+            PKIXCertPathChecker[] pkixCertPathCheckers)
+            throws CertificateException, NoSuchProviderException, InvalidAlgorithmParameterException,
+            NoSuchAlgorithmException, CertPathValidatorException {
+        LOG.debug(
+                "Verifying certificate {} as part of cert chain with certificate {}",
+                certificate.getSubjectDN().getName(),
+                caCertChain.getSubjectDN().getName());
+        CertPath cp = getCertPath(certificate);
+        PKIXParameters params = getPkixParameters(caCertChain, date, pkixCertPathCheckers);
+        CertPathValidator cpv =
+                CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
+        PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Certificate verify result:{} ", result);
+        }
     }
-    params.setRevocationEnabled(false);
-    params.setDate(date);
-    return params;
-  }
 
-  public static CertPath getCertPath(X509Certificate certificate)
-      throws CertificateException, NoSuchProviderException {
-    ArrayList<X509Certificate> certlist = new ArrayList<>();
-    certlist.add(certificate);
-    return CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME)
-        .generateCertPath(certlist);
-  }
+    public static PKIXParameters getPkixParameters(
+            X509Certificate caCertChain, Date date, PKIXCertPathChecker[] pkixCertPathCheckers)
+            throws InvalidAlgorithmParameterException {
+        TrustAnchor anchor = new TrustAnchor(caCertChain, null);
+        PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
+        for (final PKIXCertPathChecker pkixCertPathChecker : pkixCertPathCheckers) {
+            params.addCertPathChecker(pkixCertPathChecker);
+        }
+        params.setRevocationEnabled(false);
+        params.setDate(date);
+        return params;
+    }
 
-  /**
-   * Parse a X509Certificate from an array of bytes
-   *
-   * @param provider a provider name
-   * @param cert a byte array containing an encoded certificate
-   * @return a decoded X509Certificate
-   * @throws CertificateParsingException if the byte array wasn't valid, or contained a certificate
-   *     other than an X509 Certificate.
-   */
-  public static Optional<X509Certificate> parseX509Certificate(String provider, byte[] cert)
-      throws CertificateParsingException, CmpClientException {
-    LOG.debug("Parsing X509Certificate from bytes with provider {}", provider);
-    final CertificateFactory cf = getCertificateFactory(provider);
-    X509Certificate result;
-    try {
-      result =
-          (X509Certificate)
-              Objects.requireNonNull(cf).generateCertificate(new ByteArrayInputStream(cert));
-    } catch (CertificateException ce) {
-      throw new CertificateParsingException("Could not parse byte array as X509Certificate ", ce);
+    public static CertPath getCertPath(X509Certificate certificate)
+            throws CertificateException, NoSuchProviderException {
+        ArrayList<X509Certificate> certlist = new ArrayList<>();
+        certlist.add(certificate);
+        return CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME)
+                .generateCertPath(certlist);
     }
-    if (result != null) {
-      return Optional.of(result);
-    } else {
-      throw new CertificateParsingException("Could not parse byte array as X509Certificate.");
+
+    /**
+     * Parse a X509Certificate from an array of bytes
+     *
+     * @param provider a provider name
+     * @param cert     a byte array containing an encoded certificate
+     * @return a decoded X509Certificate
+     * @throws CertificateParsingException if the byte array wasn't valid, or contained a certificate
+     *                                     other than an X509 Certificate.
+     */
+    public static Optional<X509Certificate> parseX509Certificate(String provider, byte[] cert)
+            throws CertificateParsingException, CmpClientException {
+        LOG.debug("Parsing X509Certificate from bytes with provider {}", provider);
+        final CertificateFactory cf = getCertificateFactory(provider);
+        X509Certificate result;
+        try {
+            result =
+                    (X509Certificate)
+                            Objects.requireNonNull(cf).generateCertificate(new ByteArrayInputStream(cert));
+        } catch (CertificateException ce) {
+            throw new CertificateParsingException("Could not parse byte array as X509Certificate ", ce);
+        }
+        if (result != null) {
+            return Optional.of(result);
+        } else {
+            throw new CertificateParsingException("Could not parse byte array as X509Certificate.");
+        }
     }
-  }
 
-  /**
-   * Returns a CertificateFactory that can be used to create certificates from byte arrays and such.
-   *
-   * @param provider Security provider that should be used to create certificates, default BC is
-   *     null is passed.
-   * @return CertificateFactory for creating certificate
-   */
-  public static CertificateFactory getCertificateFactory(final String provider)
-      throws CmpClientException {
-    LOG.debug("Creating certificate Factory to generate certificate using provider {}", provider);
-    final String prov;
-    prov = Objects.requireNonNullElse(provider, BouncyCastleProvider.PROVIDER_NAME);
-    try {
-      return CertificateFactory.getInstance("X.509", prov);
-    } catch (NoSuchProviderException nspe) {
-      CmpClientException cmpClientException = new CmpClientException("NoSuchProvider: ", nspe);
-      LOG.error("NoSuchProvider: ", nspe);
-      throw cmpClientException;
-    } catch (CertificateException ce) {
-      CmpClientException cmpClientException = new CmpClientException("CertificateException: ", ce);
-      LOG.error("CertificateException: ", ce);
-      throw cmpClientException;
+    /**
+     * Returns a CertificateFactory that can be used to create certificates from byte arrays and such.
+     *
+     * @param provider Security provider that should be used to create certificates, default BC is
+     *                 null is passed.
+     * @return CertificateFactory for creating certificate
+     */
+    public static CertificateFactory getCertificateFactory(final String provider)
+            throws CmpClientException {
+        LOG.debug("Creating certificate Factory to generate certificate using provider {}", provider);
+        final String prov;
+        prov = Objects.requireNonNullElse(provider, BouncyCastleProvider.PROVIDER_NAME);
+        try {
+            return CertificateFactory.getInstance("X.509", prov);
+        } catch (NoSuchProviderException nspe) {
+            CmpClientException cmpClientException = new CmpClientException("NoSuchProvider: ", nspe);
+            LOG.error("NoSuchProvider: ", nspe);
+            throw cmpClientException;
+        } catch (CertificateException ce) {
+            CmpClientException cmpClientException = new CmpClientException("CertificateException: ", ce);
+            LOG.error("CertificateException: ", ce);
+            throw cmpClientException;
+        }
     }
-  }
 
-  /**
-   * puts together certChain and Trust store and verifies the certChain
-   *
-   * @param respPkiMessage PKIMessage that may contain extra certs used for certchain
-   * @param certRepMessage CertRepMessage that should contain rootCA for certchain
-   * @param leafCertificate certificate returned from our original Cert Request
-   * @return list of two lists, CertChain and TrustStore
-   * @throws CertificateParsingException thrown if error occurs while parsing certificate
-   * @throws IOException thrown if IOException occurs while parsing certificate
-   * @throws CmpClientException thrown if error occurs during the verification of the certChain
-   */
-  public static List<List<X509Certificate>> verifyAndReturnCertChainAndTrustSTore(
-      PKIMessage respPkiMessage, CertRepMessage certRepMessage, X509Certificate leafCertificate)
-      throws CertificateParsingException, IOException, CmpClientException {
-    List<X509Certificate> certChain =
-        addExtraCertsToChain(respPkiMessage, certRepMessage, leafCertificate);
-    List<String> certNames = getNamesOfCerts(certChain);
-    LOG.debug("Verifying the following certificates in the cert chain: {}", certNames);
-    verify(certChain);
-    ArrayList<X509Certificate> trustStore = new ArrayList<>();
-    final int rootCaIndex = certChain.size() - 1;
-    trustStore.add(certChain.get(rootCaIndex));
-    certChain.remove(rootCaIndex);
-    List<List<X509Certificate>> listOfArray = new ArrayList<>();
-    listOfArray.add(certChain);
-    listOfArray.add(trustStore);
-    return listOfArray;
-  }
+    /**
+     * puts together certChain and Trust store and verifies the certChain
+     *
+     * @param respPkiMessage  PKIMessage that may contain extra certs used for certchain
+     * @param certRepMessage  CertRepMessage that should contain rootCA for certchain
+     * @param leafCertificate certificate returned from our original Cert Request
+     * @return list of two lists, CertChain and TrustStore
+     * @throws CertificateParsingException thrown if error occurs while parsing certificate
+     * @throws IOException                 thrown if IOException occurs while parsing certificate
+     * @throws CmpClientException          thrown if error occurs during the verification of the certChain
+     */
+    public static List<List<X509Certificate>> verifyAndReturnCertChainAndTrustSTore(
+            PKIMessage respPkiMessage, CertRepMessage certRepMessage, X509Certificate leafCertificate)
+            throws CertificateParsingException, IOException, CmpClientException {
+        List<X509Certificate> certChain =
+                addExtraCertsToChain(respPkiMessage, certRepMessage, leafCertificate);
+        List<String> certNames = getNamesOfCerts(certChain);
+        LOG.debug("Verifying the following certificates in the cert chain: {}", certNames);
+        verify(certChain);
+        ArrayList<X509Certificate> trustStore = new ArrayList<>();
+        final int rootCaIndex = certChain.size() - 1;
+        trustStore.add(certChain.get(rootCaIndex));
+        certChain.remove(rootCaIndex);
+        List<List<X509Certificate>> listOfArray = new ArrayList<>();
+        listOfArray.add(certChain);
+        listOfArray.add(trustStore);
+        return listOfArray;
+    }
 
-  public static List<String> getNamesOfCerts(List<X509Certificate> certChain) {
-    List<String> certNames = new ArrayList<>();
-    certChain.forEach(cert -> certNames.add(cert.getSubjectDN().getName()));
-    return certNames;
-  }
+    public static List<String> getNamesOfCerts(List<X509Certificate> certChain) {
+        List<String> certNames = new ArrayList<>();
+        certChain.forEach(cert -> certNames.add(cert.getSubjectDN().getName()));
+        return certNames;
+    }
 
-  /**
-   * checks whether PKIMessage contains extracerts to create certchain, if not creates from caPubs
-   *
-   * @param respPkiMessage PKIMessage that may contain extra certs used for certchain
-   * @param certRepMessage CertRepMessage that should contain rootCA for certchain
-   * @param leafCert certificate at top of certChain.
-   * @throws CertificateParsingException thrown if error occurs while parsing certificate
-   * @throws IOException thrown if IOException occurs while parsing certificate
-   * @throws CmpClientException thrown if there are errors creating CertificateFactory
-   */
-  public static List<X509Certificate> addExtraCertsToChain(
-      PKIMessage respPkiMessage, CertRepMessage certRepMessage, X509Certificate leafCert)
-      throws CertificateParsingException, IOException, CmpClientException {
-    List<X509Certificate> certChain = new ArrayList<>();
-    certChain.add(leafCert);
-    if (respPkiMessage.getExtraCerts() != null) {
-      final CMPCertificate[] extraCerts = respPkiMessage.getExtraCerts();
-      for (CMPCertificate cmpCert : extraCerts) {
-        Optional<X509Certificate> cert =
-            getCertfromByteArray(cmpCert.getEncoded(), X509Certificate.class);
-        certChain =
-            ifCertPresent(
-                certChain,
-                cert,
-                "Adding certificate from extra certs {} to cert chain",
-                "Couldn't add certificate from extra certs, certificate wasn't an X509Certificate");
-        return certChain;
-      }
-    } else {
-      final CMPCertificate respCmpCaCert = getRootCa(certRepMessage);
-      Optional<X509Certificate> cert =
-          getCertfromByteArray(respCmpCaCert.getEncoded(), X509Certificate.class);
-      certChain =
-          ifCertPresent(
-              certChain,
-              cert,
-              "Adding certificate from CaPubs {} to TrustStore",
-              "Couldn't add certificate from CaPubs, certificate wasn't an X509Certificate");
-      return certChain;
+    /**
+     * checks whether PKIMessage contains extracerts to create certchain, if not creates from caPubs
+     *
+     * @param respPkiMessage PKIMessage that may contain extra certs used for certchain
+     * @param certRepMessage CertRepMessage that should contain rootCA for certchain
+     * @param leafCert       certificate at top of certChain.
+     * @throws CertificateParsingException thrown if error occurs while parsing certificate
+     * @throws IOException                 thrown if IOException occurs while parsing certificate
+     * @throws CmpClientException          thrown if there are errors creating CertificateFactory
+     */
+    public static List<X509Certificate> addExtraCertsToChain(
+            PKIMessage respPkiMessage, CertRepMessage certRepMessage, X509Certificate leafCert)
+            throws CertificateParsingException, IOException, CmpClientException {
+        List<X509Certificate> certChain = new ArrayList<>();
+        certChain.add(leafCert);
+        if (respPkiMessage.getExtraCerts() != null) {
+            final CMPCertificate[] extraCerts = respPkiMessage.getExtraCerts();
+            for (CMPCertificate cmpCert : extraCerts) {
+                Optional<X509Certificate> cert =
+                        getCertfromByteArray(cmpCert.getEncoded(), X509Certificate.class);
+                certChain =
+                        ifCertPresent(
+                                certChain,
+                                cert,
+                                "Adding certificate from extra certs {} to cert chain",
+                                "Couldn't add certificate from extra certs, certificate wasn't an X509Certificate");
+                return certChain;
+            }
+        } else {
+            final CMPCertificate respCmpCaCert = getRootCa(certRepMessage);
+            Optional<X509Certificate> cert =
+                    getCertfromByteArray(respCmpCaCert.getEncoded(), X509Certificate.class);
+            certChain =
+                    ifCertPresent(
+                            certChain,
+                            cert,
+                            "Adding certificate from CaPubs {} to TrustStore",
+                            "Couldn't add certificate from CaPubs, certificate wasn't an X509Certificate");
+            return certChain;
+        }
+        return Collections.emptyList();
     }
-    return Collections.emptyList();
-  }
 
-  public static List<X509Certificate> ifCertPresent(
-      List<X509Certificate> certChain,
-      Optional<X509Certificate> cert,
-      String certPresentString,
-      String certUnavailableString) {
-    if (cert.isPresent()) {
-      LOG.debug(certPresentString, cert.get().getSubjectDN().getName());
-      certChain.add(cert.get());
-      return certChain;
-    } else {
-      LOG.debug(certUnavailableString);
-      return certChain;
+    public static List<X509Certificate> ifCertPresent(
+            List<X509Certificate> certChain,
+            Optional<X509Certificate> cert,
+            String certPresentString,
+            String certUnavailableString) {
+        if (cert.isPresent()) {
+            LOG.debug(certPresentString, cert.get().getSubjectDN().getName());
+            certChain.add(cert.get());
+            return certChain;
+        } else {
+            LOG.debug(certUnavailableString);
+            return certChain;
+        }
     }
-  }
 
-  private static CMPCertificate getRootCa(CertRepMessage certRepMessage) {
-    return certRepMessage.getCaPubs()[0];
-  }
+    private static CMPCertificate getRootCa(CertRepMessage certRepMessage) {
+        return certRepMessage.getCaPubs()[0];
+    }
 }
index 8191c69..4b9f2cd 100644 (file)
@@ -34,6 +34,7 @@ import java.util.Objects;
 import javax.crypto.Mac;
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
+
 import org.bouncycastle.asn1.ASN1Encodable;
 import org.bouncycastle.asn1.ASN1EncodableVector;
 import org.bouncycastle.asn1.ASN1ObjectIdentifier;
@@ -55,184 +56,186 @@ import org.slf4j.LoggerFactory;
 
 public final class CmpResponseValidationHelper {
 
-  private static final Logger LOG = LoggerFactory.getLogger(CmpResponseValidationHelper.class);
+    private static final Logger LOG = LoggerFactory.getLogger(CmpResponseValidationHelper.class);
+
+    private CmpResponseValidationHelper() {
+    }
 
-  private CmpResponseValidationHelper() {}
+    /**
+     * Create a base key to use for verifying the PasswordBasedMac on a PKIMessage
+     *
+     * @param pbmParamSeq      parameters recieved in PKIMessage used with password
+     * @param initAuthPassword password used to decrypt the basekey
+     * @return bytes representing the basekey
+     * @throws CmpClientException thrown if algorithem exceptions occur for the message digest
+     */
+    public static byte[] getBaseKeyFromPbmParameters(
+            PBMParameter pbmParamSeq, String initAuthPassword) throws CmpClientException {
+        final int iterationCount = pbmParamSeq.getIterationCount().getPositiveValue().intValue();
+        LOG.info("Iteration count is: {}", iterationCount);
+        final AlgorithmIdentifier owfAlg = pbmParamSeq.getOwf();
+        LOG.info("One Way Function type is: {}", owfAlg.getAlgorithm().getId());
+        final byte[] salt = pbmParamSeq.getSalt().getOctets();
+        final byte[] raSecret = initAuthPassword != null ? initAuthPassword.getBytes() : new byte[0];
+        byte[] basekey = new byte[raSecret.length + salt.length];
+        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
+        System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
+        try {
+            final MessageDigest messageDigest =
+                    MessageDigest.getInstance(
+                            owfAlg.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
+            for (int i = 0; i < iterationCount; i++) {
+                basekey = messageDigest.digest(basekey);
+                messageDigest.reset();
+            }
+        } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
+            LOG.error("ProtectionBytes don't match passwordBasedProtection, authentication failed");
+            throw new CmpClientException(
+                    "ProtectionBytes don't match passwordBasedProtection, authentication failed", ex);
+        }
+        return basekey;
+    }
 
-  /**
-   * Create a base key to use for verifying the PasswordBasedMac on a PKIMessage
-   *
-   * @param pbmParamSeq parameters recieved in PKIMessage used with password
-   * @param initAuthPassword password used to decrypt the basekey
-   * @return bytes representing the basekey
-   * @throws CmpClientException thrown if algorithem exceptions occur for the message digest
-   */
-  public static byte[] getBaseKeyFromPbmParameters(
-      PBMParameter pbmParamSeq, String initAuthPassword) throws CmpClientException {
-    final int iterationCount = pbmParamSeq.getIterationCount().getPositiveValue().intValue();
-    LOG.info("Iteration count is: {}", iterationCount);
-    final AlgorithmIdentifier owfAlg = pbmParamSeq.getOwf();
-    LOG.info("One Way Function type is: {}", owfAlg.getAlgorithm().getId());
-    final byte[] salt = pbmParamSeq.getSalt().getOctets();
-    final byte[] raSecret = initAuthPassword != null ? initAuthPassword.getBytes() : new byte[0];
-    byte[] basekey = new byte[raSecret.length + salt.length];
-    System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
-    System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
-    try {
-      final MessageDigest messageDigest =
-          MessageDigest.getInstance(
-              owfAlg.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
-      for (int i = 0; i < iterationCount; i++) {
-        basekey = messageDigest.digest(basekey);
-        messageDigest.reset();
-      }
-    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
-      LOG.error("ProtectionBytes don't match passwordBasedProtection, authentication failed");
-      throw new CmpClientException(
-          "ProtectionBytes don't match passwordBasedProtection, authentication failed", ex);
+    /**
+     * Verifies the signature of the response message using our public key
+     *
+     * @param respPkiMessage PKIMessage we wish to verify signature for
+     * @param pk             public key used to verify signature.
+     * @throws CmpClientException
+     */
+    public static void verifySignature(PKIMessage respPkiMessage, PublicKey pk)
+            throws CmpClientException {
+        final byte[] protBytes = getProtectedBytes(respPkiMessage);
+        final DERBitString derBitString = respPkiMessage.getProtection();
+        try {
+            final Signature signature =
+                    Signature.getInstance(
+                            PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(),
+                            BouncyCastleProvider.PROVIDER_NAME);
+            signature.initVerify(pk);
+            signature.update(protBytes);
+            signature.verify(derBitString.getBytes());
+        } catch (NoSuchAlgorithmException
+                | NoSuchProviderException
+                | InvalidKeyException
+                | SignatureException e) {
+            CmpClientException clientException =
+                    new CmpClientException("Signature Verification failed", e);
+            LOG.error("Signature Verification failed", e);
+            throw clientException;
+        }
     }
-    return basekey;
-  }
 
-  /**
-   * Verifies the signature of the response message using our public key
-   *
-   * @param respPkiMessage PKIMessage we wish to verify signature for
-   * @param pk public key used to verify signature.
-   * @throws CmpClientException
-   */
-  public static void verifySignature(PKIMessage respPkiMessage, PublicKey pk)
-      throws CmpClientException {
-    final byte[] protBytes = getProtectedBytes(respPkiMessage);
-    final DERBitString derBitString = respPkiMessage.getProtection();
-    try {
-      final Signature signature =
-          Signature.getInstance(
-              PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(),
-              BouncyCastleProvider.PROVIDER_NAME);
-      signature.initVerify(pk);
-      signature.update(protBytes);
-      signature.verify(derBitString.getBytes());
-    } catch (NoSuchAlgorithmException
-        | NoSuchProviderException
-        | InvalidKeyException
-        | SignatureException e) {
-      CmpClientException clientException =
-          new CmpClientException("Signature Verification failed", e);
-      LOG.error("Signature Verification failed", e);
-      throw clientException;
+    /**
+     * Converts the header and the body of a PKIMessage to an ASN1Encodable and returns the as a byte
+     * array
+     *
+     * @param msg PKIMessage to get protected bytes from
+     * @return the PKIMessage's header and body in byte array
+     */
+    public static byte[] getProtectedBytes(PKIMessage msg) throws CmpClientException {
+        return getProtectedBytes(msg.getHeader(), msg.getBody());
     }
-  }
-  /**
-   * Converts the header and the body of a PKIMessage to an ASN1Encodable and returns the as a byte
-   * array
-   *
-   * @param msg PKIMessage to get protected bytes from
-   * @return the PKIMessage's header and body in byte array
-   */
-  public static byte[] getProtectedBytes(PKIMessage msg) throws CmpClientException {
-    return getProtectedBytes(msg.getHeader(), msg.getBody());
-  }
 
-  /**
-   * Converts the header and the body of a PKIMessage to an ASN1Encodable and returns the as a byte
-   * array
-   *
-   * @param header PKIHeader to be converted
-   * @param body PKIMessage to be converted
-   * @return the PKIMessage's header and body in byte array
-   */
-  public static byte[] getProtectedBytes(PKIHeader header, PKIBody body) throws CmpClientException {
-    byte[] res;
-    ASN1EncodableVector v = new ASN1EncodableVector();
-    v.add(header);
-    v.add(body);
-    ASN1Encodable protectedPart = new DERSequence(v);
-    try {
-      ByteArrayOutputStream bao = new ByteArrayOutputStream();
-      DEROutputStream out = new DEROutputStream(bao);
-      out.writeObject(protectedPart);
-      res = bao.toByteArray();
-    } catch (IOException ioe) {
-      CmpClientException cmpClientException =
-          new CmpClientException("Error occured while getting protected bytes", ioe);
-      LOG.error("Error occured while getting protected bytes", ioe);
-      throw cmpClientException;
+    /**
+     * Converts the header and the body of a PKIMessage to an ASN1Encodable and returns the as a byte
+     * array
+     *
+     * @param header PKIHeader to be converted
+     * @param body   PKIMessage to be converted
+     * @return the PKIMessage's header and body in byte array
+     */
+    public static byte[] getProtectedBytes(PKIHeader header, PKIBody body) throws CmpClientException {
+        byte[] res;
+        ASN1EncodableVector encodableVector = new ASN1EncodableVector();
+        encodableVector.add(header);
+        encodableVector.add(body);
+        ASN1Encodable protectedPart = new DERSequence(encodableVector);
+        try {
+            ByteArrayOutputStream bao = new ByteArrayOutputStream();
+            DEROutputStream out = new DEROutputStream(bao);
+            out.writeObject(protectedPart);
+            res = bao.toByteArray();
+        } catch (IOException ioe) {
+            CmpClientException cmpClientException =
+                    new CmpClientException("Error occured while getting protected bytes", ioe);
+            LOG.error("Error occured while getting protected bytes", ioe);
+            throw cmpClientException;
+        }
+        return res;
     }
-    return res;
-  }
 
-  /**
-   * verify the password based protection within the response message
-   *
-   * @param respPkiMessage PKIMessage we want to verify password based protection for
-   * @param initAuthPassword password used to decrypt protection
-   * @param protectionAlgo protection algorithm we can use to decrypt protection
-   * @throws CmpClientException
-   */
-  public static void verifyPasswordBasedProtection(
-      PKIMessage respPkiMessage, String initAuthPassword, AlgorithmIdentifier protectionAlgo)
-      throws CmpClientException {
-    final byte[] protectedBytes = getProtectedBytes(respPkiMessage);
-    final PBMParameter pbmParamSeq = PBMParameter.getInstance(protectionAlgo.getParameters());
-    if (Objects.nonNull(pbmParamSeq)) {
-      try {
-        byte[] basekey = getBaseKeyFromPbmParameters(pbmParamSeq, initAuthPassword);
-        final Mac mac = getMac(protectedBytes, pbmParamSeq, basekey);
-        final byte[] outBytes = mac.doFinal();
-        final byte[] protectionBytes = respPkiMessage.getProtection().getBytes();
-        if (!Arrays.equals(outBytes, protectionBytes)) {
-          LOG.error("protectionBytes don't match passwordBasedProtection, authentication failed");
-          throw new CmpClientException(
-              "protectionBytes don't match passwordBasedProtection, authentication failed");
+    /**
+     * verify the password based protection within the response message
+     *
+     * @param respPkiMessage   PKIMessage we want to verify password based protection for
+     * @param initAuthPassword password used to decrypt protection
+     * @param protectionAlgo   protection algorithm we can use to decrypt protection
+     * @throws CmpClientException
+     */
+    public static void verifyPasswordBasedProtection(
+            PKIMessage respPkiMessage, String initAuthPassword, AlgorithmIdentifier protectionAlgo)
+            throws CmpClientException {
+        final byte[] protectedBytes = getProtectedBytes(respPkiMessage);
+        final PBMParameter pbmParamSeq = PBMParameter.getInstance(protectionAlgo.getParameters());
+        if (Objects.nonNull(pbmParamSeq)) {
+            try {
+                byte[] basekey = getBaseKeyFromPbmParameters(pbmParamSeq, initAuthPassword);
+                final Mac mac = getMac(protectedBytes, pbmParamSeq, basekey);
+                final byte[] outBytes = mac.doFinal();
+                final byte[] protectionBytes = respPkiMessage.getProtection().getBytes();
+                if (!Arrays.equals(outBytes, protectionBytes)) {
+                    LOG.error("protectionBytes don't match passwordBasedProtection, authentication failed");
+                    throw new CmpClientException(
+                            "protectionBytes don't match passwordBasedProtection, authentication failed");
+                }
+            } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidKeyException ex) {
+                CmpClientException cmpClientException =
+                        new CmpClientException("Error while validating CMP response ", ex);
+                LOG.error("Error while validating CMP response ", ex);
+                throw cmpClientException;
+            }
         }
-      } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidKeyException ex) {
-        CmpClientException cmpClientException =
-            new CmpClientException("Error while validating CMP response ", ex);
-        LOG.error("Error while validating CMP response ", ex);
-        throw cmpClientException;
-      }
     }
-  }
 
-  public static void checkImplicitConfirm(PKIHeader header) {
-    InfoTypeAndValue[] infos = header.getGeneralInfo();
-    if (Objects.nonNull(infos)) {
-      if (CMPObjectIdentifiers.it_implicitConfirm.equals(getImplicitConfirm(infos))) {
-        LOG.info("Implicit Confirm on certificate from server.");
-      } else {
-        LOG.debug("No Implicit confirm in Response");
-      }
-    } else {
-      LOG.debug("No general Info in header of response, cannot verify implicit confirm");
+    public static void checkImplicitConfirm(PKIHeader header) {
+        InfoTypeAndValue[] infos = header.getGeneralInfo();
+        if (Objects.nonNull(infos)) {
+            if (CMPObjectIdentifiers.it_implicitConfirm.equals(getImplicitConfirm(infos))) {
+                LOG.info("Implicit Confirm on certificate from server.");
+            } else {
+                LOG.debug("No Implicit confirm in Response");
+            }
+        } else {
+            LOG.debug("No general Info in header of response, cannot verify implicit confirm");
+        }
     }
-  }
 
-  public static ASN1ObjectIdentifier getImplicitConfirm(InfoTypeAndValue[] info) {
-    return info[0].getInfoType();
-  }
+    public static ASN1ObjectIdentifier getImplicitConfirm(InfoTypeAndValue[] info) {
+        return info[0].getInfoType();
+    }
 
-  /**
-   * Get cryptographical Mac we can use to decrypt our PKIMessage
-   *
-   * @param protectedBytes Protected bytes representing the PKIMessage
-   * @param pbmParamSeq Parameters used to decrypt PKIMessage, including mac algorithm used
-   * @param basekey Key used alongside mac Oid to create secret key for decrypting PKIMessage
-   * @return Mac that's ready to return decrypted bytes
-   * @throws NoSuchAlgorithmException Possibly thrown trying to get mac instance
-   * @throws NoSuchProviderException Possibly thrown trying to get mac instance
-   * @throws InvalidKeyException Possibly thrown trying to initialize mac using secretkey
-   */
-  public static Mac getMac(byte[] protectedBytes, PBMParameter pbmParamSeq, byte[] basekey)
-      throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
-    final AlgorithmIdentifier macAlg = pbmParamSeq.getMac();
-    LOG.info("Mac type is: {}", macAlg.getAlgorithm().getId());
-    final String macOid = macAlg.getAlgorithm().getId();
-    final Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
-    final SecretKey key = new SecretKeySpec(basekey, macOid);
-    mac.init(key);
-    mac.reset();
-    mac.update(protectedBytes, 0, protectedBytes.length);
-    return mac;
-  }
+    /**
+     * Get cryptographical Mac we can use to decrypt our PKIMessage
+     *
+     * @param protectedBytes Protected bytes representing the PKIMessage
+     * @param pbmParamSeq    Parameters used to decrypt PKIMessage, including mac algorithm used
+     * @param basekey        Key used alongside mac Oid to create secret key for decrypting PKIMessage
+     * @return Mac that's ready to return decrypted bytes
+     * @throws NoSuchAlgorithmException Possibly thrown trying to get mac instance
+     * @throws NoSuchProviderException  Possibly thrown trying to get mac instance
+     * @throws InvalidKeyException      Possibly thrown trying to initialize mac using secretkey
+     */
+    public static Mac getMac(byte[] protectedBytes, PBMParameter pbmParamSeq, byte[] basekey)
+            throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
+        final AlgorithmIdentifier macAlg = pbmParamSeq.getMac();
+        LOG.info("Mac type is: {}", macAlg.getAlgorithm().getId());
+        final String macOid = macAlg.getAlgorithm().getId();
+        final Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
+        final SecretKey key = new SecretKeySpec(basekey, macOid);
+        mac.init(key);
+        mac.reset();
+        mac.update(protectedBytes, 0, protectedBytes.length);
+        return mac;
+    }
 }
index 1bda4ac..ced0fed 100644 (file)
@@ -25,6 +25,7 @@ import java.io.IOException;
 import java.security.SecureRandom;
 import java.util.Date;
 import java.util.Objects;
+
 import org.bouncycastle.asn1.ASN1Encodable;
 import org.bouncycastle.asn1.ASN1EncodableVector;
 import org.bouncycastle.asn1.ASN1GeneralizedTime;
@@ -45,105 +46,108 @@ import org.slf4j.LoggerFactory;
 
 public final class CmpUtil {
 
-  private static final Logger LOGGER = LoggerFactory.getLogger(CmpUtil.class);
-  private static final SecureRandom secureRandom = new SecureRandom();
+    private static final Logger LOGGER = LoggerFactory.getLogger(CmpUtil.class);
+    private static final SecureRandom SECURE_RANDOM = new SecureRandom();
+    public static final int RANDOM_BYTE_LENGTH = 16;
+    public static final int RANDOM_SEED = 1000;
 
-  private CmpUtil() {}
+    private CmpUtil() {
+    }
 
-  /**
-   * Validates specified object reference is not null.
-   *
-   * @param argument T - the type of the reference.
-   * @param message message - detail message to be used in the event that a NullPointerException is
-   *     thrown.
-   * @return The Object if not null
-   */
-  public static <T> T notNull(T argument, String message) {
-    return Objects.requireNonNull(argument, message + " must not be null");
-  }
+    /**
+     * Validates specified object reference is not null.
+     *
+     * @param argument T - the type of the reference.
+     * @param message  message - detail message to be used in the event that a NullPointerException is
+     *                 thrown.
+     * @return The Object if not null
+     */
+    public static <T> T notNull(T argument, String message) {
+        return Objects.requireNonNull(argument, message + " must not be null");
+    }
 
-  /**
-   * Validates String object reference is not null and not empty.
-   *
-   * @param stringArg String Object that need to be validated.
-   * @return boolean
-   */
-  public static boolean isNullOrEmpty(String stringArg) {
-    return (stringArg != null && !stringArg.trim().isEmpty());
-  }
+    /**
+     * Validates String object reference is not null and not empty.
+     *
+     * @param stringArg String Object that need to be validated.
+     * @return boolean
+     */
+    public static boolean isNullOrEmpty(String stringArg) {
+        return (stringArg != null && !stringArg.trim().isEmpty());
+    }
 
-  /**
-   * Creates a random number than can be used for sendernonce, transactionId and salts.
-   *
-   * @return bytes containing a random number string representing a nonce
-   */
-  static byte[] createRandomBytes() {
-    LOGGER.info("Generating random array of bytes");
-    byte[] randomBytes = new byte[16];
-    secureRandom.nextBytes(randomBytes);
-    return randomBytes;
-  }
+    /**
+     * Creates a random number than can be used for sendernonce, transactionId and salts.
+     *
+     * @return bytes containing a random number string representing a nonce
+     */
+    static byte[] createRandomBytes() {
+        LOGGER.info("Generating random array of bytes");
+        byte[] randomBytes = new byte[RANDOM_BYTE_LENGTH];
+        SECURE_RANDOM.nextBytes(randomBytes);
+        return randomBytes;
+    }
 
-  /**
-   * Creates a random integer than can be used to represent a transactionId or determine the number
-   * iterations in a protection algorithm.
-   *
-   * @return bytes containing a random number string representing a nonce
-   */
-  static int createRandomInt(int range) {
-    LOGGER.info("Generating random integer");
-    return secureRandom.nextInt(range) + 1000;
-  }
+    /**
+     * Creates a random integer than can be used to represent a transactionId or determine the number
+     * iterations in a protection algorithm.
+     *
+     * @return bytes containing a random number string representing a nonce
+     */
+    static int createRandomInt(int range) {
+        LOGGER.info("Generating random integer");
+        return SECURE_RANDOM.nextInt(range) + RANDOM_SEED;
+    }
 
-  /**
-   * Generates protected bytes of a combined PKIHeader and PKIBody.
-   *
-   * @param header Header of PKIMessage containing common parameters
-   * @param body Body of PKIMessage containing specific information for message
-   * @return bytes representing the PKIHeader and PKIBody thats to be protected
-   */
-  static byte[] generateProtectedBytes(PKIHeader header, PKIBody body) throws CmpClientException {
-    LOGGER.info("Generating array of bytes representing PkiHeader and PkiBody");
-    byte[] res;
-    ASN1EncodableVector vector = new ASN1EncodableVector();
-    vector.add(header);
-    vector.add(body);
-    ASN1Encodable protectedPart = new DERSequence(vector);
-    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
-      DEROutputStream out = new DEROutputStream(baos);
-      out.writeObject(protectedPart);
-      res = baos.toByteArray();
-    } catch (IOException ioe) {
-      CmpClientException cmpClientException =
-          new CmpClientException("IOException occurred while creating protectedBytes", ioe);
-      LOGGER.error("IOException occurred while creating protectedBytes");
-      throw cmpClientException;
+    /**
+     * Generates protected bytes of a combined PKIHeader and PKIBody.
+     *
+     * @param header Header of PKIMessage containing common parameters
+     * @param body   Body of PKIMessage containing specific information for message
+     * @return bytes representing the PKIHeader and PKIBody thats to be protected
+     */
+    static byte[] generateProtectedBytes(PKIHeader header, PKIBody body) throws CmpClientException {
+        LOGGER.info("Generating array of bytes representing PkiHeader and PkiBody");
+        byte[] res;
+        ASN1EncodableVector vector = new ASN1EncodableVector();
+        vector.add(header);
+        vector.add(body);
+        ASN1Encodable protectedPart = new DERSequence(vector);
+        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+            DEROutputStream out = new DEROutputStream(baos);
+            out.writeObject(protectedPart);
+            res = baos.toByteArray();
+        } catch (IOException ioe) {
+            CmpClientException cmpClientException =
+                    new CmpClientException("IOException occurred while creating protectedBytes", ioe);
+            LOGGER.error("IOException occurred while creating protectedBytes");
+            throw cmpClientException;
+        }
+        return res;
     }
-    return res;
-  }
 
-  /**
-   * Generates a PKIHeader Builder object.
-   *
-   * @param subjectDn distinguished name of Subject
-   * @param issuerDn distinguished name of external CA
-   * @param protectionAlg protection Algorithm used to protect PKIMessage
-   * @return PKIHeaderBuilder
-   */
-  static PKIHeader generatePkiHeader(
-      X500Name subjectDn, X500Name issuerDn, AlgorithmIdentifier protectionAlg, String senderKid) {
-    LOGGER.info("Generating a Pki Header Builder");
-    PKIHeaderBuilder pkiHeaderBuilder =
-        new PKIHeaderBuilder(
-            PKIHeader.CMP_2000, new GeneralName(subjectDn), new GeneralName(issuerDn));
+    /**
+     * Generates a PKIHeader Builder object.
+     *
+     * @param subjectDn     distinguished name of Subject
+     * @param issuerDn      distinguished name of external CA
+     * @param protectionAlg protection Algorithm used to protect PKIMessage
+     * @return PKIHeaderBuilder
+     */
+    static PKIHeader generatePkiHeader(
+            X500Name subjectDn, X500Name issuerDn, AlgorithmIdentifier protectionAlg, String senderKid) {
+        LOGGER.info("Generating a Pki Header Builder");
+        PKIHeaderBuilder pkiHeaderBuilder =
+                new PKIHeaderBuilder(
+                        PKIHeader.CMP_2000, new GeneralName(subjectDn), new GeneralName(issuerDn));
 
-    pkiHeaderBuilder.setMessageTime(new ASN1GeneralizedTime(new Date()));
-    pkiHeaderBuilder.setSenderNonce(new DEROctetString(createRandomBytes()));
-    pkiHeaderBuilder.setTransactionID(new DEROctetString(createRandomBytes()));
-    pkiHeaderBuilder.setProtectionAlg(protectionAlg);
-    pkiHeaderBuilder.setGeneralInfo(new InfoTypeAndValue(CMPObjectIdentifiers.it_implicitConfirm));
-    pkiHeaderBuilder.setSenderKID(new DEROctetString(senderKid.getBytes()));
+        pkiHeaderBuilder.setMessageTime(new ASN1GeneralizedTime(new Date()));
+        pkiHeaderBuilder.setSenderNonce(new DEROctetString(createRandomBytes()));
+        pkiHeaderBuilder.setTransactionID(new DEROctetString(createRandomBytes()));
+        pkiHeaderBuilder.setProtectionAlg(protectionAlg);
+        pkiHeaderBuilder.setGeneralInfo(new InfoTypeAndValue(CMPObjectIdentifiers.it_implicitConfirm));
+        pkiHeaderBuilder.setSenderKID(new DEROctetString(senderKid.getBytes()));
 
-    return pkiHeaderBuilder.build();
-  }
+        return pkiHeaderBuilder.build();
+    }
 }
index 682e410..68c743d 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.aaf.certservice.cmpv2client.impl;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+
 import org.apache.http.client.methods.CloseableHttpResponse;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.entity.ByteArrayEntity;
@@ -33,50 +34,50 @@ import org.slf4j.LoggerFactory;
 
 class Cmpv2HttpClient {
 
-  private static final Logger LOG = LoggerFactory.getLogger(Cmpv2HttpClient.class);
+    private static final Logger LOG = LoggerFactory.getLogger(Cmpv2HttpClient.class);
 
-  private static final String CONTENT_TYPE = "Content-type";
-  private static final String CMP_REQUEST_MIMETYPE = "application/pkixcmp";
-  private final CloseableHttpClient httpClient;
+    private static final String CONTENT_TYPE = "Content-type";
+    private static final String CMP_REQUEST_MIMETYPE = "application/pkixcmp";
+    private final CloseableHttpClient httpClient;
 
-  /**
-   * constructor for Cmpv2HttpClient
-   *
-   * @param httpClient CloseableHttpClient used for sending/recieve request.
-   */
-  public Cmpv2HttpClient(CloseableHttpClient httpClient) {
-    this.httpClient = httpClient;
-  }
+    /**
+     * constructor for Cmpv2HttpClient
+     *
+     * @param httpClient CloseableHttpClient used for sending/recieve request.
+     */
+    Cmpv2HttpClient(CloseableHttpClient httpClient) {
+        this.httpClient = httpClient;
+    }
 
-  /**
-   * Send Post Request to Server
-   *
-   * @param pkiMessage PKIMessage to send to server
-   * @param urlString url for the server we're sending request
-   * @param caName name of CA server
-   * @return PKIMessage received from CMPServer
-   * @throws CmpClientException thrown if problems with connecting or parsing response to server
-   */
-  public byte[] postRequest(
-      final PKIMessage pkiMessage, final String urlString, final String caName)
-      throws CmpClientException {
-    try (final ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream()) {
-      final HttpPost postRequest = new HttpPost(urlString);
-      final byte[] requestBytes = pkiMessage.getEncoded();
+    /**
+     * Send Post Request to Server
+     *
+     * @param pkiMessage PKIMessage to send to server
+     * @param urlString  url for the server we're sending request
+     * @param caName     name of CA server
+     * @return PKIMessage received from CMPServer
+     * @throws CmpClientException thrown if problems with connecting or parsing response to server
+     */
+    public byte[] postRequest(
+            final PKIMessage pkiMessage, final String urlString, final String caName)
+            throws CmpClientException {
+        try (ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream()) {
+            final HttpPost postRequest = new HttpPost(urlString);
+            final byte[] requestBytes = pkiMessage.getEncoded();
 
-      postRequest.setEntity(new ByteArrayEntity(requestBytes));
-      postRequest.setHeader(CONTENT_TYPE, CMP_REQUEST_MIMETYPE);
+            postRequest.setEntity(new ByteArrayEntity(requestBytes));
+            postRequest.setHeader(CONTENT_TYPE, CMP_REQUEST_MIMETYPE);
 
-      try (CloseableHttpResponse response = httpClient.execute(postRequest)) {
-        response.getEntity().writeTo(byteArrOutputStream);
-      }
-      return byteArrOutputStream.toByteArray();
-    } catch (IOException ioe) {
-      CmpClientException cmpClientException =
-          new CmpClientException(
-              String.format("IOException error while trying to connect CA %s", caName), ioe);
-      LOG.error("IOException error {}, while trying to connect CA {}", ioe.getMessage(), caName);
-      throw cmpClientException;
+            try (CloseableHttpResponse response = httpClient.execute(postRequest)) {
+                response.getEntity().writeTo(byteArrOutputStream);
+            }
+            return byteArrOutputStream.toByteArray();
+        } catch (IOException ioe) {
+            CmpClientException cmpClientException =
+                    new CmpClientException(
+                            String.format("IOException error while trying to connect CA %s", caName), ioe);
+            LOG.error("IOException error {}, while trying to connect CA {}", ioe.getMessage(), caName);
+            throw cmpClientException;
+        }
     }
-  }
 }
index b185c92..687c47d 100644 (file)
@@ -27,6 +27,7 @@ import static org.onap.aaf.certservice.cmpv2client.impl.CmpUtil.generatePkiHeade
 import java.security.KeyPair;
 import java.util.Date;
 import java.util.List;
+
 import org.bouncycastle.asn1.DERUTF8String;
 import org.bouncycastle.asn1.cmp.PKIBody;
 import org.bouncycastle.asn1.cmp.PKIHeader;
@@ -48,88 +49,88 @@ import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
  */
 class CreateCertRequest {
 
-  private X500Name issuerDn;
-  private X500Name subjectDn;
-  private List<String> sansList;
-  private KeyPair subjectKeyPair;
-  private Date notBefore;
-  private Date notAfter;
-  private String initAuthPassword;
-  private String senderKid;
-
-  private static final int ITERATIONS = createRandomInt(5000);
-  private static final byte[] SALT = createRandomBytes();
-  private final int certReqId = createRandomInt(Integer.MAX_VALUE);
-
-  public void setIssuerDn(X500Name issuerDn) {
-    this.issuerDn = issuerDn;
-  }
-
-  public void setSubjectDn(X500Name subjectDn) {
-    this.subjectDn = subjectDn;
-  }
-
-  public void setSansList(List<String> sansList) {
-    this.sansList = sansList;
-  }
-
-  public void setSubjectKeyPair(KeyPair subjectKeyPair) {
-    this.subjectKeyPair = subjectKeyPair;
-  }
-
-  public void setNotBefore(Date notBefore) {
-    this.notBefore = notBefore;
-  }
-
-  public void setNotAfter(Date notAfter) {
-    this.notAfter = notAfter;
-  }
-
-  public void setInitAuthPassword(String initAuthPassword) {
-    this.initAuthPassword = initAuthPassword;
-  }
-
-  public void setSenderKid(String senderKid) {
-    this.senderKid = senderKid;
-  }
-
-  /**
-   * Method to create {@link PKIMessage} from {@link CertRequest},{@link ProofOfPossession}, {@link
-   * CertReqMsg}, {@link CertReqMessages}, {@link PKIHeader} and {@link PKIBody}.
-   *
-   * @return {@link PKIMessage}
-   */
-  public PKIMessage generateCertReq() throws CmpClientException {
-    final CertTemplateBuilder certTemplateBuilder =
-        new CertTemplateBuilder()
-            .setIssuer(issuerDn)
-            .setSubject(subjectDn)
-            .setExtensions(CmpMessageHelper.generateExtension(sansList))
-            .setValidity(CmpMessageHelper.generateOptionalValidity(notBefore, notAfter))
-            .setPublicKey(
-                SubjectPublicKeyInfo.getInstance(subjectKeyPair.getPublic().getEncoded()));
-
-    final CertRequest certRequest = new CertRequest(certReqId, certTemplateBuilder.build(), null);
-    final ProofOfPossession proofOfPossession =
-        CmpMessageHelper.generateProofOfPossession(certRequest, subjectKeyPair);
-
-    final AttributeTypeAndValue[] attrTypeVal = {
-      new AttributeTypeAndValue(
-          CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String(initAuthPassword))
-    };
-
-    final CertReqMsg certReqMsg = new CertReqMsg(certRequest, proofOfPossession, attrTypeVal);
-    final CertReqMessages certReqMessages = new CertReqMessages(certReqMsg);
-
-    final PKIHeader pkiHeader =
-        generatePkiHeader(
-            subjectDn,
-            issuerDn,
-            CmpMessageHelper.protectionAlgoIdentifier(ITERATIONS, SALT),
-            senderKid);
-    final PKIBody pkiBody = new PKIBody(PKIBody.TYPE_INIT_REQ, certReqMessages);
-
-    return CmpMessageHelper.protectPkiMessage(
-        pkiHeader, pkiBody, initAuthPassword, ITERATIONS, SALT);
-  }
+    private X500Name issuerDn;
+    private X500Name subjectDn;
+    private List<String> sansList;
+    private KeyPair subjectKeyPair;
+    private Date notBefore;
+    private Date notAfter;
+    private String initAuthPassword;
+    private String senderKid;
+
+    private static final int ITERATIONS = createRandomInt(5000);
+    private static final byte[] SALT = createRandomBytes();
+    private final int certReqId = createRandomInt(Integer.MAX_VALUE);
+
+    public void setIssuerDn(X500Name issuerDn) {
+        this.issuerDn = issuerDn;
+    }
+
+    public void setSubjectDn(X500Name subjectDn) {
+        this.subjectDn = subjectDn;
+    }
+
+    public void setSansList(List<String> sansList) {
+        this.sansList = sansList;
+    }
+
+    public void setSubjectKeyPair(KeyPair subjectKeyPair) {
+        this.subjectKeyPair = subjectKeyPair;
+    }
+
+    public void setNotBefore(Date notBefore) {
+        this.notBefore = notBefore;
+    }
+
+    public void setNotAfter(Date notAfter) {
+        this.notAfter = notAfter;
+    }
+
+    public void setInitAuthPassword(String initAuthPassword) {
+        this.initAuthPassword = initAuthPassword;
+    }
+
+    public void setSenderKid(String senderKid) {
+        this.senderKid = senderKid;
+    }
+
+    /**
+     * Method to create {@link PKIMessage} from {@link CertRequest},{@link ProofOfPossession}, {@link
+     * CertReqMsg}, {@link CertReqMessages}, {@link PKIHeader} and {@link PKIBody}.
+     *
+     * @return {@link PKIMessage}
+     */
+    public PKIMessage generateCertReq() throws CmpClientException {
+        final CertTemplateBuilder certTemplateBuilder =
+                new CertTemplateBuilder()
+                        .setIssuer(issuerDn)
+                        .setSubject(subjectDn)
+                        .setExtensions(CmpMessageHelper.generateExtension(sansList))
+                        .setValidity(CmpMessageHelper.generateOptionalValidity(notBefore, notAfter))
+                        .setPublicKey(
+                                SubjectPublicKeyInfo.getInstance(subjectKeyPair.getPublic().getEncoded()));
+
+        final CertRequest certRequest = new CertRequest(certReqId, certTemplateBuilder.build(), null);
+        final ProofOfPossession proofOfPossession =
+                CmpMessageHelper.generateProofOfPossession(certRequest, subjectKeyPair);
+
+        final AttributeTypeAndValue[] attrTypeVal = {
+                new AttributeTypeAndValue(
+                        CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String(initAuthPassword))
+        };
+
+        final CertReqMsg certReqMsg = new CertReqMsg(certRequest, proofOfPossession, attrTypeVal);
+        final CertReqMessages certReqMessages = new CertReqMessages(certReqMsg);
+
+        final PKIHeader pkiHeader =
+                generatePkiHeader(
+                        subjectDn,
+                        issuerDn,
+                        CmpMessageHelper.protectionAlgoIdentifier(ITERATIONS, SALT),
+                        senderKid);
+        final PKIBody pkiBody = new PKIBody(PKIBody.TYPE_INIT_REQ, certReqMessages);
+
+        return CmpMessageHelper.protectPkiMessage(
+                pkiHeader, pkiBody, initAuthPassword, ITERATIONS, SALT);
+    }
 }
index ae284da..0dc60aa 100644 (file)
@@ -27,8 +27,8 @@ import org.springframework.boot.test.context.SpringBootTest;
 class CertServiceApplicationTests {
 
     @Test
-    // We are excluding this line in Sonar due to fact that
-    // this test checks if Spring context is loaded and does not require assertion
+        // We are excluding this line in Sonar due to fact that
+        // this test checks if Spring context is loaded and does not require assertion
     void contextLoads() { // NOSONAR
     }
 }
index 8ebac68..449670c 100644 (file)
@@ -26,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.Mockito.when;
 
 import java.util.Arrays;
+
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
index 4000a38..d3ed730 100644 (file)
@@ -42,7 +42,8 @@ public class ReadinessControllerTest {
         Mockito.when(cmpServersConfig.isReady()).thenReturn(true);
 
         // Then
-        assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.OK);;
+        assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.OK);
+        ;
     }
 
     @Test
@@ -51,7 +52,8 @@ public class ReadinessControllerTest {
         Mockito.when(cmpServersConfig.isReady()).thenReturn(false);
 
         // Then
-        assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);;
+        assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
+        ;
     }
 
 }
index 5e0e355..92c18e1 100644 (file)
@@ -66,8 +66,8 @@ public class ReloadConfigControllerTest {
 
         // When
         Exception exception = assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> reloadConfigController.reloadConfiguration());
+                CmpServersConfigLoadingException.class,
+                () -> reloadConfigController.reloadConfiguration());
 
         // Then
         Assertions.assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE);
index 1b896a4..a63c8e0 100644 (file)
@@ -69,9 +69,9 @@ class CertificationModelFactoryTest {
     @Mock
     private Cmpv2ServerProvider cmpv2ServerProvider;
     @Mock
-    private  CsrModelFactory csrModelFactory;
+    private CsrModelFactory csrModelFactory;
     @Mock
-    private  CertificationProvider certificationProvider;
+    private CertificationProvider certificationProvider;
 
 
     private static String getEncodedString(String testCsr) {
@@ -95,7 +95,7 @@ class CertificationModelFactoryTest {
 
         // When
         CertificationModel certificationModel =
-                certificationModelFactory.createCertificationModel(ENCODED_CSR, ENCODED_PK,TEST_CA);
+                certificationModelFactory.createCertificationModel(ENCODED_CSR, ENCODED_PK, TEST_CA);
 
         // Then
         assertEquals(2, certificationModel.getCertificateChain().size());
@@ -105,7 +105,7 @@ class CertificationModelFactoryTest {
     }
 
     @Test
-    void shouldThrowDecryptionExceptionWhenGivenWrongEncodedCSR()
+    void shouldThrowDecryptionExceptionWhenGivenWrongEncodedCsr()
             throws DecryptionException {
         // Given
         String expectedMessage = "Incorrect CSR, decryption failed";
index aa6f1d0..f75bd60 100644 (file)
@@ -17,6 +17,7 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
+
 package org.onap.aaf.certservice.certification;
 
 import org.junit.jupiter.api.BeforeEach;
index 772f456..d2c3c54 100644 (file)
@@ -127,7 +127,7 @@ class CsrModelFactoryTest {
     }
 
     @Test
-    void shouldThrowKeyDecryptionExceptionWhenPKIsNotInBase64Encoding() {
+    void shouldThrowKeyDecryptionExceptionWhenPkIsNotInBase64Encoding() {
         // given
         String encoderPK = "Not Base64 Key";
         String wrongCsr = new String(Base64.encode(TEST_CSR.getBytes()));
index 296f63c..32fd207 100644 (file)
@@ -22,7 +22,6 @@ package org.onap.aaf.certservice.certification.adapter;
 
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.StringWriter;
 import java.nio.charset.StandardCharsets;
 import java.security.NoSuchProviderException;
 import java.security.PrivateKey;
@@ -32,6 +31,7 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
+
 import org.apache.commons.io.IOUtils;
 import org.bouncycastle.asn1.x509.Certificate;
 import org.bouncycastle.cert.X509CertificateHolder;
@@ -51,7 +51,7 @@ import org.onap.aaf.certservice.certification.model.CertificationModel;
 import org.onap.aaf.certservice.certification.model.CsrModel;
 import org.onap.aaf.certservice.cmpv2client.api.CmpClient;
 import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
-import org.onap.aaf.certservice.cmpv2client.external.CSRMeta;
+import org.onap.aaf.certservice.cmpv2client.external.CsrMeta;
 import org.springframework.boot.test.context.SpringBootTest;
 
 @SpringBootTest
@@ -64,7 +64,7 @@ class Cmpv2ClientAdapterTest {
     @Mock
     private Cmpv2Server server;
     @Mock
-    private RSAContentSignerBuilder rsaContentSignerBuilder;
+    private RsaContentSignerBuilder rsaContentSignerBuilder;
     @Mock
     private X509CertificateBuilder x509CertificateBuilder;
     @Mock
@@ -84,9 +84,9 @@ class Cmpv2ClientAdapterTest {
     @Mock
     private CertificateFactoryProvider certificateFactoryProvider;
     @Mock
-    private CSRMetaBuilder csrMetaBuilder;
+    private CsrMetaBuilder csrMetaBuilder;
     @Mock
-    private CSRMeta csrMeta;
+    private CsrMeta csrMeta;
 
     @InjectMocks
     private Cmpv2ClientAdapter adapter;
@@ -97,7 +97,7 @@ class Cmpv2ClientAdapterTest {
     @Test
     void adapterShouldRethrowClientExceptionOnFailure()
             throws CmpClientException, IOException, OperatorCreationException, CertificateException,
-                           NoSuchProviderException {
+            NoSuchProviderException {
         // Given
         stubInternalProperties();
 
@@ -112,7 +112,7 @@ class Cmpv2ClientAdapterTest {
     @Test
     void shouldConvertToCertificationModel()
             throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException,
-                           CmpClientException, Cmpv2ClientAdapterException {
+            CmpClientException, Cmpv2ClientAdapterException {
         // Given
         stubInternalProperties();
 
@@ -139,7 +139,7 @@ class Cmpv2ClientAdapterTest {
     @Test
     void adapterShouldThrowClientAdapterExceptionOnFailure()
             throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException,
-                           CmpClientException {
+            CmpClientException {
         // Given
         stubInternalProperties();
 
@@ -28,7 +28,7 @@ import org.onap.aaf.certservice.certification.configuration.model.Authentication
 import org.onap.aaf.certservice.certification.configuration.model.CaMode;
 import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
 import org.onap.aaf.certservice.certification.model.CsrModel;
-import org.onap.aaf.certservice.cmpv2client.external.CSRMeta;
+import org.onap.aaf.certservice.cmpv2client.external.CsrMeta;
 
 import java.security.PrivateKey;
 import java.security.PublicKey;
@@ -39,16 +39,16 @@ import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-public class CSRMetaBuilderTest {
+public class CsrMetaBuilderTest {
 
-    private CSRMetaBuilder csrMetaBuilder;
+    private CsrMetaBuilder csrMetaBuilder;
 
     private static final String TEST_CA = "testCA";
     private static final X500Name TEST_SUBJECT_DATA = new X500Name("CN=testIssuer");
 
     @BeforeEach
     void setUp() {
-        csrMetaBuilder = new CSRMetaBuilder();
+        csrMetaBuilder = new CsrMetaBuilder();
     }
 
     @Test
@@ -63,23 +63,23 @@ public class CSRMetaBuilderTest {
         when(testCsrModel.getPrivateKey()).thenReturn(mockPrivateKey);
         PublicKey mockPublicKey = mock(PublicKey.class);
         when(testCsrModel.getPublicKey()).thenReturn(mockPublicKey);
-        List<String> testSans = Arrays.asList("SAN01","SAN02");
+        List<String> testSans = Arrays.asList("SAN01", "SAN02");
         when(testCsrModel.getSans()).thenReturn(testSans);
 
         when(testCsrModel.getSubjectData()).thenReturn(TEST_SUBJECT_DATA);
 
         // When
-        CSRMeta createdCSRMeta = csrMetaBuilder.build(testCsrModel, testServer);
+        CsrMeta createdCsrMeta = csrMetaBuilder.build(testCsrModel, testServer);
 
         // Then
-        assertThat(createdCSRMeta.getPassword()).isEqualTo(testServer.getAuthentication().getIak());
-        assertThat(createdCSRMeta.getSenderKid()).isEqualTo(testServer.getAuthentication().getRv());
-        assertThat(createdCSRMeta.getCaUrl()).isEqualTo(testServer.getUrl());
-        assertThat(createdCSRMeta.getSans()).containsAll(testSans);
-        assertThat(createdCSRMeta.getKeyPair().getPrivate()).isEqualTo(mockPrivateKey);
-        assertThat(createdCSRMeta.getKeyPair().getPublic()).isEqualTo(mockPublicKey);
-        assertThat(createdCSRMeta.getX500Name()).isEqualTo(TEST_SUBJECT_DATA);
-        assertThat(createdCSRMeta.getIssuerX500Name()).isEqualTo(TEST_SUBJECT_DATA);
+        assertThat(createdCsrMeta.getPassword()).isEqualTo(testServer.getAuthentication().getIak());
+        assertThat(createdCsrMeta.getSenderKid()).isEqualTo(testServer.getAuthentication().getRv());
+        assertThat(createdCsrMeta.getCaUrl()).isEqualTo(testServer.getUrl());
+        assertThat(createdCsrMeta.getSans()).containsAll(testSans);
+        assertThat(createdCsrMeta.getKeyPair().getPrivate()).isEqualTo(mockPrivateKey);
+        assertThat(createdCsrMeta.getKeyPair().getPublic()).isEqualTo(mockPublicKey);
+        assertThat(createdCsrMeta.getX500Name()).isEqualTo(TEST_SUBJECT_DATA);
+        assertThat(createdCsrMeta.getIssuerX500Name()).isEqualTo(TEST_SUBJECT_DATA);
     }
 
     private Cmpv2Server createTestServer() {
@@ -34,13 +34,13 @@ import java.security.PrivateKey;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.onap.aaf.certservice.certification.TestUtils.createCsrModel;
 
-class RSAContentSignerBuilderTest {
+class RsaContentSignerBuilderTest {
 
-    private  RSAContentSignerBuilder rsaContentSignerBuilder;
+    private RsaContentSignerBuilder rsaContentSignerBuilder;
 
     @BeforeEach
     void setUp() {
-        rsaContentSignerBuilder = new RSAContentSignerBuilder();
+        rsaContentSignerBuilder = new RsaContentSignerBuilder();
     }
 
     @Test
index 26d11fc..d53c6c7 100644 (file)
@@ -53,7 +53,7 @@ public class X509CertificateBuilderTest {
         CsrModel testCsrModel = createCsrModel();
         PKCS10CertificationRequest testCertificationRequest = testCsrModel.getCsr();
         PrivateKey testPrivateKey = testCsrModel.getPrivateKey();
-        RSAContentSignerBuilder rsaContentSignerBuilder = new RSAContentSignerBuilder();
+        RsaContentSignerBuilder rsaContentSignerBuilder = new RsaContentSignerBuilder();
         ContentSigner createdContentSigner = rsaContentSignerBuilder.build(testCertificationRequest, testPrivateKey);
 
         // When
index c78f6ce..6197005 100644 (file)
@@ -25,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.util.List;
 import java.util.Map;
+
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.onap.aaf.certservice.CertServiceApplication;
@@ -79,8 +80,8 @@ class CmpServersConfigLoaderTest {
     void shouldThrowExceptionWhenFileMissing() {
         // When
         Exception exception = assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> configLoader.load(NONEXISTENT_CONFIG_FILENAME));
+                CmpServersConfigLoadingException.class,
+                () -> configLoader.load(NONEXISTENT_CONFIG_FILENAME));
 
         // Then
         assertThat(exception.getMessage()).contains("Exception occurred during CMP Servers configuration loading");
@@ -93,8 +94,8 @@ class CmpServersConfigLoaderTest {
 
         // When
         Exception exception = assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> configLoader.load(path));
+                CmpServersConfigLoadingException.class,
+                () -> configLoader.load(path));
 
         // Then
         assertThat(exception.getMessage()).contains("Validation of CMPv2 servers configuration failed");
index 043dbc0..511c396 100644 (file)
@@ -26,6 +26,7 @@ import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.startsWith;
 
 import java.util.List;
+
 import org.bouncycastle.asn1.x500.X500Name;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -95,12 +96,12 @@ class CmpServersConfigTest {
     void shouldRethrowExceptionWhenReloaded() throws CmpServersConfigLoadingException {
         // Given
         Mockito.when(cmpServersConfigLoader.load(any())).thenThrow(new CmpServersConfigLoadingException(
-            ERROR_MESSAGE));
+                ERROR_MESSAGE));
 
         // Then
         assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> cmpServersConfig.reloadConfiguration());
+                CmpServersConfigLoadingException.class,
+                () -> cmpServersConfig.reloadConfiguration());
     }
 
     @Test
@@ -110,8 +111,8 @@ class CmpServersConfigTest {
 
         // When
         Exception exception = assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> cmpServersConfig.reloadConfiguration());
+                CmpServersConfigLoadingException.class,
+                () -> cmpServersConfig.reloadConfiguration());
 
         // Then
         assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE);
@@ -128,10 +129,10 @@ class CmpServersConfigTest {
 
         // Then
         receivedCmpServers.forEach((server) -> assertThat(server.toString())
-            .doesNotContain(
-                server.getAuthentication().getIak(),
-                server.getAuthentication().getRv()
-            ));
+                .doesNotContain(
+                        server.getAuthentication().getIak(),
+                        server.getAuthentication().getRv()
+                ));
     }
 
     @Test
@@ -141,8 +142,8 @@ class CmpServersConfigTest {
 
         // Then
         assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> cmpServersConfig.loadConfiguration());
+                CmpServersConfigLoadingException.class,
+                () -> cmpServersConfig.loadConfiguration());
     }
 
     @Test
@@ -152,8 +153,8 @@ class CmpServersConfigTest {
 
         // When
         Exception exception = assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> cmpServersConfig.loadConfiguration());
+                CmpServersConfigLoadingException.class,
+                () -> cmpServersConfig.loadConfiguration());
 
         // Then
         assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE);
@@ -201,8 +202,8 @@ class CmpServersConfigTest {
 
         // When
         assertThrows(
-            CmpServersConfigLoadingException.class,
-            () -> cmpServersConfig.loadConfiguration());
+                CmpServersConfigLoadingException.class,
+                () -> cmpServersConfig.loadConfiguration());
 
         // Then
         assertThat(cmpServersConfig.isReady()).isFalse();
index 7e14e47..b83fb9a 100644 (file)
@@ -51,7 +51,7 @@ class Cmpv2ServerProviderTest {
     @BeforeEach
     void setUp() {
         cmpv2ServerProvider =
-                new  Cmpv2ServerProvider(cmpServersConfig);
+                new Cmpv2ServerProvider(cmpServersConfig);
     }
 
     @Test
index 10a7ba4..1c021b4 100644 (file)
@@ -54,13 +54,13 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldNotThrowExceptionWhenServerConfigurationIsValid() {
+    void shouldNotThrowExceptionWhenServerConfigurationIsValid() {
         // Then
         assertDoesNotThrow(() -> validator.validate(server));
     }
 
     @Test
-    public void shouldThrowExceptionWhenWrongProtocolInURL() {
+    void shouldThrowExceptionWhenWrongProtocolInUrl() {
         // Given
         server.setUrl("https://test.test.test:60000/");
 
@@ -69,7 +69,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenWrongPortInURL() {
+    void shouldThrowExceptionWhenWrongPortInUrl() {
         // Given
         server.setUrl("http://test.test.test:70000/");
 
@@ -78,7 +78,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenWrongCANameLength() {
+    void shouldThrowExceptionWhenWrongCaNameLength() {
         // Given
         server.setCaName(EMPTY_STRING);
 
@@ -87,7 +87,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenWrongRVLength() {
+    void shouldThrowExceptionWhenWrongRvLength() {
         // Given
         authentication.setRv(EMPTY_STRING);
 
@@ -97,7 +97,7 @@ class Cmpv2ServerConfigurationValidatorTest {
 
 
     @Test
-    public void shouldThrowExceptionWhenWrongIAKLength() {
+    void shouldThrowExceptionWhenWrongIakLength() {
         // Given
         authentication.setIak(EMPTY_STRING);
 
@@ -106,7 +106,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenCaNameIsNull() {
+    void shouldThrowExceptionWhenCaNameIsNull() {
         // Given
         server.setCaName(null);
 
@@ -115,7 +115,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenIssuerDnIsNull() {
+    void shouldThrowExceptionWhenIssuerDnIsNull() {
         // Given
         server.setIssuerDN(null);
 
@@ -124,7 +124,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenCaModeIsNull() {
+    void shouldThrowExceptionWhenCaModeIsNull() {
         // Given
         server.setCaMode(null);
 
@@ -133,7 +133,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenUrlIsNull() {
+    void shouldThrowExceptionWhenUrlIsNull() {
         // Given
         server.setUrl(null);
 
@@ -142,7 +142,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenAuthenticationIsNull() {
+    void shouldThrowExceptionWhenAuthenticationIsNull() {
         // Given
         server.setAuthentication(null);
 
@@ -151,7 +151,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenIakIsNull() {
+    void shouldThrowExceptionWhenIakIsNull() {
         // Given
         authentication.setIak(null);
 
@@ -160,7 +160,7 @@ class Cmpv2ServerConfigurationValidatorTest {
     }
 
     @Test
-    public void shouldThrowExceptionWhenRvIsNull() {
+    void shouldThrowExceptionWhenRvIsNull() {
         // Given
         authentication.setRv(null);
 
@@ -23,33 +23,35 @@ package org.onap.aaf.certservice.certification.configuration.validation.constrai
 
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
-class Cmpv2URLValidatorTest {
 
-    private final Cmpv2URLValidator validator = new Cmpv2URLValidator();
+class Cmpv2UrlValidatorTest {
+
+    private final Cmpv2UrlValidator validator = new Cmpv2UrlValidator();
 
     @Test
-    public void givenCorrectURLWhenValidatingShouldReturnTrue() {
+    void givenCorrectUrlWhenValidatingShouldReturnTrue() {
         //given
-        String URL = "http://127.0.0.1/ejbca/publicweb/cmp/cmp";
+        String url = "http://127.0.0.1/ejbca/publicweb/cmp/cmp";
 
         //when
-        boolean result = validator.isValid(URL, null);
+        boolean result = validator.isValid(url, null);
 
         //then
         assertTrue(result);
     }
 
     @Test
-    public void givenIncorrectURLWhenValidatingShouldReturnFalse() {
+    void givenIncorrectUrlWhenValidatingShouldReturnFalse() {
         //given
-        String URL = "httttp://127.0.0.1:80000/ejbca/publicweb/cmp/cmp";
+        String url = "httttp://127.0.0.1:80000/ejbca/publicweb/cmp/cmp";
 
         //when
-        boolean result = validator.isValid(URL, null);
+        boolean result = validator.isValid(url, null);
 
         //then
         assertFalse(result);
     }
-}
\ No newline at end of file
+}
index d185047..e729c73 100644 (file)
  * ============LICENSE_END=========================================================
  */
 
-
 package org.onap.aaf.certservice.certification.configuration.validation.constraints.violations;
 
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 class PortNumberViolationTest {
 
     private final PortNumberViolation violation = new PortNumberViolation();
 
     @Test
-    public void givenValidPortShouldReturnTrue() {
+    void givenValidPortShouldReturnTrue() {
         //given
-        String validURL1 = "http://127.0.0.1:8080/ejbca/publicweb/cmp/cmp";
-        String validURL2 = "http://127.0.0.1:1/ejbca/publicweb/cmp/cmp";
-        String validURL3 = "http://127.0.0.1:65535/ejbca/publicweb/cmp/cmp";
+        String validUrl1 = "http://127.0.0.1:8080/ejbca/publicweb/cmp/cmp";
+        String validUrl2 = "http://127.0.0.1:1/ejbca/publicweb/cmp/cmp";
+        String validUrl3 = "http://127.0.0.1:65535/ejbca/publicweb/cmp/cmp";
 
         //when
-        boolean result1 = violation.validate(validURL1);
-        boolean result2 = violation.validate(validURL2);
-        boolean result3 = violation.validate(validURL3);
+        boolean result1 = violation.validate(validUrl1);
+        boolean result2 = violation.validate(validUrl2);
+        boolean result3 = violation.validate(validUrl3);
 
         //then
         assertTrue(result1);
@@ -48,29 +48,29 @@ class PortNumberViolationTest {
     }
 
     @Test
-    public void givenEmptyPortShouldReturnTrue() {
+    void givenEmptyPortShouldReturnTrue() {
         //given
-        String validURL = "http://127.0.0.1/ejbca/publicweb/cmp/cmp";
+        String validUrl = "http://127.0.0.1/ejbca/publicweb/cmp/cmp";
 
         //when
-        boolean result = violation.validate(validURL);
+        boolean result = violation.validate(validUrl);
 
         //then
         assertTrue(result);
     }
 
     @Test
-    public void givenInvalidPortShouldReturnFalse() {
+    void givenInvalidPortShouldReturnFalse() {
         //given
-        String invalidURL1 = "http://127.0.0.1:0/ejbca/publicweb/cmp/cmp";
-        String invalidURL2 = "http://127.0.0.1:65536/ejbca/publicweb/cmp/cmp";
+        String invalidUrl1 = "http://127.0.0.1:0/ejbca/publicweb/cmp/cmp";
+        String invalidUrl2 = "http://127.0.0.1:65536/ejbca/publicweb/cmp/cmp";
 
         //when
-        boolean result1 = violation.validate(invalidURL1);
-        boolean result2 = violation.validate(invalidURL2);
+        boolean result1 = violation.validate(invalidUrl1);
+        boolean result2 = violation.validate(invalidUrl2);
 
         //then
         assertFalse(result1);
         assertFalse(result2);
     }
-}
\ No newline at end of file
+}
index cba2f34..dce66d5 100644 (file)
@@ -22,33 +22,35 @@ package org.onap.aaf.certservice.certification.configuration.validation.constrai
 
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
 
 class RequestTypeViolationTest {
 
     private final RequestTypeViolation violation = new RequestTypeViolation();
 
     @Test
-    public void givenValidRequestTypeShouldReturnTrue() {
+    void givenValidRequestTypeShouldReturnTrue() {
         //given
-        String validURL = "http://127.0.0.1/ejbca/publicweb/cmp/cmp";
+        String validUrl = "http://127.0.0.1/ejbca/publicweb/cmp/cmp";
 
         //when
-        boolean result = violation.validate(validURL);
+        boolean result = violation.validate(validUrl);
 
         //then
         assertTrue(result);
     }
 
     @Test
-    public void givenInvalidRequestTypeShouldReturnFalse() {
+    void givenInvalidRequestTypeShouldReturnFalse() {
         //given
-        String invalidURL = "htestps://127.0.0.1/ejbca/publicweb/cmp/cmp";
+        String invalidUrl = "htestps://127.0.0.1/ejbca/publicweb/cmp/cmp";
 
         //when
-        boolean result = violation.validate(invalidURL);
+        boolean result = violation.validate(invalidUrl);
 
         //then
         assertFalse(result);
     }
-}
\ No newline at end of file
+}
index 45bd966..08bc336 100644 (file)
@@ -24,7 +24,7 @@ import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
 import org.bouncycastle.util.io.pem.PemObject;
 import org.junit.jupiter.api.Test;
-import org.onap.aaf.certservice.certification.PKCS10CertificationRequestFactory;
+import org.onap.aaf.certservice.certification.Pkcs10CertificationRequestFactory;
 import org.onap.aaf.certservice.certification.PemObjectFactory;
 import org.onap.aaf.certservice.certification.exception.CsrDecryptionException;
 import org.onap.aaf.certservice.certification.exception.DecryptionException;
@@ -44,10 +44,11 @@ import static org.onap.aaf.certservice.certification.TestData.TEST_PK;
 
 class CsrModelTest {
 
-    private final PKCS10CertificationRequestFactory certificationRequestFactory
-            = new PKCS10CertificationRequestFactory();
+    private final Pkcs10CertificationRequestFactory certificationRequestFactory
+            = new Pkcs10CertificationRequestFactory();
     private final PemObjectFactory pemObjectFactory
             = new PemObjectFactory();
+
     @Test
     void shouldByConstructedAndReturnProperFields() throws DecryptionException, IOException {
         // Given
@@ -175,7 +176,7 @@ class CsrModelTest {
     private PKCS10CertificationRequest generateTestCertificationRequest() throws DecryptionException {
         return pemObjectFactory.createPemObject(TEST_CSR)
                 .flatMap(
-                        certificationRequestFactory::createKCS10CertificationRequest
+                        certificationRequestFactory::createPkcs10CertificationRequest
                 ).orElseThrow(
                         () -> new DecryptionException("Incorrect CSR, decryption failed")
                 );
diff --git a/certService/src/test/java/org/onap/aaf/certservice/cmpv2Client/Cmpv2ClientTest.java b/certService/src/test/java/org/onap/aaf/certservice/cmpv2Client/Cmpv2ClientTest.java
deleted file mode 100644 (file)
index a2f3050..0000000
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- * Copyright (C) 2019 Ericsson Software Technology AB. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.onap.aaf.certservice.cmpv2Client;
-
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.Security;
-import java.security.cert.X509Certificate;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.security.spec.X509EncodedKeySpec;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import org.apache.commons.io.IOUtils;
-import org.apache.http.HttpEntity;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.bouncycastle.cert.CertException;
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mock;
-import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
-import org.onap.aaf.certservice.cmpv2client.external.CSRMeta;
-import org.onap.aaf.certservice.cmpv2client.external.RDN;
-import org.onap.aaf.certservice.cmpv2client.impl.CmpClientImpl;
-
-class Cmpv2ClientTest {
-
-  static {
-    Security.addProvider(new BouncyCastleProvider());
-  }
-
-  private CSRMeta csrMeta;
-  private Date notBefore;
-  private Date notAfter;
-
-  @Mock KeyPairGenerator kpg;
-
-  @Mock X509Certificate cert;
-
-  @Mock CloseableHttpClient httpClient;
-
-  @Mock CloseableHttpResponse httpResponse;
-
-  @Mock HttpEntity httpEntity;
-
-  private static KeyPair keyPair;
-  private static ArrayList<RDN> rdns;
-
-  @BeforeEach
-  void setUp()
-      throws NoSuchProviderException, NoSuchAlgorithmException, IOException,
-          InvalidKeySpecException {
-    KeyPairGenerator keyGenerator;
-    keyGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
-    keyGenerator.initialize(2048);
-    keyPair = loadKeyPair();
-    rdns = new ArrayList<>();
-    try {
-      rdns.add(new RDN("O=CommonCompany"));
-    } catch (CertException e) {
-      e.printStackTrace();
-    }
-    initMocks(this);
-  }
-
-  public KeyPair loadKeyPair()
-      throws IOException, NoSuchAlgorithmException, InvalidKeySpecException,
-          NoSuchProviderException {
-
-    final InputStream privateInputStream = this.getClass().getResourceAsStream("/privateKey");
-    final InputStream publicInputStream = this.getClass().getResourceAsStream("/publicKey");
-    BufferedInputStream bis = new BufferedInputStream(privateInputStream);
-    byte[] privateBytes = IOUtils.toByteArray(bis);
-    bis = new BufferedInputStream(publicInputStream);
-    byte[] publicBytes = IOUtils.toByteArray(bis);
-
-    KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
-    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicBytes);
-    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
-
-    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateBytes);
-    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
-
-    return new KeyPair(publicKey, privateKey);
-  }
-
-  @Test
-  void shouldReturnValidPkiMessageWhenCreateCertificateRequestMessageMethodCalledWithValidCsr()
-      throws Exception {
-    // given
-    Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
-    Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
-    setCsrMetaValuesAndDateValues(
-        rdns,
-        "CN=CommonName",
-        "CN=ManagementCA",
-        "CommonName.com",
-        "CommonName@cn.com",
-        "mypassword",
-        "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
-        "senderKID",
-        beforeDate,
-        afterDate);
-    when(httpClient.execute(any())).thenReturn(httpResponse);
-    when(httpResponse.getEntity()).thenReturn(httpEntity);
-
-    try (final InputStream is =
-            this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile");
-        BufferedInputStream bis = new BufferedInputStream(is)) {
-
-      byte[] ba = IOUtils.toByteArray(bis);
-      doAnswer(
-              invocation -> {
-                OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
-                os.write(ba);
-                return null;
-              })
-          .when(httpEntity)
-          .writeTo(any(OutputStream.class));
-    }
-    CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
-    // when
-    List<List<X509Certificate>> cmpClientResult =
-        cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter);
-    // then
-    assertNotNull(cmpClientResult);
-  }
-
-  @Test
-  void
-      shouldThrowCmpClientExceptionWhenCreateCertificateRequestMessageMethodCalledWithWrongProtectedBytesInResponse()
-          throws Exception {
-    // given
-    Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
-    Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
-    setCsrMetaValuesAndDateValues(
-        rdns,
-        "CN=CommonName",
-        "CN=ManagementCA",
-        "CommonName.com",
-        "CommonName@cn.com",
-        "password",
-        "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
-        "senderKID",
-        beforeDate,
-        afterDate);
-    when(httpClient.execute(any())).thenReturn(httpResponse);
-    when(httpResponse.getEntity()).thenReturn(httpEntity);
-
-    try (final InputStream is =
-            this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile");
-        BufferedInputStream bis = new BufferedInputStream(is)) {
-
-      byte[] ba = IOUtils.toByteArray(bis);
-      doAnswer(
-              invocation -> {
-                OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
-                os.write(ba);
-                return null;
-              })
-          .when(httpEntity)
-          .writeTo(any(OutputStream.class));
-    }
-    CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
-    // then
-    Assertions.assertThrows(
-        CmpClientException.class,
-        () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
-  }
-
-  @Test
-  void shouldThrowCmpClientExceptionWithPkiErrorExceptionWhenCmpClientCalledWithBadPassword()
-      throws Exception {
-    // given
-    Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
-    Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
-    setCsrMetaValuesAndDateValues(
-        rdns,
-        "CN=CommonName",
-        "CN=ManagementCA",
-        "CommonName.com",
-        "CommonName@cn.com",
-        "password",
-        "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
-        "senderKID",
-        beforeDate,
-        afterDate);
-    when(httpClient.execute(any())).thenReturn(httpResponse);
-    when(httpResponse.getEntity()).thenReturn(httpEntity);
-
-    try (final InputStream is =
-            this.getClass().getResourceAsStream("/ReturnedFailurePKIMessageBadPassword");
-        BufferedInputStream bis = new BufferedInputStream(is)) {
-
-      byte[] ba = IOUtils.toByteArray(bis);
-      doAnswer(
-              invocation -> {
-                OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
-                os.write(ba);
-                return null;
-              })
-          .when(httpEntity)
-          .writeTo(any(OutputStream.class));
-    }
-    CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
-
-    // then
-    Assertions.assertThrows(
-        CmpClientException.class,
-        () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
-  }
-
-  @Test
-  void shouldThrowIllegalArgumentExceptionWhencreateCertificateCalledWithInvalidCsr()
-      throws ParseException {
-    // given
-    Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
-    Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
-    setCsrMetaValuesAndDateValues(
-        rdns,
-        "CN=CommonName",
-        "CN=ManagementCA",
-        "CommonName.com",
-        "CommonName@cn.com",
-        "password",
-        "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
-        "senderKID",
-        beforeDate,
-        afterDate);
-    CmpClientImpl cmpClient = new CmpClientImpl(httpClient);
-    // then
-    Assertions.assertThrows(
-        IllegalArgumentException.class,
-        () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
-  }
-
-  @Test
-  void shouldThrowIOExceptionWhenCreateCertificateCalledWithNoServerAvailable()
-      throws IOException, ParseException {
-    // given
-    Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
-    Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
-    setCsrMetaValuesAndDateValues(
-        rdns,
-        "CN=Common",
-        "CN=CommonCA",
-        "Common.com",
-        "Common@cn.com",
-        "myPassword",
-        "http://127.0.0.1/ejbca/publicweb/cmp/cmpTest",
-        "sender",
-        beforeDate,
-        afterDate);
-    when(httpClient.execute(any())).thenThrow(IOException.class);
-    CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
-    // then
-    Assertions.assertThrows(
-        CmpClientException.class,
-        () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
-  }
-
-  private void setCsrMetaValuesAndDateValues(
-      List<RDN> rdns,
-      String cn,
-      String issuerCn,
-      String san,
-      String email,
-      String password,
-      String externalCaUrl,
-      String senderKid,
-      Date notBefore,
-      Date notAfter) {
-    csrMeta = new CSRMeta(rdns);
-    csrMeta.setCn(cn);
-    csrMeta.addSan(san);
-    csrMeta.setPassword(password);
-    csrMeta.setEmail(email);
-    csrMeta.setIssuerCn(issuerCn);
-    when(kpg.generateKeyPair()).thenReturn(keyPair);
-    csrMeta.getKeyPairOrGenerateIfNull();
-    csrMeta.setCaUrl(externalCaUrl);
-    csrMeta.setSenderKid(senderKid);
-    this.notBefore = notBefore;
-    this.notAfter = notAfter;
-  }
-}
diff --git a/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java b/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java
new file mode 100644 (file)
index 0000000..3f5a254
--- /dev/null
@@ -0,0 +1,329 @@
+/*
+ * Copyright (C) 2019 Ericsson Software Technology AB. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package org.onap.aaf.certservice.cmpv2client;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+import static org.mockito.MockitoAnnotations.initMocks;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.Security;
+import java.security.cert.X509Certificate;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.bouncycastle.cert.CertException;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
+import org.onap.aaf.certservice.cmpv2client.external.CsrMeta;
+import org.onap.aaf.certservice.cmpv2client.external.Rdn;
+import org.onap.aaf.certservice.cmpv2client.impl.CmpClientImpl;
+
+class Cmpv2ClientTest {
+
+    static {
+        Security.addProvider(new BouncyCastleProvider());
+    }
+
+    private CsrMeta csrMeta;
+    private Date notBefore;
+    private Date notAfter;
+
+    @Mock
+    KeyPairGenerator kpg;
+
+    @Mock
+    X509Certificate cert;
+
+    @Mock
+    CloseableHttpClient httpClient;
+
+    @Mock
+    CloseableHttpResponse httpResponse;
+
+    @Mock
+    HttpEntity httpEntity;
+
+    private static KeyPair keyPair;
+    private static ArrayList<Rdn> rdns;
+
+    @BeforeEach
+    void setUp()
+            throws NoSuchProviderException, NoSuchAlgorithmException, IOException,
+            InvalidKeySpecException {
+        KeyPairGenerator keyGenerator;
+        keyGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
+        keyGenerator.initialize(2048);
+        keyPair = loadKeyPair();
+        rdns = new ArrayList<>();
+        try {
+            rdns.add(new Rdn("O=CommonCompany"));
+        } catch (CertException e) {
+            e.printStackTrace();
+        }
+        initMocks(this);
+    }
+
+    public KeyPair loadKeyPair()
+            throws IOException, NoSuchAlgorithmException, InvalidKeySpecException,
+            NoSuchProviderException {
+
+        final InputStream privateInputStream = this.getClass().getResourceAsStream("/privateKey");
+        final InputStream publicInputStream = this.getClass().getResourceAsStream("/publicKey");
+        BufferedInputStream bis = new BufferedInputStream(privateInputStream);
+        byte[] privateBytes = IOUtils.toByteArray(bis);
+        bis = new BufferedInputStream(publicInputStream);
+        byte[] publicBytes = IOUtils.toByteArray(bis);
+
+        KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
+        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicBytes);
+        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
+
+        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateBytes);
+        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
+
+        return new KeyPair(publicKey, privateKey);
+    }
+
+    @Test
+    void shouldReturnValidPkiMessageWhenCreateCertificateRequestMessageMethodCalledWithValidCsr()
+            throws Exception {
+        // given
+        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
+        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
+        setCsrMetaValuesAndDateValues(
+                rdns,
+                "CN=CommonName",
+                "CN=ManagementCA",
+                "CommonName.com",
+                "CommonName@cn.com",
+                "mypassword",
+                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
+                "senderKID",
+                beforeDate,
+                afterDate);
+        when(httpClient.execute(any())).thenReturn(httpResponse);
+        when(httpResponse.getEntity()).thenReturn(httpEntity);
+
+        try (final InputStream is =
+                     this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile");
+             BufferedInputStream bis = new BufferedInputStream(is)) {
+
+            byte[] ba = IOUtils.toByteArray(bis);
+            doAnswer(
+                    invocation -> {
+                        OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
+                        os.write(ba);
+                        return null;
+                    })
+                    .when(httpEntity)
+                    .writeTo(any(OutputStream.class));
+        }
+        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
+        // when
+        List<List<X509Certificate>> cmpClientResult =
+                cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter);
+        // then
+        assertNotNull(cmpClientResult);
+    }
+
+    @Test
+    void
+    shouldThrowCmpClientExceptionWhenCreateCertificateRequestMessageMethodCalledWithWrongProtectedBytesInResponse()
+            throws Exception {
+        // given
+        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
+        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
+        setCsrMetaValuesAndDateValues(
+                rdns,
+                "CN=CommonName",
+                "CN=ManagementCA",
+                "CommonName.com",
+                "CommonName@cn.com",
+                "password",
+                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
+                "senderKID",
+                beforeDate,
+                afterDate);
+        when(httpClient.execute(any())).thenReturn(httpResponse);
+        when(httpResponse.getEntity()).thenReturn(httpEntity);
+
+        try (final InputStream is =
+                     this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile");
+             BufferedInputStream bis = new BufferedInputStream(is)) {
+
+            byte[] ba = IOUtils.toByteArray(bis);
+            doAnswer(
+                    invocation -> {
+                        OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
+                        os.write(ba);
+                        return null;
+                    })
+                    .when(httpEntity)
+                    .writeTo(any(OutputStream.class));
+        }
+        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
+        // then
+        Assertions.assertThrows(
+                CmpClientException.class,
+                () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
+    }
+
+    @Test
+    void shouldThrowCmpClientExceptionWithPkiErrorExceptionWhenCmpClientCalledWithBadPassword()
+            throws Exception {
+        // given
+        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
+        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
+        setCsrMetaValuesAndDateValues(
+                rdns,
+                "CN=CommonName",
+                "CN=ManagementCA",
+                "CommonName.com",
+                "CommonName@cn.com",
+                "password",
+                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
+                "senderKID",
+                beforeDate,
+                afterDate);
+        when(httpClient.execute(any())).thenReturn(httpResponse);
+        when(httpResponse.getEntity()).thenReturn(httpEntity);
+
+        try (final InputStream is =
+                     this.getClass().getResourceAsStream("/ReturnedFailurePKIMessageBadPassword");
+             BufferedInputStream bis = new BufferedInputStream(is)) {
+
+            byte[] ba = IOUtils.toByteArray(bis);
+            doAnswer(
+                    invocation -> {
+                        OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
+                        os.write(ba);
+                        return null;
+                    })
+                    .when(httpEntity)
+                    .writeTo(any(OutputStream.class));
+        }
+        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
+
+        // then
+        Assertions.assertThrows(
+                CmpClientException.class,
+                () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
+    }
+
+    @Test
+    void shouldThrowIllegalArgumentExceptionWhencreateCertificateCalledWithInvalidCsr()
+            throws ParseException {
+        // given
+        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
+        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
+        setCsrMetaValuesAndDateValues(
+                rdns,
+                "CN=CommonName",
+                "CN=ManagementCA",
+                "CommonName.com",
+                "CommonName@cn.com",
+                "password",
+                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
+                "senderKID",
+                beforeDate,
+                afterDate);
+        CmpClientImpl cmpClient = new CmpClientImpl(httpClient);
+        // then
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
+    }
+
+    @Test
+    void shouldThrowIoExceptionWhenCreateCertificateCalledWithNoServerAvailable()
+            throws IOException, ParseException {
+        // given
+        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
+        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
+        setCsrMetaValuesAndDateValues(
+                rdns,
+                "CN=Common",
+                "CN=CommonCA",
+                "Common.com",
+                "Common@cn.com",
+                "myPassword",
+                "http://127.0.0.1/ejbca/publicweb/cmp/cmpTest",
+                "sender",
+                beforeDate,
+                afterDate);
+        when(httpClient.execute(any())).thenThrow(IOException.class);
+        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
+        // then
+        Assertions.assertThrows(
+                CmpClientException.class,
+                () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter));
+    }
+
+    private void setCsrMetaValuesAndDateValues(
+            List<Rdn> rdns,
+            String cn,
+            String issuerCn,
+            String san,
+            String email,
+            String password,
+            String externalCaUrl,
+            String senderKid,
+            Date notBefore,
+            Date notAfter) {
+        csrMeta = new CsrMeta(rdns);
+        csrMeta.setCn(cn);
+        csrMeta.addSan(san);
+        csrMeta.setPassword(password);
+        csrMeta.setEmail(email);
+        csrMeta.setIssuerCn(issuerCn);
+        when(kpg.generateKeyPair()).thenReturn(keyPair);
+        csrMeta.getKeyPairOrGenerateIfNull();
+        csrMeta.setCaUrl(externalCaUrl);
+        csrMeta.setSenderKid(senderKid);
+        this.notBefore = notBefore;
+        this.notAfter = notAfter;
+    }
+}
@@ -31,19 +31,20 @@ import java.util.List;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
-class RDNTest {
+class RdnTest {
 
     @Test
-    public void shouldCreateCorrectRDN() throws CertException {
+    void shouldCreateCorrectRdn() throws CertException {
+        // given
+        final String expectedValue = "ManagmentCA";
+        final ASN1ObjectIdentifier expectedAoi = BCStyle.CN;
+
         //when
-        RDN rdn1 = new RDN("CN=ManagmentCA");
-        RDN rdn2 = new RDN("CN = ManagmentCA ");
-        RDN rdn3 = new RDN("CN", "ManagmentCA");
+        Rdn rdn1 = new Rdn("CN=ManagmentCA");
+        Rdn rdn2 = new Rdn("CN = ManagmentCA ");
+        Rdn rdn3 = new Rdn("CN", "ManagmentCA");
 
         //then
-        String expectedValue = "ManagmentCA";
-        ASN1ObjectIdentifier expectedAoi = BCStyle.CN;
-
         assertEquals(expectedValue, rdn1.getValue());
         assertEquals(expectedValue, rdn2.getValue());
         assertEquals(expectedValue, rdn3.getValue());
@@ -53,7 +54,7 @@ class RDNTest {
     }
 
     @Test
-    public void shouldCorrectlySplitAndTrimString() {
+    void shouldCorrectlySplitAndTrimString() {
         //given
         String value1 = " T  =  Test";
         List<String> expected1 = Arrays.asList("T", "Test");
@@ -62,8 +63,8 @@ class RDNTest {
         List<String> expected2 = Arrays.asList("This", "is 99 tested", "string");
 
         //when
-        List<String> actual1 = RDN.parseRDN("=", value1);
-        List<String> actual2 = RDN.parseRDN("[0-9]{3,}", value2);
+        List<String> actual1 = Rdn.parseRdn("=", value1);
+        List<String> actual2 = Rdn.parseRdn("[0-9]{3,}", value2);
 
         //then
         assertEquals(expected1, actual1);
@@ -71,8 +72,8 @@ class RDNTest {
     }
 
     @Test
-    public void shouldConvertAoiStringToEnum() throws CertException {
-        RDN rdn = new RDN("CN", "ManagmentCA");
+    void shouldConvertAoiStringToEnum() throws CertException {
+        Rdn rdn = new Rdn("CN", "ManagmentCA");
 
         assertEquals(BCStyle.CN, rdn.getAoi("CN"));
         assertEquals(BCStyle.C, rdn.getAoi("C"));
@@ -92,4 +93,4 @@ class RDNTest {
         assertEquals(BCStyle.SERIALNUMBER, rdn.getAoi("SERIALNUMBER"));
         assertThrows(CertException.class, () -> rdn.getAoi("INVALIDTAG"));
     }
-}
\ No newline at end of file
+}