Split out keystore-legacy
[netconf.git] / keystore / keystore-legacy / src / main / java / org / opendaylight / netconf / keystore / legacy / 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;
9
10 import java.io.ByteArrayInputStream;
11 import java.nio.charset.StandardCharsets;
12 import java.security.GeneralSecurityException;
13 import java.security.KeyFactory;
14 import java.security.PrivateKey;
15 import java.security.cert.CertificateFactory;
16 import java.security.cert.X509Certificate;
17 import java.security.spec.InvalidKeySpecException;
18 import java.security.spec.PKCS8EncodedKeySpec;
19 import java.util.Base64;
20 import org.eclipse.jdt.annotation.NonNull;
21
22 public final class SecurityHelper {
23     private CertificateFactory certFactory;
24     private KeyFactory dsaFactory;
25     private KeyFactory rsaFactory;
26
27     public @NonNull PrivateKey getJavaPrivateKey(final String base64PrivateKey) throws GeneralSecurityException {
28         final var keySpec = new PKCS8EncodedKeySpec(base64Decode(base64PrivateKey));
29
30         if (rsaFactory == null) {
31             rsaFactory = KeyFactory.getInstance("RSA");
32         }
33         try {
34             return rsaFactory.generatePrivate(keySpec);
35         } catch (InvalidKeySpecException ignore) {
36             // Ignored
37         }
38
39         if (dsaFactory == null) {
40             dsaFactory = KeyFactory.getInstance("DSA");
41         }
42         return dsaFactory.generatePrivate(keySpec);
43     }
44
45     public @NonNull X509Certificate getCertificate(final String base64Certificate) throws GeneralSecurityException {
46         // TODO: https://stackoverflow.com/questions/43809909/is-certificatefactory-getinstancex-509-thread-safe
47         //        indicates this is thread-safe in most cases, but can we get a better assurance?
48         if (certFactory == null) {
49             certFactory = CertificateFactory.getInstance("X.509");
50         }
51         return (X509Certificate) certFactory.generateCertificate(
52             new ByteArrayInputStream(base64Decode(base64Certificate)));
53     }
54
55     private static byte[] base64Decode(final String base64) {
56         return Base64.getMimeDecoder().decode(base64.getBytes(StandardCharsets.US_ASCII));
57     }
58
59 }