From dd84c4aad3b0ebb9af61e1c45c95a033121c5153 Mon Sep 17 00:00:00 2001 From: Piotr Marcinkiewicz Date: Tue, 13 Jul 2021 15:41:57 +0200 Subject: [OOM-CERT-SERVICE] Refactor CertService API code - move conversion StringBase64 to PrivateKey to separate class - move protection algorithm classes to separate package - adjust modifiers and test to above changes Issue-ID: OOM-2753 Signed-off-by: Piotr Marcinkiewicz Change-Id: Ifafa38162acfcd59d5177dbc478a6209e97a18e3 --- .../certification/CertificationProvider.java | 2 +- .../certification/conversion/CsrModelFactory.java | 21 +-- .../conversion/OldCertificateModelFactory.java | 35 ++--- .../StringBase64ToPrivateKeyConverter.java | 55 ++++++++ .../certservice/certification/model/CsrModel.java | 42 ++---- .../cmpv2client/impl/CmpClientImpl.java | 30 ++-- .../oom/certservice/cmpv2client/impl/CmpUtil.java | 18 +-- .../cmpv2client/impl/CreateCertRequest.java | 13 +- .../cmpv2client/impl/PasswordBasedProtection.java | 100 ------------- .../cmpv2client/impl/PkiMessageProtection.java | 76 ---------- .../cmpv2client/impl/SignatureProtection.java | 63 --------- .../impl/protections/PasswordBasedProtection.java | 100 +++++++++++++ .../impl/protections/PkiMessageProtection.java | 76 ++++++++++ .../impl/protections/SignatureProtection.java | 63 +++++++++ .../validation/CmpCertificationValidator.java | 18 +-- .../conversion/CsrModelFactoryTest.java | 17 ++- .../StringBase64ToPrivateKeyConverterTest.java | 89 ++++++++++++ .../certification/model/CsrModelTest.java | 69 +++++---- .../impl/PasswordBasedProtectionTest.java | 154 --------------------- .../certservice/cmpv2client/impl/PkiTestUtils.java | 101 -------------- .../cmpv2client/impl/SignatureProtectionTest.java | 94 ------------- .../protections/PasswordBasedProtectionTest.java | 154 +++++++++++++++++++++ .../cmpv2client/impl/protections/PkiTestUtils.java | 101 ++++++++++++++ .../impl/protections/SignatureProtectionTest.java | 94 +++++++++++++ 24 files changed, 843 insertions(+), 742 deletions(-) create mode 100644 certService/src/main/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverter.java delete mode 100644 certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtection.java delete mode 100644 certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PkiMessageProtection.java delete mode 100644 certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtection.java create mode 100644 certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtection.java create mode 100644 certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiMessageProtection.java create mode 100644 certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtection.java create mode 100644 certService/src/test/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverterTest.java delete mode 100644 certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtectionTest.java delete mode 100644 certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PkiTestUtils.java delete mode 100644 certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtectionTest.java create mode 100644 certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtectionTest.java create mode 100644 certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiTestUtils.java create mode 100644 certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtectionTest.java diff --git a/certService/src/main/java/org/onap/oom/certservice/certification/CertificationProvider.java b/certService/src/main/java/org/onap/oom/certservice/certification/CertificationProvider.java index 94e778e3..f7fe2c64 100644 --- a/certService/src/main/java/org/onap/oom/certservice/certification/CertificationProvider.java +++ b/certService/src/main/java/org/onap/oom/certservice/certification/CertificationProvider.java @@ -70,7 +70,7 @@ public class CertificationProvider { return getCertificationResponseModel(certificates); } - private static List convertFromX509CertificateListToPemList(List certificates) { + private List convertFromX509CertificateListToPemList(List certificates) { return certificates.stream().map(CertificationProvider::convertFromX509CertificateToPem).filter(cert -> !cert.isEmpty()) .collect(Collectors.toList()); } diff --git a/certService/src/main/java/org/onap/oom/certservice/certification/conversion/CsrModelFactory.java b/certService/src/main/java/org/onap/oom/certservice/certification/conversion/CsrModelFactory.java index e4ee4c10..6f80f793 100644 --- a/certService/src/main/java/org/onap/oom/certservice/certification/conversion/CsrModelFactory.java +++ b/certService/src/main/java/org/onap/oom/certservice/certification/conversion/CsrModelFactory.java @@ -21,13 +21,13 @@ package org.onap.oom.certservice.certification.conversion; import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.util.io.pem.PemObject; import org.onap.oom.certservice.certification.exception.CsrDecryptionException; import org.onap.oom.certservice.certification.exception.DecryptionException; -import org.onap.oom.certservice.certification.exception.KeyDecryptionException; import org.onap.oom.certservice.certification.model.CsrModel; import org.springframework.stereotype.Service; +import java.security.PrivateKey; + @Service public class CsrModelFactory { @@ -36,23 +36,14 @@ public class CsrModelFactory { = new PemObjectFactory(); private final Pkcs10CertificationRequestFactory certificationRequestFactory = new Pkcs10CertificationRequestFactory(); - + private final StringBase64ToPrivateKeyConverter stringBase64ToPrivateKeyConverter + = new StringBase64ToPrivateKeyConverter(); public CsrModel createCsrModel(StringBase64 csr, StringBase64 privateKey) throws DecryptionException { PKCS10CertificationRequest decodedCsr = decodeCsr(csr); - PemObject decodedPrivateKey = decodePrivateKey(privateKey); - return new CsrModel.CsrModelBuilder(decodedCsr, decodedPrivateKey).build(); - } - - private PemObject decodePrivateKey(StringBase64 privateKey) - throws KeyDecryptionException { - - return privateKey.asString() - .flatMap(pemObjectFactory::createPemObject) - .orElseThrow( - () -> new KeyDecryptionException("Incorrect Key, decryption failed") - ); + PrivateKey javaPrivateKey = stringBase64ToPrivateKeyConverter.convert(privateKey); + return new CsrModel.CsrModelBuilder(decodedCsr, javaPrivateKey).build(); } private PKCS10CertificationRequest decodeCsr(StringBase64 csr) diff --git a/certService/src/main/java/org/onap/oom/certservice/certification/conversion/OldCertificateModelFactory.java b/certService/src/main/java/org/onap/oom/certservice/certification/conversion/OldCertificateModelFactory.java index f5c199f6..fba5259c 100644 --- a/certService/src/main/java/org/onap/oom/certservice/certification/conversion/OldCertificateModelFactory.java +++ b/certService/src/main/java/org/onap/oom/certservice/certification/conversion/OldCertificateModelFactory.java @@ -20,19 +20,10 @@ package org.onap.oom.certservice.certification.conversion; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.Certificate; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; -import org.bouncycastle.util.io.pem.PemObject; import org.onap.oom.certservice.certification.X509CertificateParser; import org.onap.oom.certservice.certification.exception.CertificateDecryptionException; import org.onap.oom.certservice.certification.exception.KeyDecryptionException; @@ -41,13 +32,19 @@ import org.onap.oom.certservice.certification.model.OldCertificateModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateParsingException; +import java.security.cert.X509Certificate; + @Service public class OldCertificateModelFactory { private static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n"; private static final String END_CERTIFICATE = "-----END CERTIFICATE-----\n"; - private static final PemObjectFactory PEM_OBJECT_FACTORY = new PemObjectFactory(); + private final StringBase64ToPrivateKeyConverter stringBase64ToPrivateKeyConverter + = new StringBase64ToPrivateKeyConverter(); private final PemStringToCertificateConverter pemStringToCertificateConverter; private final X509CertificateParser x509CertificateParser; @@ -68,14 +65,13 @@ public class OldCertificateModelFactory { final X500Name subjectData = x509CertificateParser.getSubject(x509Certificate); final GeneralName[] sans = x509CertificateParser.getSans(x509Certificate); final Certificate certificate = new JcaX509CertificateHolder(x509Certificate).toASN1Structure(); - final PrivateKey oldPrivateKey = getOldPrivateKeyObject(encodedOldPrivateKey); + final PrivateKey oldPrivateKey = stringBase64ToPrivateKeyConverter.convert(new StringBase64(encodedOldPrivateKey)); return new OldCertificateModel(certificate, subjectData, sans, oldPrivateKey); } catch (StringToCertificateConversionException e) { throw new CertificateDecryptionException("Cannot convert certificate", e); - } catch (CertificateParsingException e) { throw new CertificateDecryptionException("Cannot read Subject Alternative Names from certificate"); - } catch (NoSuchAlgorithmException | KeyDecryptionException | CertificateEncodingException | InvalidKeySpecException e) { + } catch (KeyDecryptionException | CertificateEncodingException e) { throw new CertificateDecryptionException("Cannot convert certificate or key", e); } } @@ -91,17 +87,4 @@ public class OldCertificateModelFactory { return !(certificateChain.contains(BEGIN_CERTIFICATE) && certificateChain.contains(END_CERTIFICATE)); } - private PrivateKey getOldPrivateKeyObject(String encodedOldPrivateKey) - throws KeyDecryptionException, InvalidKeySpecException, NoSuchAlgorithmException { - - StringBase64 stringBase64 = new StringBase64(encodedOldPrivateKey); - PemObject pemObject = stringBase64.asString() - .flatMap(PEM_OBJECT_FACTORY::createPemObject) - .orElseThrow( - () -> new KeyDecryptionException("Incorrect Key, decryption failed") - ); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pemObject.getContent()); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - return keyFactory.generatePrivate(keySpec); - } } diff --git a/certService/src/main/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverter.java b/certService/src/main/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverter.java new file mode 100644 index 00000000..1ea752b1 --- /dev/null +++ b/certService/src/main/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverter.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.certification.conversion; + +import org.bouncycastle.util.io.pem.PemObject; +import org.onap.oom.certservice.certification.exception.KeyDecryptionException; + +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; + +public class StringBase64ToPrivateKeyConverter { + + private final PemObjectFactory pemObjectFactory = new PemObjectFactory(); + + public PrivateKey convert(StringBase64 privateKey) throws KeyDecryptionException { + PemObject decodedPrivateKey = createDecodedPrivateKey(privateKey); + try { + KeyFactory factory = KeyFactory.getInstance("RSA"); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedPrivateKey.getContent()); + return factory.generatePrivate(keySpec); + } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { + throw new KeyDecryptionException("Converting Private Key failed", e.getCause()); + } + } + + private PemObject createDecodedPrivateKey(StringBase64 privateKey) throws KeyDecryptionException { + return privateKey.asString() + .flatMap(pemObjectFactory::createPemObject) + .orElseThrow( + () -> new KeyDecryptionException("Incorrect Key, decryption failed") + ); + } + +} diff --git a/certService/src/main/java/org/onap/oom/certservice/certification/model/CsrModel.java b/certService/src/main/java/org/onap/oom/certservice/certification/model/CsrModel.java index 96755832..cd88ff11 100644 --- a/certService/src/main/java/org/onap/oom/certservice/certification/model/CsrModel.java +++ b/certService/src/main/java/org/onap/oom/certservice/certification/model/CsrModel.java @@ -20,16 +20,6 @@ package org.onap.oom.certservice.certification.model; -import java.io.IOException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.Arrays; -import java.util.stream.Collectors; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extensions; @@ -41,6 +31,16 @@ import org.onap.oom.certservice.certification.exception.CsrDecryptionException; import org.onap.oom.certservice.certification.exception.DecryptionException; import org.onap.oom.certservice.certification.exception.KeyDecryptionException; +import java.io.IOException; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; +import java.util.Arrays; +import java.util.stream.Collectors; + public class CsrModel { @@ -95,19 +95,18 @@ public class CsrModel { public static class CsrModelBuilder { private final PKCS10CertificationRequest csr; - private final PemObject privateKey; + private final PrivateKey privateKey; public CsrModel build() throws DecryptionException { X500Name subjectData = getSubjectData(); - PrivateKey javaPrivateKey = convertingPemPrivateKeyToJavaSecurityPrivateKey(getPrivateKey()); PublicKey javaPublicKey = convertingPemPublicKeyToJavaSecurityPublicKey(getPublicKey()); GeneralName[] sans = getSansData(); - return new CsrModel(csr, subjectData, javaPrivateKey, javaPublicKey, sans); + return new CsrModel(csr, subjectData, privateKey, javaPublicKey, sans); } - public CsrModelBuilder(PKCS10CertificationRequest csr, PemObject privateKey) { + public CsrModelBuilder(PKCS10CertificationRequest csr, PrivateKey privateKey) { this.csr = csr; this.privateKey = privateKey; } @@ -120,10 +119,6 @@ public class CsrModel { } } - private PemObject getPrivateKey() { - return privateKey; - } - private X500Name getSubjectData() { return csr.getSubject(); } @@ -144,17 +139,6 @@ public class CsrModel { return csr.getAttributes().length == 0; } - private PrivateKey convertingPemPrivateKeyToJavaSecurityPrivateKey(PemObject privateKey) - throws KeyDecryptionException { - try { - KeyFactory factory = KeyFactory.getInstance("RSA"); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getContent()); - return factory.generatePrivate(keySpec); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - throw new KeyDecryptionException("Converting Private Key failed", e.getCause()); - } - } - private PublicKey convertingPemPublicKeyToJavaSecurityPublicKey(PemObject publicKey) throws KeyDecryptionException { try { diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpClientImpl.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpClientImpl.java index bbca91b6..58291650 100644 --- a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpClientImpl.java +++ b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpClientImpl.java @@ -22,19 +22,6 @@ package org.onap.oom.certservice.cmpv2client.impl; -import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.checkIfCmpResponseContainsError; -import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.getCertFromByteArray; -import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.verifyAndReturnCertChainAndTrustSTore; - -import java.io.IOException; -import java.security.KeyPair; -import java.security.Security; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; -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; @@ -48,11 +35,28 @@ import org.onap.oom.certservice.certification.model.CsrModel; import org.onap.oom.certservice.certification.model.OldCertificateModel; import org.onap.oom.certservice.cmpv2client.api.CmpClient; import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; +import org.onap.oom.certservice.cmpv2client.impl.protections.PasswordBasedProtection; +import org.onap.oom.certservice.cmpv2client.impl.protections.PkiMessageProtection; +import org.onap.oom.certservice.cmpv2client.impl.protections.SignatureProtection; import org.onap.oom.certservice.cmpv2client.model.Cmpv2CertificationModel; import org.onap.oom.certservice.cmpv2client.validation.CmpCertificationValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.security.KeyPair; +import java.security.Security; +import java.security.cert.CertificateParsingException; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.Date; +import java.util.Objects; +import java.util.Optional; + +import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.checkIfCmpResponseContainsError; +import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.getCertFromByteArray; +import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.verifyAndReturnCertChainAndTrustSTore; + /** * Implementation of the CmpClient Interface conforming to RFC4210 (Certificate Management Protocol * (CMP)) and RFC4211 (Certificate Request Message Format (CRMF)) standards. diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpUtil.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpUtil.java index 8912e88c..a05a5b7a 100644 --- a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpUtil.java +++ b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpUtil.java @@ -21,12 +21,6 @@ package org.onap.oom.certservice.cmpv2client.impl; -import java.io.ByteArrayOutputStream; -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; @@ -46,6 +40,12 @@ import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.SecureRandom; +import java.util.Date; +import java.util.Objects; + public final class CmpUtil { private static final Logger LOGGER = LoggerFactory.getLogger(CmpUtil.class); @@ -83,7 +83,7 @@ public final class CmpUtil { * * @return bytes containing a random number string representing a nonce */ - static byte[] createRandomBytes() { + public static byte[] createRandomBytes() { LOGGER.info("Generating random array of bytes"); byte[] randomBytes = new byte[RANDOM_BYTE_LENGTH]; SECURE_RANDOM.nextBytes(randomBytes); @@ -96,7 +96,7 @@ public final class CmpUtil { * * @return bytes containing a random number string representing a nonce */ - static int createRandomInt(int range) { + public static int createRandomInt(int range) { LOGGER.info("Generating random integer"); return SECURE_RANDOM.nextInt(range) + RANDOM_SEED; } @@ -108,7 +108,7 @@ public final class CmpUtil { * @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 { + public 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(); diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CreateCertRequest.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CreateCertRequest.java index c3283044..c7ed8b77 100644 --- a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CreateCertRequest.java +++ b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CreateCertRequest.java @@ -21,12 +21,6 @@ package org.onap.oom.certservice.cmpv2client.impl; -import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.createRandomInt; -import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.generatePkiHeader; - -import java.security.KeyPair; -import java.util.Date; - import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.cmp.CMPCertificate; @@ -44,6 +38,13 @@ import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; +import org.onap.oom.certservice.cmpv2client.impl.protections.PkiMessageProtection; + +import java.security.KeyPair; +import java.util.Date; + +import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.createRandomInt; +import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.generatePkiHeader; /** * Implementation of the CmpClient Interface conforming to RFC4210 (Certificate Management Protocol diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtection.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtection.java deleted file mode 100644 index 621415c0..00000000 --- a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtection.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nokia. - * ================================================================================ - * 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========================================================= - */ - -package org.onap.oom.certservice.cmpv2client.impl; - -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.cmp.PBMParameter; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; - -import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.createRandomBytes; -import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.createRandomInt; - -/** - * Implementation of password-based PKIMessage protection - */ -public class PasswordBasedProtection extends PkiMessageProtection { - - private static final int ITERATIONS = createRandomInt(1000); - private static final byte[] SALT = createRandomBytes(); - 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.3.6.1.5.5.8.1.2")); - private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC = - new ASN1ObjectIdentifier("1.2.840.113533.7.66.13"); - - private final String initAuthPassword; - - PasswordBasedProtection(String initAuthPassword) { - this.initAuthPassword = initAuthPassword; - } - - @Override - AlgorithmIdentifier getAlgorithmIdentifier() { - 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); - } - - @Override - byte[] generateProtectionBytes(byte[] protectedBytes) throws GeneralSecurityException { - byte[] baseKey = generateBaseKey(); - return generateMacBytes(baseKey, protectedBytes); - } - - private byte[] generateBaseKey() throws NoSuchAlgorithmException, NoSuchProviderException { - byte[] raSecret = initAuthPassword.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); - MessageDigest dig = - MessageDigest.getInstance( - OWF_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME); - for (int i = 0; i < ITERATIONS; i++) { - baseKey = dig.digest(baseKey); - dig.reset(); - } - return baseKey; - } - - private byte[] generateMacBytes(byte[] baseKey, byte[] protectedBytes) throws GeneralSecurityException { - 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); - return mac.doFinal(); - } - -} diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PkiMessageProtection.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PkiMessageProtection.java deleted file mode 100644 index d32ed588..00000000 --- a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/PkiMessageProtection.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nokia. - * ================================================================================ - * 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========================================================= - */ - -package org.onap.oom.certservice.cmpv2client.impl; - -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.cmp.PKIBody; -import org.bouncycastle.asn1.cmp.PKIHeader; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.security.GeneralSecurityException; - -import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.generateProtectedBytes; - -/** - * Representation of PKIMessage protection. Complies with RFC4210 (Certificate Management Protocol - * (CMP)) and RFC4211 (Certificate Request Message Format (CRMF)) standards. - */ -public abstract class PkiMessageProtection { - - private static final Logger LOG = LoggerFactory.getLogger(PkiMessageProtection.class); - - /** - * Takes PKIHeader and PKIBody as parameters and generates protection bytes. - * - * @return bytes representing protection wrapped into DERBitString object. - */ - DERBitString generatePkiMessageProtection(PKIHeader pkiHeader, PKIBody pkiBody) throws CmpClientException { - try { - byte[] protectedBytes = generateProtectedBytes(pkiHeader, pkiBody); - byte[] protectionBytes = generateProtectionBytes(protectedBytes); - return new DERBitString(protectionBytes); - } catch (GeneralSecurityException ex) { - CmpClientException cmpClientException = - new CmpClientException( - "Exception occurred while generating protection for PKIMessage", ex); - LOG.error("Exception occurred while generating the protection for PKIMessage"); - throw cmpClientException; - } - } - - /** - * Takes encoded bytes of PKIMessage (PKIHeader and PKIBody) and generates protection bytes. - * - * @return bytes representing protection. - */ - abstract byte[] generateProtectionBytes(byte[] protectedBytes) throws GeneralSecurityException; - - /** - * Returns Algorithm Identifier for protection of PKIMessage. - * - * @return Algorithm Identifier. - */ - abstract AlgorithmIdentifier getAlgorithmIdentifier(); - -} diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtection.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtection.java deleted file mode 100644 index ad778430..00000000 --- a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtection.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nokia. - * ================================================================================ - * 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========================================================= - */ - -package org.onap.oom.certservice.cmpv2client.impl; - - -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; - -import java.security.GeneralSecurityException; -import java.security.PrivateKey; -import java.security.Signature; - -/** - * Implementation of signature PKIMessage protection - */ -public class SignatureProtection extends PkiMessageProtection { - - private static final AlgorithmIdentifier SHA256_RSA_ALGORITHM = new DefaultSignatureAlgorithmIdentifierFinder() - .find("SHA256withRSA"); - - private final PrivateKey oldPrivateKey; - - SignatureProtection(PrivateKey privateKey) { - this.oldPrivateKey = privateKey; - } - - @Override - AlgorithmIdentifier getAlgorithmIdentifier() { - return SHA256_RSA_ALGORITHM; - } - - @Override - byte[] generateProtectionBytes(byte[] protectedBytes) throws GeneralSecurityException { - Signature signature = - Signature.getInstance( - PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), - BouncyCastleProvider.PROVIDER_NAME); - signature.initSign(oldPrivateKey); - signature.update(protectedBytes, 0, protectedBytes.length); - return signature.sign(); - } - -} diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtection.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtection.java new file mode 100644 index 00000000..c9d79e2d --- /dev/null +++ b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtection.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.cmpv2client.impl.protections; + +import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.cmp.PBMParameter; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; + +import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.createRandomBytes; +import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.createRandomInt; + +/** + * Implementation of password-based PKIMessage protection + */ +public class PasswordBasedProtection extends PkiMessageProtection { + + private static final int ITERATIONS = createRandomInt(1000); + private static final byte[] SALT = createRandomBytes(); + 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.3.6.1.5.5.8.1.2")); + private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC = + new ASN1ObjectIdentifier("1.2.840.113533.7.66.13"); + + private final String initAuthPassword; + + public PasswordBasedProtection(String initAuthPassword) { + this.initAuthPassword = initAuthPassword; + } + + @Override + public AlgorithmIdentifier getAlgorithmIdentifier() { + 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); + } + + @Override + byte[] generateProtectionBytes(byte[] protectedBytes) throws GeneralSecurityException { + byte[] baseKey = generateBaseKey(); + return generateMacBytes(baseKey, protectedBytes); + } + + private byte[] generateBaseKey() throws NoSuchAlgorithmException, NoSuchProviderException { + byte[] raSecret = initAuthPassword.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); + MessageDigest dig = + MessageDigest.getInstance( + OWF_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME); + for (int i = 0; i < ITERATIONS; i++) { + baseKey = dig.digest(baseKey); + dig.reset(); + } + return baseKey; + } + + private byte[] generateMacBytes(byte[] baseKey, byte[] protectedBytes) throws GeneralSecurityException { + 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); + return mac.doFinal(); + } + +} diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiMessageProtection.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiMessageProtection.java new file mode 100644 index 00000000..235d4bbf --- /dev/null +++ b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiMessageProtection.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.cmpv2client.impl.protections; + +import org.bouncycastle.asn1.DERBitString; +import org.bouncycastle.asn1.cmp.PKIBody; +import org.bouncycastle.asn1.cmp.PKIHeader; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.security.GeneralSecurityException; + +import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.generateProtectedBytes; + +/** + * Representation of PKIMessage protection. Complies with RFC4210 (Certificate Management Protocol + * (CMP)) and RFC4211 (Certificate Request Message Format (CRMF)) standards. + */ +public abstract class PkiMessageProtection { + + private static final Logger LOG = LoggerFactory.getLogger(PkiMessageProtection.class); + + /** + * Takes PKIHeader and PKIBody as parameters and generates protection bytes. + * + * @return bytes representing protection wrapped into DERBitString object. + */ + public DERBitString generatePkiMessageProtection(PKIHeader pkiHeader, PKIBody pkiBody) throws CmpClientException { + try { + byte[] protectedBytes = generateProtectedBytes(pkiHeader, pkiBody); + byte[] protectionBytes = generateProtectionBytes(protectedBytes); + return new DERBitString(protectionBytes); + } catch (GeneralSecurityException ex) { + CmpClientException cmpClientException = + new CmpClientException( + "Exception occurred while generating protection for PKIMessage", ex); + LOG.error("Exception occurred while generating the protection for PKIMessage"); + throw cmpClientException; + } + } + + /** + * Returns Algorithm Identifier for protection of PKIMessage. + * + * @return Algorithm Identifier. + */ + public abstract AlgorithmIdentifier getAlgorithmIdentifier(); + + /** + * Takes encoded bytes of PKIMessage (PKIHeader and PKIBody) and generates protection bytes. + * + * @return bytes representing protection. + */ + abstract byte[] generateProtectionBytes(byte[] protectedBytes) throws GeneralSecurityException; + +} diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtection.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtection.java new file mode 100644 index 00000000..faf99c96 --- /dev/null +++ b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtection.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.cmpv2client.impl.protections; + + +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; + +import java.security.GeneralSecurityException; +import java.security.PrivateKey; +import java.security.Signature; + +/** + * Implementation of signature PKIMessage protection + */ +public class SignatureProtection extends PkiMessageProtection { + + private static final AlgorithmIdentifier SHA256_RSA_ALGORITHM = new DefaultSignatureAlgorithmIdentifierFinder() + .find("SHA256withRSA"); + + private final PrivateKey oldPrivateKey; + + public SignatureProtection(PrivateKey privateKey) { + this.oldPrivateKey = privateKey; + } + + @Override + public AlgorithmIdentifier getAlgorithmIdentifier() { + return SHA256_RSA_ALGORITHM; + } + + @Override + byte[] generateProtectionBytes(byte[] protectedBytes) throws GeneralSecurityException { + Signature signature = + Signature.getInstance( + PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), + BouncyCastleProvider.PROVIDER_NAME); + signature.initSign(oldPrivateKey); + signature.update(protectedBytes, 0, protectedBytes.length); + return signature.sign(); + } + +} diff --git a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/validation/CmpCertificationValidator.java b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/validation/CmpCertificationValidator.java index 40a2a1d9..b9a04a47 100644 --- a/certService/src/main/java/org/onap/oom/certservice/cmpv2client/validation/CmpCertificationValidator.java +++ b/certService/src/main/java/org/onap/oom/certservice/cmpv2client/validation/CmpCertificationValidator.java @@ -22,14 +22,7 @@ package org.onap.oom.certservice.cmpv2client.validation; -import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.checkImplicitConfirm; -import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifyPasswordBasedProtection; -import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifySignature; -import java.security.PublicKey; -import java.util.Date; -import java.util.Objects; -import java.util.Optional; import org.apache.http.impl.client.CloseableHttpClient; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.cmp.CertResponse; @@ -46,13 +39,22 @@ import org.onap.oom.certservice.cmpv2client.impl.PkiStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.security.PublicKey; +import java.util.Date; +import java.util.Objects; +import java.util.Optional; + +import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.checkImplicitConfirm; +import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifyPasswordBasedProtection; +import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifySignature; + public class CmpCertificationValidator { private static final String DEFAULT_CA_NAME = "Certification Authority"; private static final String DEFAULT_PROFILE = CaMode.RA.getProfile(); private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC = new ASN1ObjectIdentifier("1.2.840.113533.7.66.13"); private static final Logger LOG = LoggerFactory.getLogger(CmpCertificationValidator.class); - public static void validate( + public void validate( final CsrModel csrModel, final Cmpv2Server server, final CloseableHttpClient httpClient, diff --git a/certService/src/test/java/org/onap/oom/certservice/certification/conversion/CsrModelFactoryTest.java b/certService/src/test/java/org/onap/oom/certservice/certification/conversion/CsrModelFactoryTest.java index 26624867..54508e4b 100644 --- a/certService/src/test/java/org/onap/oom/certservice/certification/conversion/CsrModelFactoryTest.java +++ b/certService/src/test/java/org/onap/oom/certservice/certification/conversion/CsrModelFactoryTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Cert Service * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. + * Copyright (C) 2020-2021 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. @@ -20,13 +20,6 @@ package org.onap.oom.certservice.certification.conversion; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.onap.oom.certservice.certification.TestData.TEST_CSR; -import static org.onap.oom.certservice.certification.TestData.TEST_PK; -import static org.onap.oom.certservice.certification.TestData.TEST_WRONG_CSR; -import static org.onap.oom.certservice.certification.TestData.TEST_WRONG_PEM; - import org.bouncycastle.util.encoders.Base64; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -36,6 +29,13 @@ import org.onap.oom.certservice.certification.exception.DecryptionException; import org.onap.oom.certservice.certification.exception.KeyDecryptionException; import org.onap.oom.certservice.certification.model.CsrModel; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.onap.oom.certservice.certification.TestData.TEST_CSR; +import static org.onap.oom.certservice.certification.TestData.TEST_PK; +import static org.onap.oom.certservice.certification.TestData.TEST_WRONG_CSR; +import static org.onap.oom.certservice.certification.TestData.TEST_WRONG_PEM; + class CsrModelFactoryTest { @@ -58,7 +58,6 @@ class CsrModelFactoryTest { assertTrue(decryptedCsr.toString() .contains(TestData.EXPECTED_CERT_SUBJECT)); - System.out.println(decryptedCsr.toString()); assertTrue(decryptedCsr.toString() .contains(TestData.EXPECTED_CERT_SANS)); } diff --git a/certService/src/test/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverterTest.java b/certService/src/test/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverterTest.java new file mode 100644 index 00000000..7a722b2c --- /dev/null +++ b/certService/src/test/java/org/onap/oom/certservice/certification/conversion/StringBase64ToPrivateKeyConverterTest.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.certification.conversion; + +import org.bouncycastle.util.encoders.Base64; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.certification.exception.KeyDecryptionException; + +import java.security.PrivateKey; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.onap.oom.certservice.certification.TestData.TEST_PEM; +import static org.onap.oom.certservice.certification.TestData.TEST_PK; + +class StringBase64ToPrivateKeyConverterTest { + + private static final String RSA = "RSA"; + public static final String PKCS_8 = "PKCS#8"; + + @Test + void shouldUseProperAlgorithmWhenConverting() throws KeyDecryptionException { + // Given + StringBase64ToPrivateKeyConverter stringBase64ToPrivateKeyConverter = new StringBase64ToPrivateKeyConverter(); + String encodedPK = new String(Base64.encode(TEST_PK.getBytes())); + // When + PrivateKey privateKey = stringBase64ToPrivateKeyConverter.convert(new StringBase64(encodedPK)); + // Then + assertEquals(RSA, privateKey.getAlgorithm()); + } + + @Test + void shouldUsePkcs8FormatWhenConverting() throws KeyDecryptionException { + // Given + StringBase64ToPrivateKeyConverter stringBase64ToPrivateKeyConverter = new StringBase64ToPrivateKeyConverter(); + String encodedPK = new String(Base64.encode(TEST_PK.getBytes())); + // When + PrivateKey privateKey = stringBase64ToPrivateKeyConverter.convert(new StringBase64(encodedPK)); + // Then + assertEquals(PKCS_8, privateKey.getFormat()); + } + + @Test + void shouldCorrectlyConvertWhenPrivateKeyPemIsProper() throws KeyDecryptionException { + // Given + StringBase64ToPrivateKeyConverter stringBase64ToPrivateKeyConverter = new StringBase64ToPrivateKeyConverter(); + String encodedPK = new String(Base64.encode(TEST_PK.getBytes())); + // When + PrivateKey privateKey = stringBase64ToPrivateKeyConverter.convert(new StringBase64(encodedPK)); + // Then + assertNotNull(privateKey.getEncoded()); + } + + @Test + void shouldThrowExceptionWhenPrivateKeyPemIsNotProperPrivateKey() { + // Given + StringBase64ToPrivateKeyConverter stringBase64ToPrivateKeyConverter = new StringBase64ToPrivateKeyConverter(); + StringBase64 privateKey = new StringBase64(TEST_PEM); + // When + Exception exception = assertThrows( + KeyDecryptionException.class, () -> stringBase64ToPrivateKeyConverter.convert(privateKey)); + + String expectedMessage = "Incorrect Key, decryption failed"; + String actualMessage = exception.getMessage(); + // Then + assertTrue(actualMessage.contains(expectedMessage)); + } + +} diff --git a/certService/src/test/java/org/onap/oom/certservice/certification/model/CsrModelTest.java b/certService/src/test/java/org/onap/oom/certservice/certification/model/CsrModelTest.java index 72837e56..c3bd4d78 100644 --- a/certService/src/test/java/org/onap/oom/certservice/certification/model/CsrModelTest.java +++ b/certService/src/test/java/org/onap/oom/certservice/certification/model/CsrModelTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PROJECT * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. + * Copyright (C) 2020-2021 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. @@ -20,21 +20,26 @@ package org.onap.oom.certservice.certification.model; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; 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.oom.certservice.certification.conversion.Pkcs10CertificationRequestFactory; -import org.onap.oom.certservice.certification.conversion.PemObjectFactory; import org.onap.oom.certservice.certification.TestData; +import org.onap.oom.certservice.certification.conversion.PemObjectFactory; +import org.onap.oom.certservice.certification.conversion.Pkcs10CertificationRequestFactory; import org.onap.oom.certservice.certification.exception.CsrDecryptionException; import org.onap.oom.certservice.certification.exception.DecryptionException; import org.onap.oom.certservice.certification.exception.KeyDecryptionException; import java.io.IOException; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -57,7 +62,7 @@ class CsrModelTest { @Test void shouldByConstructedAndReturnProperFields() throws DecryptionException, IOException { // Given - PemObject testPrivateKey = getPemPrivateKey(); + PrivateKey testPrivateKey = getPemPrivateKey(); PemObject testPublicKey = generateTestPublicKey(); PKCS10CertificationRequest testCsr = generateTestCertificationRequest(); @@ -70,7 +75,7 @@ class CsrModelTest { assertThat(csrModel.getCsr()) .isEqualTo(testCsr); assertThat(csrModel.getPrivateKey().getEncoded()) - .contains(testPrivateKey.getContent()); + .isEqualTo(testPrivateKey.getEncoded()); assertThat(csrModel.getPublicKey().getEncoded()) .contains(testPublicKey.getContent()); assertThat(sansList) @@ -84,7 +89,7 @@ class CsrModelTest { @Test void shouldThrowExceptionWhenPublicKeyIsNotCorrect() throws DecryptionException, IOException { // Given - PemObject testPrivateKey = getPemPrivateKey(); + PrivateKey testPrivateKey = getPemPrivateKey(); PKCS10CertificationRequest testCsr = mock(PKCS10CertificationRequest.class); SubjectPublicKeyInfo wrongKryInfo = mock(SubjectPublicKeyInfo.class); when(testCsr.getSubjectPublicKeyInfo()) @@ -105,34 +110,10 @@ class CsrModelTest { assertTrue(actualMessage.contains(expectedMessage)); } - @Test - void shouldThrowExceptionWhenPrivateKeyPemIsNotProperPrivateKey() throws KeyDecryptionException, IOException { - // Given - PemObject testPrivateKey = getPemWrongKey(); - PKCS10CertificationRequest testCsr = mock(PKCS10CertificationRequest.class); - SubjectPublicKeyInfo wrongKryInfo = mock(SubjectPublicKeyInfo.class); - when(testCsr.getSubjectPublicKeyInfo()) - .thenReturn(wrongKryInfo); - when(wrongKryInfo.getEncoded()) - .thenThrow(new IOException()); - - // When - Exception exception = assertThrows( - KeyDecryptionException.class, - () -> new CsrModel.CsrModelBuilder(testCsr, testPrivateKey).build() - ); - - String expectedMessage = "Converting Private Key failed"; - String actualMessage = exception.getMessage(); - - // Then - assertTrue(actualMessage.contains(expectedMessage)); - } - @Test void shouldThrowExceptionWhenPublicKeyPemIsNotProperPublicKey() throws KeyDecryptionException, IOException { // Given - PemObject testPrivateKey = getPemPrivateKey(); + PrivateKey testPrivateKey = getPemPrivateKey(); PemObject testPublicKey = getPemWrongKey(); PKCS10CertificationRequest testCsr = mock(PKCS10CertificationRequest.class); SubjectPublicKeyInfo wrongKryInfo = mock(SubjectPublicKeyInfo.class); @@ -154,11 +135,12 @@ class CsrModelTest { assertTrue(actualMessage.contains(expectedMessage)); } - private PemObject getPemPrivateKey() throws KeyDecryptionException { + private PrivateKey getPemPrivateKey() throws KeyDecryptionException { PemObjectFactory pemObjectFactory = new PemObjectFactory(); - return pemObjectFactory.createPemObject(TEST_PK).orElseThrow( - () -> new KeyDecryptionException("Private key decoding fail") + PemObject pemObject = pemObjectFactory.createPemObject(TEST_PK).orElseThrow( + () -> new KeyDecryptionException("Private key decoding fail") ); + return convertToPrivateKey(pemObject); } private PemObject getPemWrongKey() throws KeyDecryptionException { @@ -172,7 +154,7 @@ class CsrModelTest { PemObject testPrivateKey = pemObjectFactory.createPemObject(TEST_PK).orElseThrow( () -> new DecryptionException("Incorrect Private Key, decryption failed") ); - return new CsrModel.CsrModelBuilder(testCsr, testPrivateKey).build(); + return new CsrModel.CsrModelBuilder(testCsr, convertToPrivateKey(testPrivateKey)).build(); } private PemObject generateTestPublicKey() throws DecryptionException, IOException { @@ -189,4 +171,15 @@ class CsrModelTest { ); } + private PrivateKey convertToPrivateKey(PemObject privateKey) + throws KeyDecryptionException { + try { + KeyFactory factory = KeyFactory.getInstance("RSA"); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getContent()); + return factory.generatePrivate(keySpec); + } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { + throw new KeyDecryptionException("Converting Private Key failed", e.getCause()); + } + } + } diff --git a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtectionTest.java b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtectionTest.java deleted file mode 100644 index b280a2e6..00000000 --- a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PasswordBasedProtectionTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nokia. - * ================================================================================ - * 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========================================================= - */ - -package org.onap.oom.certservice.cmpv2client.impl; - -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.cmp.PBMParameter; -import org.bouncycastle.asn1.cmp.PKIBody; -import org.bouncycastle.asn1.cmp.PKIHeader; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.cert.cmp.CMPException; -import org.bouncycastle.cert.cmp.ProtectedPKIMessage; -import org.bouncycastle.cert.crmf.PKMACBuilder; -import org.bouncycastle.cert.crmf.jcajce.JcePKMACValuesCalculator; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; - -import java.security.Security; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.onap.oom.certservice.cmpv2client.impl.PkiTestUtils.getProtectedPkiMessage; -import static org.onap.oom.certservice.cmpv2client.impl.PkiTestUtils.getTestPkiHeader; - -class PasswordBasedProtectionTest { - - private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC = new ASN1ObjectIdentifier("1.2.840.113533.7.66.13"); - private static final AlgorithmIdentifier SHA_1_ALGORITHM = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26")); - private static final AlgorithmIdentifier H_MAC_SHA_1_ALGORITHM = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.6.1.5.5.8.1.2")); - private static final int MIN_ITERATION_COUNT = 1000; - private static final int MAX_ITERATION_COUNT = 2000; - private static final int SALT_LENGTH = 16; - - @BeforeAll - static void setUp() { - Security.addProvider(new BouncyCastleProvider()); - } - - @AfterAll - static void clean() { - Security.removeProvider("BC"); - } - - @Test - void shouldReturnPasswordBasedMacAlgorithmWhenGetAlgorithmMethodCalled() { - //Given - PasswordBasedProtection protection = new PasswordBasedProtection(null); - //When - AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); - //Then - assertEquals(PASSWORD_BASED_MAC, algorithmIdentifier.getAlgorithm()); - } - - @Test - void shouldSetPasswordBasedParametersWhenGetAlgorithmMethodCalled() { - //Given - PasswordBasedProtection protection = new PasswordBasedProtection(null); - //When - AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); - //Then - assertTrue(algorithmIdentifier.getParameters() instanceof PBMParameter); - } - - @Test - void shouldSetSha1ForOwfWhenGetAlgorithmMethodCalled() { - //Given - PasswordBasedProtection protection = new PasswordBasedProtection(null); - //When - AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); - //Then - PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); - assertEquals(SHA_1_ALGORITHM, pbmParameters.getOwf()); - } - - @Test - void shouldSetHMacSha1ForMacWhenGetAlgorithmMethodCalled() { - //Given - PasswordBasedProtection protection = new PasswordBasedProtection(null); - //When - AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); - //Then - PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); - assertEquals(H_MAC_SHA_1_ALGORITHM, pbmParameters.getMac()); - } - - @Test - void shouldSetSaltWhenGetAlgorithmMethodCalled() { - //Given - PasswordBasedProtection protection = new PasswordBasedProtection(null); - //When - AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); - //Then - PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); - assertTrue(pbmParameters.getSalt() instanceof DEROctetString); - DEROctetString salt = (DEROctetString) pbmParameters.getSalt(); - assertEquals(SALT_LENGTH, salt.getOctets().length); - } - - @Test - void shouldSetIterationCountWhenGetAlgorithmMethodCalled() { - //Given - PasswordBasedProtection protection = new PasswordBasedProtection(null); - //When - AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); - //Then - PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); - assertNotNull(pbmParameters.getIterationCount()); - long iterationCount = pbmParameters.getIterationCount().getValue().longValue(); - assertTrue(MIN_ITERATION_COUNT <= iterationCount && iterationCount < MAX_ITERATION_COUNT, - "Iteration count not in range"); - } - - @ParameterizedTest - @ValueSource(strings = {"test", "123"}) - void shouldReturnProtectionByPasswordWhenGenerateProtectionMethodCalled(String initAuthPassword) - throws CmpClientException, CMPException { - //Given - PasswordBasedProtection protection = new PasswordBasedProtection(initAuthPassword); - PKIHeader pkiHeader = getTestPkiHeader(protection.getAlgorithmIdentifier()); - PKIBody pkiBody = PkiTestUtils.getTestPkiBody(SHA_1_ALGORITHM); - //When - DERBitString messageProtection = protection.generatePkiMessageProtection(pkiHeader, pkiBody); - //Then - ProtectedPKIMessage protectedPkiMessage = getProtectedPkiMessage(pkiHeader, pkiBody, messageProtection); - PKMACBuilder pkMacBuilder = new PKMACBuilder(new JcePKMACValuesCalculator()); - assertTrue(protectedPkiMessage.verify(pkMacBuilder, initAuthPassword.toCharArray())); - } - -} diff --git a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PkiTestUtils.java b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PkiTestUtils.java deleted file mode 100644 index 7f7df455..00000000 --- a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/PkiTestUtils.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nokia. - * ================================================================================ - * 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========================================================= - */ - -package org.onap.oom.certservice.cmpv2client.impl; - -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DERGeneralizedTime; -import org.bouncycastle.asn1.cmp.PKIBody; -import org.bouncycastle.asn1.cmp.PKIHeader; -import org.bouncycastle.asn1.cmp.PKIHeaderBuilder; -import org.bouncycastle.asn1.cmp.PKIMessage; -import org.bouncycastle.asn1.crmf.CertReqMessages; -import org.bouncycastle.asn1.crmf.CertReqMsg; -import org.bouncycastle.asn1.crmf.CertRequest; -import org.bouncycastle.asn1.crmf.CertTemplateBuilder; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.cert.cmp.GeneralPKIMessage; -import org.bouncycastle.cert.cmp.ProtectedPKIMessage; -import org.bouncycastle.operator.ContentVerifierProvider; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.util.Date; - -final class PkiTestUtils { - - private static final String CN_TEST_SUBJECT = "CN=test1Subject"; - private static final String CN_TEST_ISSUER = "CN=test2Issuer"; - private static final int TEST_CERT_REQUEST_ID = 1432; - private static final int PVNO = 0; - private static final String BC_PROVIDER = "BC"; - private static final String RSA = "RSA"; - - private PkiTestUtils() { - } - - static PKIBody getTestPkiBody(AlgorithmIdentifier signingAlgorithm) { - CertTemplateBuilder certTemplateBuilder = - new CertTemplateBuilder() - .setIssuer(new X500Name(CN_TEST_ISSUER)) - .setSubject(new X500Name(CN_TEST_SUBJECT)) - .setSigningAlg(signingAlgorithm); - - CertRequest certRequest = new CertRequest(TEST_CERT_REQUEST_ID, certTemplateBuilder.build(), null); - CertReqMsg certReqMsg = new CertReqMsg(certRequest, null, null); - - CertReqMessages certReqMessages = new CertReqMessages(certReqMsg); - return new PKIBody(0, certReqMessages); - } - - static PKIHeader getTestPkiHeader(AlgorithmIdentifier protectionAlgorithm) { - PKIHeaderBuilder pkiHeader = new PKIHeaderBuilder( - PVNO, - new GeneralName(new X500Name(CN_TEST_SUBJECT)), - new GeneralName(new X500Name(CN_TEST_ISSUER))); - pkiHeader.setProtectionAlg(protectionAlgorithm); - pkiHeader.setMessageTime(new DERGeneralizedTime(new Date())); - return pkiHeader.build(); - } - - static ProtectedPKIMessage getProtectedPkiMessage(PKIHeader pkiHeader, PKIBody pkiBody, DERBitString messageProtection) { - PKIMessage pkiMessage = new PKIMessage(pkiHeader, pkiBody, messageProtection); - GeneralPKIMessage generalPkiMessage = new GeneralPKIMessage(pkiMessage); - return new ProtectedPKIMessage(generalPkiMessage); - } - - static KeyPair getKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA, BC_PROVIDER); - return keyPairGenerator.generateKeyPair(); - } - - static ContentVerifierProvider getContentVerifierProvider(PublicKey publicKey) throws OperatorCreationException { - return new JcaContentVerifierProviderBuilder() - .setProvider(BC_PROVIDER) - .build(publicKey); - } -} diff --git a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtectionTest.java b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtectionTest.java deleted file mode 100644 index ba382c42..00000000 --- a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/SignatureProtectionTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nokia. - * ================================================================================ - * 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========================================================= - */ - -package org.onap.oom.certservice.cmpv2client.impl; - -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.cmp.PKIBody; -import org.bouncycastle.asn1.cmp.PKIHeader; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.cert.cmp.CMPException; -import org.bouncycastle.cert.cmp.ProtectedPKIMessage; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.operator.ContentVerifierProvider; -import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; -import org.bouncycastle.operator.OperatorCreationException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; - -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.Security; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.onap.oom.certservice.cmpv2client.impl.PkiTestUtils.getProtectedPkiMessage; -import static org.onap.oom.certservice.cmpv2client.impl.PkiTestUtils.getTestPkiBody; -import static org.onap.oom.certservice.cmpv2client.impl.PkiTestUtils.getTestPkiHeader; - -class SignatureProtectionTest { - - private static final String SHA256_RSA_OID = "1.2.840.113549.1.1.11"; - private static final AlgorithmIdentifier SHA256_RSA_ALGORITHM = new DefaultSignatureAlgorithmIdentifierFinder() - .find("SHA256withRSA"); - private static final String BC_PROVIDER = "BC"; - - @BeforeAll - static void setUp() { - Security.addProvider(new BouncyCastleProvider()); - } - - @AfterAll - static void clean() { - Security.removeProvider(BC_PROVIDER); - } - - @Test - void shouldReturnExpectedAlgorithmWhenGetAlgorithmMethodCalled() { - //Given - SignatureProtection signatureProtection = new SignatureProtection(null); - //When - AlgorithmIdentifier algorithmIdentifier = signatureProtection.getAlgorithmIdentifier(); - //Then - assertNotNull(algorithmIdentifier); - assertNotNull(algorithmIdentifier.getAlgorithm()); - assertEquals(SHA256_RSA_OID, algorithmIdentifier.getAlgorithm().toString()); - } - - @Test - void shouldReturnProtectionByPkWhenGenerateProtectionMethodCalled() - throws GeneralSecurityException, CmpClientException, OperatorCreationException, CMPException { - //Given - KeyPair keyPair = PkiTestUtils.getKeyPair(); - SignatureProtection signatureProtection = new SignatureProtection(keyPair.getPrivate()); - PKIHeader pkiHeader = getTestPkiHeader(SHA256_RSA_ALGORITHM); - PKIBody pkiBody = getTestPkiBody(SHA256_RSA_ALGORITHM); - //When - DERBitString protection = signatureProtection.generatePkiMessageProtection(pkiHeader, pkiBody); - //Then - ProtectedPKIMessage protectedPkiMessage = getProtectedPkiMessage(pkiHeader, pkiBody, protection); - ContentVerifierProvider verifierProvider = PkiTestUtils.getContentVerifierProvider(keyPair.getPublic()); - assertTrue(protectedPkiMessage.verify(verifierProvider)); - } - -} diff --git a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtectionTest.java b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtectionTest.java new file mode 100644 index 00000000..c249fab7 --- /dev/null +++ b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PasswordBasedProtectionTest.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.cmpv2client.impl.protections; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DERBitString; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.cmp.PBMParameter; +import org.bouncycastle.asn1.cmp.PKIBody; +import org.bouncycastle.asn1.cmp.PKIHeader; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.cert.cmp.CMPException; +import org.bouncycastle.cert.cmp.ProtectedPKIMessage; +import org.bouncycastle.cert.crmf.PKMACBuilder; +import org.bouncycastle.cert.crmf.jcajce.JcePKMACValuesCalculator; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; + +import java.security.Security; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.onap.oom.certservice.cmpv2client.impl.protections.PkiTestUtils.getProtectedPkiMessage; +import static org.onap.oom.certservice.cmpv2client.impl.protections.PkiTestUtils.getTestPkiHeader; + +class PasswordBasedProtectionTest { + + private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC = new ASN1ObjectIdentifier("1.2.840.113533.7.66.13"); + private static final AlgorithmIdentifier SHA_1_ALGORITHM = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26")); + private static final AlgorithmIdentifier H_MAC_SHA_1_ALGORITHM = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.6.1.5.5.8.1.2")); + private static final int MIN_ITERATION_COUNT = 1000; + private static final int MAX_ITERATION_COUNT = 2000; + private static final int SALT_LENGTH = 16; + + @BeforeAll + static void setUp() { + Security.addProvider(new BouncyCastleProvider()); + } + + @AfterAll + static void clean() { + Security.removeProvider("BC"); + } + + @Test + void shouldReturnPasswordBasedMacAlgorithmWhenGetAlgorithmMethodCalled() { + //Given + PasswordBasedProtection protection = new PasswordBasedProtection(null); + //When + AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); + //Then + assertEquals(PASSWORD_BASED_MAC, algorithmIdentifier.getAlgorithm()); + } + + @Test + void shouldSetPasswordBasedParametersWhenGetAlgorithmMethodCalled() { + //Given + PasswordBasedProtection protection = new PasswordBasedProtection(null); + //When + AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); + //Then + assertTrue(algorithmIdentifier.getParameters() instanceof PBMParameter); + } + + @Test + void shouldSetSha1ForOwfWhenGetAlgorithmMethodCalled() { + //Given + PasswordBasedProtection protection = new PasswordBasedProtection(null); + //When + AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); + //Then + PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); + assertEquals(SHA_1_ALGORITHM, pbmParameters.getOwf()); + } + + @Test + void shouldSetHMacSha1ForMacWhenGetAlgorithmMethodCalled() { + //Given + PasswordBasedProtection protection = new PasswordBasedProtection(null); + //When + AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); + //Then + PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); + assertEquals(H_MAC_SHA_1_ALGORITHM, pbmParameters.getMac()); + } + + @Test + void shouldSetSaltWhenGetAlgorithmMethodCalled() { + //Given + PasswordBasedProtection protection = new PasswordBasedProtection(null); + //When + AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); + //Then + PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); + assertTrue(pbmParameters.getSalt() instanceof DEROctetString); + DEROctetString salt = (DEROctetString) pbmParameters.getSalt(); + assertEquals(SALT_LENGTH, salt.getOctets().length); + } + + @Test + void shouldSetIterationCountWhenGetAlgorithmMethodCalled() { + //Given + PasswordBasedProtection protection = new PasswordBasedProtection(null); + //When + AlgorithmIdentifier algorithmIdentifier = protection.getAlgorithmIdentifier(); + //Then + PBMParameter pbmParameters = (PBMParameter) algorithmIdentifier.getParameters(); + assertNotNull(pbmParameters.getIterationCount()); + long iterationCount = pbmParameters.getIterationCount().getValue().longValue(); + assertTrue(MIN_ITERATION_COUNT <= iterationCount && iterationCount < MAX_ITERATION_COUNT, + "Iteration count not in range"); + } + + @ParameterizedTest + @ValueSource(strings = {"test", "123"}) + void shouldReturnProtectionByPasswordWhenGenerateProtectionMethodCalled(String initAuthPassword) + throws CmpClientException, CMPException { + //Given + PasswordBasedProtection protection = new PasswordBasedProtection(initAuthPassword); + PKIHeader pkiHeader = getTestPkiHeader(protection.getAlgorithmIdentifier()); + PKIBody pkiBody = PkiTestUtils.getTestPkiBody(SHA_1_ALGORITHM); + //When + DERBitString messageProtection = protection.generatePkiMessageProtection(pkiHeader, pkiBody); + //Then + ProtectedPKIMessage protectedPkiMessage = getProtectedPkiMessage(pkiHeader, pkiBody, messageProtection); + PKMACBuilder pkMacBuilder = new PKMACBuilder(new JcePKMACValuesCalculator()); + assertTrue(protectedPkiMessage.verify(pkMacBuilder, initAuthPassword.toCharArray())); + } + +} diff --git a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiTestUtils.java b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiTestUtils.java new file mode 100644 index 00000000..74af51c1 --- /dev/null +++ b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/PkiTestUtils.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.cmpv2client.impl.protections; + +import org.bouncycastle.asn1.DERBitString; +import org.bouncycastle.asn1.DERGeneralizedTime; +import org.bouncycastle.asn1.cmp.PKIBody; +import org.bouncycastle.asn1.cmp.PKIHeader; +import org.bouncycastle.asn1.cmp.PKIHeaderBuilder; +import org.bouncycastle.asn1.cmp.PKIMessage; +import org.bouncycastle.asn1.crmf.CertReqMessages; +import org.bouncycastle.asn1.crmf.CertReqMsg; +import org.bouncycastle.asn1.crmf.CertRequest; +import org.bouncycastle.asn1.crmf.CertTemplateBuilder; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.cert.cmp.GeneralPKIMessage; +import org.bouncycastle.cert.cmp.ProtectedPKIMessage; +import org.bouncycastle.operator.ContentVerifierProvider; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.util.Date; + +final class PkiTestUtils { + + private static final String CN_TEST_SUBJECT = "CN=test1Subject"; + private static final String CN_TEST_ISSUER = "CN=test2Issuer"; + private static final int TEST_CERT_REQUEST_ID = 1432; + private static final int PVNO = 0; + private static final String BC_PROVIDER = "BC"; + private static final String RSA = "RSA"; + + private PkiTestUtils() { + } + + static PKIBody getTestPkiBody(AlgorithmIdentifier signingAlgorithm) { + CertTemplateBuilder certTemplateBuilder = + new CertTemplateBuilder() + .setIssuer(new X500Name(CN_TEST_ISSUER)) + .setSubject(new X500Name(CN_TEST_SUBJECT)) + .setSigningAlg(signingAlgorithm); + + CertRequest certRequest = new CertRequest(TEST_CERT_REQUEST_ID, certTemplateBuilder.build(), null); + CertReqMsg certReqMsg = new CertReqMsg(certRequest, null, null); + + CertReqMessages certReqMessages = new CertReqMessages(certReqMsg); + return new PKIBody(0, certReqMessages); + } + + static PKIHeader getTestPkiHeader(AlgorithmIdentifier protectionAlgorithm) { + PKIHeaderBuilder pkiHeader = new PKIHeaderBuilder( + PVNO, + new GeneralName(new X500Name(CN_TEST_SUBJECT)), + new GeneralName(new X500Name(CN_TEST_ISSUER))); + pkiHeader.setProtectionAlg(protectionAlgorithm); + pkiHeader.setMessageTime(new DERGeneralizedTime(new Date())); + return pkiHeader.build(); + } + + static ProtectedPKIMessage getProtectedPkiMessage(PKIHeader pkiHeader, PKIBody pkiBody, DERBitString messageProtection) { + PKIMessage pkiMessage = new PKIMessage(pkiHeader, pkiBody, messageProtection); + GeneralPKIMessage generalPkiMessage = new GeneralPKIMessage(pkiMessage); + return new ProtectedPKIMessage(generalPkiMessage); + } + + static KeyPair getKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA, BC_PROVIDER); + return keyPairGenerator.generateKeyPair(); + } + + static ContentVerifierProvider getContentVerifierProvider(PublicKey publicKey) throws OperatorCreationException { + return new JcaContentVerifierProviderBuilder() + .setProvider(BC_PROVIDER) + .build(publicKey); + } +} diff --git a/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtectionTest.java b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtectionTest.java new file mode 100644 index 00000000..a97a3c6e --- /dev/null +++ b/certService/src/test/java/org/onap/oom/certservice/cmpv2client/impl/protections/SignatureProtectionTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nokia. + * ================================================================================ + * 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========================================================= + */ + +package org.onap.oom.certservice.cmpv2client.impl.protections; + +import org.bouncycastle.asn1.DERBitString; +import org.bouncycastle.asn1.cmp.PKIBody; +import org.bouncycastle.asn1.cmp.PKIHeader; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.cert.cmp.CMPException; +import org.bouncycastle.cert.cmp.ProtectedPKIMessage; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentVerifierProvider; +import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; +import org.bouncycastle.operator.OperatorCreationException; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException; + +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.Security; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.onap.oom.certservice.cmpv2client.impl.protections.PkiTestUtils.getProtectedPkiMessage; +import static org.onap.oom.certservice.cmpv2client.impl.protections.PkiTestUtils.getTestPkiBody; +import static org.onap.oom.certservice.cmpv2client.impl.protections.PkiTestUtils.getTestPkiHeader; + +class SignatureProtectionTest { + + private static final String SHA256_RSA_OID = "1.2.840.113549.1.1.11"; + private static final AlgorithmIdentifier SHA256_RSA_ALGORITHM = new DefaultSignatureAlgorithmIdentifierFinder() + .find("SHA256withRSA"); + private static final String BC_PROVIDER = "BC"; + + @BeforeAll + static void setUp() { + Security.addProvider(new BouncyCastleProvider()); + } + + @AfterAll + static void clean() { + Security.removeProvider(BC_PROVIDER); + } + + @Test + void shouldReturnExpectedAlgorithmWhenGetAlgorithmMethodCalled() { + //Given + SignatureProtection signatureProtection = new SignatureProtection(null); + //When + AlgorithmIdentifier algorithmIdentifier = signatureProtection.getAlgorithmIdentifier(); + //Then + assertNotNull(algorithmIdentifier); + assertNotNull(algorithmIdentifier.getAlgorithm()); + assertEquals(SHA256_RSA_OID, algorithmIdentifier.getAlgorithm().toString()); + } + + @Test + void shouldReturnProtectionByPkWhenGenerateProtectionMethodCalled() + throws GeneralSecurityException, CmpClientException, OperatorCreationException, CMPException { + //Given + KeyPair keyPair = PkiTestUtils.getKeyPair(); + SignatureProtection signatureProtection = new SignatureProtection(keyPair.getPrivate()); + PKIHeader pkiHeader = getTestPkiHeader(SHA256_RSA_ALGORITHM); + PKIBody pkiBody = getTestPkiBody(SHA256_RSA_ALGORITHM); + //When + DERBitString protection = signatureProtection.generatePkiMessageProtection(pkiHeader, pkiBody); + //Then + ProtectedPKIMessage protectedPkiMessage = getProtectedPkiMessage(pkiHeader, pkiBody, protection); + ContentVerifierProvider verifierProvider = PkiTestUtils.getContentVerifierProvider(keyPair.getPublic()); + assertTrue(protectedPkiMessage.verify(verifierProvider)); + } + +} -- cgit 1.2.3-korg