1 /*============LICENSE_START=======================================================
2 * aaf-certservice-client
3 * ================================================================================
4 * Copyright (C) 2020 Nokia. All rights reserved.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ============LICENSE_END=========================================================
20 package org.onap.aaf.certservice.client.certification;
23 import org.bouncycastle.util.io.pem.PemObject;
24 import org.bouncycastle.util.io.pem.PemReader;
25 import org.junit.jupiter.api.Test;
26 import org.onap.aaf.certservice.client.certification.exception.PkEncodingException;
28 import java.io.IOException;
29 import java.io.StringReader;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.security.KeyFactory;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.PrivateKey;
35 import java.security.spec.InvalidKeySpecException;
36 import java.security.spec.PKCS8EncodedKeySpec;
38 import static org.assertj.core.api.Assertions.assertThat;
40 class PrivateKeyToPemEncoderTest {
42 private static final String ENCRYPTION_ALGORITHM = "RSA";
43 private static final String RESOURCES_DIR = "src/test/resources/";
44 private static final String PRIVATE_KEY_PEM_PATH = RESOURCES_DIR + "rsaPrivateKeyPem";
47 void shouldReturnProperlyEncodedPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException, PkEncodingException, IOException {
49 String expectedPem = Files.readString(Paths.get(PRIVATE_KEY_PEM_PATH));
50 PrivateKeyToPemEncoder testedPkEncoder = new PrivateKeyToPemEncoder();
52 PrivateKey privateKey = extractPrivateKeyFromPem(expectedPem);
53 String resultPkInPem = testedPkEncoder.encodePrivateKeyToPem(privateKey);
55 assertThat(resultPkInPem).isEqualTo(expectedPem);
58 private PrivateKey extractPrivateKeyFromPem(String pem) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
59 PemReader pemReader = new PemReader(new StringReader(pem));
60 PemObject pemObject = pemReader.readPemObject();
62 PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent());
63 KeyFactory kf = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
64 return kf.generatePrivate(spec);