Expose NetconfKeystoreService
[netconf.git] / keystore / keystore-legacy / src / main / java / org / opendaylight / netconf / keystore / legacy / impl / SecurityHelper.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.keystore.legacy.impl;
9
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;
19
20 final class SecurityHelper {
21     private CertificateFactory certFactory;
22     private KeyFactory dsaFactory;
23     private KeyFactory rsaFactory;
24
25     @NonNull PrivateKey generatePrivateKey(final byte[] privateKey) throws GeneralSecurityException {
26         final var keySpec = new PKCS8EncodedKeySpec(privateKey);
27
28         if (rsaFactory == null) {
29             rsaFactory = KeyFactory.getInstance("RSA");
30         }
31         try {
32             return rsaFactory.generatePrivate(keySpec);
33         } catch (InvalidKeySpecException ignore) {
34             // Ignored
35         }
36
37         if (dsaFactory == null) {
38             dsaFactory = KeyFactory.getInstance("DSA");
39         }
40         return dsaFactory.generatePrivate(keySpec);
41     }
42
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");
48         }
49         return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certificate));
50     }
51 }