2 * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.keystore.legacy.impl;
10 import java.io.ByteArrayInputStream;
11 import java.security.GeneralSecurityException;
12 import java.security.KeyFactory;
13 import java.security.PrivateKey;
14 import java.security.cert.CertificateFactory;
15 import java.security.cert.X509Certificate;
16 import java.security.spec.InvalidKeySpecException;
17 import java.security.spec.PKCS8EncodedKeySpec;
18 import org.eclipse.jdt.annotation.NonNull;
20 final class SecurityHelper {
21 private CertificateFactory certFactory;
22 private KeyFactory dsaFactory;
23 private KeyFactory rsaFactory;
25 @NonNull PrivateKey generatePrivateKey(final byte[] privateKey) throws GeneralSecurityException {
26 final var keySpec = new PKCS8EncodedKeySpec(privateKey);
28 if (rsaFactory == null) {
29 rsaFactory = KeyFactory.getInstance("RSA");
32 return rsaFactory.generatePrivate(keySpec);
33 } catch (InvalidKeySpecException ignore) {
37 if (dsaFactory == null) {
38 dsaFactory = KeyFactory.getInstance("DSA");
40 return dsaFactory.generatePrivate(keySpec);
43 @NonNull X509Certificate generateCertificate(final byte[] certificate) throws GeneralSecurityException {
44 // TODO: https://stackoverflow.com/questions/43809909/is-certificatefactory-getinstancex-509-thread-safe
45 // indicates this is thread-safe in most cases, but can we get a better assurance?
46 if (certFactory == null) {
47 certFactory = CertificateFactory.getInstance("X.509");
49 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certificate));