2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2021 Nokia. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.oom.certservice.certification.conversion;
23 import java.io.IOException;
24 import java.io.StringReader;
25 import java.security.cert.CertificateException;
26 import java.security.cert.X509Certificate;
27 import java.util.Optional;
28 import org.bouncycastle.cert.X509CertificateHolder;
29 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
30 import org.bouncycastle.jce.provider.BouncyCastleProvider;
31 import org.bouncycastle.openssl.PEMParser;
32 import org.onap.oom.certservice.certification.exception.StringToCertificateConversionException;
33 import org.springframework.stereotype.Service;
36 public class PemStringToCertificateConverter {
38 public X509Certificate convert(String certificatePemString) throws StringToCertificateConversionException {
39 try (PEMParser pemParser = new PEMParser(new StringReader(certificatePemString))) {
40 X509CertificateHolder certHolder = Optional.ofNullable((X509CertificateHolder) pemParser.readObject())
42 () -> new StringToCertificateConversionException("The certificate could not be converted correctly."));
43 return new JcaX509CertificateConverter()
44 .setProvider(new BouncyCastleProvider())
45 .getCertificate(certHolder);
46 } catch (IOException | CertificateException e) {
47 throw new StringToCertificateConversionException("Exception occurred during certificate conversion.", e);