From d722ac5874a8b160847bbc5c705b122fe7ebe6f3 Mon Sep 17 00:00:00 2001
From: OZGCloud <ozgcloud@mgm-tp.com>
Date: Fri, 26 May 2023 13:50:53 +0200
Subject: [PATCH] OZG-3322 build key store like in zufi

---
 .../kop/user/MongodbCertificateLoader.java    | 35 +++++++++++++++++--
 1 file changed, 33 insertions(+), 2 deletions(-)

diff --git a/user-manager-server/src/main/java/de/itvsh/kop/user/MongodbCertificateLoader.java b/user-manager-server/src/main/java/de/itvsh/kop/user/MongodbCertificateLoader.java
index e19bfa17..b3d95e0a 100644
--- a/user-manager-server/src/main/java/de/itvsh/kop/user/MongodbCertificateLoader.java
+++ b/user-manager-server/src/main/java/de/itvsh/kop/user/MongodbCertificateLoader.java
@@ -8,7 +8,9 @@ import java.nio.file.Paths;
 import java.security.KeyStore;
 import java.security.KeyStoreException;
 import java.security.NoSuchAlgorithmException;
+import java.security.cert.Certificate;
 import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
 
 import javax.enterprise.context.ApplicationScoped;
 import javax.enterprise.event.Observes;
@@ -27,15 +29,44 @@ class MongodbCertificateLoader {
 
 	void onStart(@Observes StartupEvent ev) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
 		if(Files.exists(Paths.get(mongoDbCaCert))) {
+			buildKeyStore();
 			System.out.println("loading cert...");
-			KeyStore keystore = KeyStore.getInstance("pkcs12");
-			keystore.load(loadCaCrt(), null);
+//			KeyStore keystore = KeyStore.getInstance("pkcs12");
+//			keystore.load(loadCaCrt(), null);
 			System.out.println("cert loaded");
 		} else {
 			System.out.println("cert file does not exists");
 		}
 	}
 
+	KeyStore buildKeyStore() {
+		try {
+			var trustStore = initKeyStore();
+			trustStore.setCertificateEntry("ca", generateCertificate());
+			return trustStore;
+		} catch (Exception e) {
+			throw new TechnicalException("Error building KeyStore", e);
+		}
+	}
+
+	KeyStore initKeyStore() {
+		try {
+			var trustStore = KeyStore.getInstance("pkcs12");
+			trustStore.load(null, null);
+			return trustStore;
+		} catch (Exception e) {
+			throw new TechnicalException("Error init KeyStore", e);
+		}
+	}
+
+	Certificate generateCertificate() {
+		try {
+			return CertificateFactory.getInstance("X.509").generateCertificate(loadCaCrt());
+		} catch (Exception e) {
+			throw new TechnicalException("Error generating Certificate", e);
+		}
+	}
+
 	InputStream loadCaCrt() {
 		try {
 			return Files.newInputStream(Paths.get(mongoDbCaCert));
-- 
GitLab