[OOM-CERT-SERVICE] Refactor CertService API code
[oom/platform/cert-service.git] / certService / src / main / java / org / onap / oom / certservice / cmpv2client / impl / protections / SignatureProtection.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nokia.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.oom.certservice.cmpv2client.impl.protections;
22
23
24 import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
25 import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
26 import org.bouncycastle.jce.provider.BouncyCastleProvider;
27 import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder;
28
29 import java.security.GeneralSecurityException;
30 import java.security.PrivateKey;
31 import java.security.Signature;
32
33 /**
34  * Implementation of signature PKIMessage protection
35  */
36 public class SignatureProtection extends PkiMessageProtection {
37
38     private static final AlgorithmIdentifier SHA256_RSA_ALGORITHM = new DefaultSignatureAlgorithmIdentifierFinder()
39             .find("SHA256withRSA");
40
41     private final PrivateKey oldPrivateKey;
42
43     public SignatureProtection(PrivateKey privateKey) {
44         this.oldPrivateKey = privateKey;
45     }
46
47     @Override
48     public AlgorithmIdentifier getAlgorithmIdentifier() {
49         return SHA256_RSA_ALGORITHM;
50     }
51
52     @Override
53     byte[] generateProtectionBytes(byte[] protectedBytes) throws GeneralSecurityException {
54         Signature signature =
55                 Signature.getInstance(
56                         PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(),
57                         BouncyCastleProvider.PROVIDER_NAME);
58         signature.initSign(oldPrivateKey);
59         signature.update(protectedBytes, 0, protectedBytes.length);
60         return signature.sign();
61     }
62
63 }