You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by hu...@apache.org on 2021/01/17 11:46:50 UTC
[plc4x] 01/01: Add Encryption handler for opcua server
This is an automated email from the ASF dual-hosted git repository.
hutcheb pushed a commit to branch add_encryption_handler_opcua
in repository https://gitbox.apache.org/repos/asf/plc4x.git
commit aa172acbb4d7a99a1ac373c9d831615d71455b90
Author: hutcheb <be...@gmail.com>
AuthorDate: Sun Jan 17 06:45:46 2021 -0500
Add Encryption handler for opcua server
---
plc4j/integrations/opcua-server/pom.xml | 9 +-
.../plc4x/java/opcuaserver/KeyStoreLoader.java | 154 ---------------------
.../apache/plc4x/java/opcuaserver/OPCUAServer.java | 101 +++++++-------
.../java/opcuaserver/backend/Plc4xNamespace.java | 19 ++-
.../opcuaserver/context/CertificateKeyPair.java | 38 +++++
.../plc4x/java/opcuaserver/context/Encryption.java | 122 ++++++++++++++++
6 files changed, 234 insertions(+), 209 deletions(-)
diff --git a/plc4j/integrations/opcua-server/pom.xml b/plc4j/integrations/opcua-server/pom.xml
index 662af42..ede65e2 100644
--- a/plc4j/integrations/opcua-server/pom.xml
+++ b/plc4j/integrations/opcua-server/pom.xml
@@ -183,7 +183,7 @@
<scope>runtime</scope>
</dependency>
- <!-- Logging dependancies -->
+ <!-- Logging dependancies -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15on</artifactId>
@@ -208,7 +208,6 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</dependency>
-
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
@@ -219,6 +218,11 @@
<artifactId>vavr</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
+
</dependencies>
<build>
@@ -278,7 +282,6 @@
<configuration>
<usedDependencies combine.children="append">
<usedDependency>org.slf4j:slf4j-simple</usedDependency>
- <usedDependency>org.bouncycastle:bcpkix-jdk15on</usedDependency>
<usedDependency>org.bouncycastle:bcmail-jdk15on</usedDependency>
<usedDependency>org.apache.plc4x:plc4j-driver-ab-eth</usedDependency>
<!--usedDependency>org.apache.plc4x:plc4j-driver-ads</usedDependency-->
diff --git a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/KeyStoreLoader.java b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/KeyStoreLoader.java
deleted file mode 100644
index 4e4d4a7..0000000
--- a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/KeyStoreLoader.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (c) 2019 the Eclipse Milo Authors
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- */
-
-package org.apache.plc4x.java.opcuaserver;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.security.Key;
-import java.security.KeyPair;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Set;
-import java.util.UUID;
-import java.util.regex.Pattern;
-
-import com.google.common.collect.Sets;
-import org.apache.plc4x.java.opcuaserver.configuration.Configuration;
-import org.apache.plc4x.java.opcuaserver.configuration.PasswordConfiguration;
-import org.eclipse.milo.opcua.sdk.server.util.HostnameUtil;
-import org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateBuilder;
-import org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class KeyStoreLoader {
-
- private static final Pattern IP_ADDR_PATTERN = Pattern.compile(
- "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
-
- private final Logger logger = LoggerFactory.getLogger(getClass());
-
- private final String certificateFileName = "plc4x-opcuaserver.pfx";
-
- private X509Certificate[] serverCertificateChain;
- private X509Certificate serverCertificate;
- private KeyPair serverKeyPair;
-
- private Configuration config;
- private PasswordConfiguration passwordConfig;
-
- public KeyStoreLoader(Configuration config, PasswordConfiguration passwordConfig, Boolean interactive) {
- this.config = config;
- this.passwordConfig = passwordConfig;
-
- File securityTempDir = new File(config.getDir(), "security");
- if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
- logger.error("Unable to create directory please confirm folder permissions on " + securityTempDir.toString());
- System.exit(1);
- }
- logger.info("security dir: {}", securityTempDir.getAbsolutePath());
-
- try {
- load(securityTempDir, interactive);
- } catch (Exception e) {
- logger.error("Error loading the key store " + e);
- System.exit(1);
- }
- }
-
- public KeyStoreLoader load(File baseDir, boolean interactive) throws Exception {
- KeyStore keyStore = KeyStore.getInstance("PKCS12");
-
- File serverKeyStore = baseDir.toPath().resolve(certificateFileName).toFile();
-
- if (!serverKeyStore.exists()) {
- if (!interactive) {
- logger.info("Please re-run with the -i switch to setup the security certificate key store");
- System.exit(1);
- }
-
- logger.info("Creating keystore at {}", serverKeyStore);
- keyStore.load(null, passwordConfig.getSecurityPassword().toCharArray());
-
- logger.info("Creating self signed certiciate {}", serverKeyStore);
- KeyPair keyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
-
- String applicationUri = "urn:eclipse:milo:plc4x:server" + UUID.randomUUID();
-
- SelfSignedCertificateBuilder builder = new SelfSignedCertificateBuilder(keyPair)
- .setCommonName(applicationUri)
- .setOrganization("org.apache")
- .setOrganizationalUnit("plc4x")
- .setLocalityName("Wakefield")
- .setStateName("MA")
- .setCountryCode("US")
- .setApplicationUri(applicationUri);
-
- // Get as many hostnames and IP addresses as we can listed in the certificate.
- Set<String> hostnames = Sets.union(
- Sets.newHashSet(HostnameUtil.getHostname()),
- HostnameUtil.getHostnames("0.0.0.0", false)
- );
-
- logger.info("using IP address/hostnames {}", hostnames.toString());
-
- for (String hostname : hostnames) {
- if (IP_ADDR_PATTERN.matcher(hostname).matches()) {
- builder.addIpAddress(hostname);
- } else {
- builder.addDnsName(hostname);
- }
- }
-
- X509Certificate certificate = builder.build();
-
- keyStore.setKeyEntry(config.getName(), keyPair.getPrivate(), passwordConfig.getSecurityPassword().toCharArray(), new X509Certificate[]{certificate});
- keyStore.store(new FileOutputStream(serverKeyStore), passwordConfig.getSecurityPassword().toCharArray());
-
- logger.info("Self signed certificate created. Replace {} and update config file passwords if not using a signed certificate.", serverKeyStore);
-
- } else {
- logger.info("Loading KeyStore at {}", serverKeyStore);
- keyStore.load(new FileInputStream(serverKeyStore), passwordConfig.getSecurityPassword().toCharArray());
- }
-
- Key serverPrivateKey = keyStore.getKey(config.getName(), passwordConfig.getSecurityPassword().toCharArray());
- if (serverPrivateKey instanceof PrivateKey) {
- serverCertificate = (X509Certificate) keyStore.getCertificate(config.getName());
-
- serverCertificateChain = Arrays.stream(keyStore.getCertificateChain(config.getName()))
- .map(X509Certificate.class::cast)
- .toArray(X509Certificate[]::new);
-
- PublicKey serverPublicKey = serverCertificate.getPublicKey();
- serverKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey);
- }
-
- return this;
- }
-
- X509Certificate getServerCertificate() {
- return serverCertificate;
- }
-
- public X509Certificate[] getServerCertificateChain() {
- return serverCertificateChain;
- }
-
- KeyPair getServerKeyPair() {
- return serverKeyPair;
- }
-
-}
diff --git a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/OPCUAServer.java b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/OPCUAServer.java
index e8c66d1..2aa6bca 100644
--- a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/OPCUAServer.java
+++ b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/OPCUAServer.java
@@ -1,18 +1,27 @@
/*
- * Copyright (c) 2019 the Eclipse Milo Authors
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * SPDX-License-Identifier: EPL-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.plc4x.java.opcuaserver;
import java.io.File;
-import java.security.KeyPair;
-import java.security.Security;
+import java.io.FileInputStream;
+import java.security.*;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.LinkedHashSet;
@@ -29,6 +38,8 @@ import java.nio.file.FileSystems;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
+import org.apache.plc4x.java.opcuaserver.context.CertificateKeyPair;
+import org.apache.plc4x.java.opcuaserver.context.Encryption;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.eclipse.milo.opcua.sdk.server.OpcUaServer;
import org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig;
@@ -203,17 +214,19 @@ public class OPCUAServer {
private final OpcUaServer server;
private final Plc4xNamespace plc4xNamespace;
+ private final String certificateFileName = "plc4x-opcuaserver.pfx";
public OPCUAServer(String[] args) throws Exception {
readCommandLineArgs(args);
- KeyStoreLoader loader = new KeyStoreLoader(config, passwordConfig, cmd.hasOption("interactive"));
- DefaultCertificateManager certificateManager = new DefaultCertificateManager(
- loader.getServerKeyPair(),
- loader.getServerCertificateChain()
- );
+ File securityTempDir = new File(config.getDir(), "security");
+ if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
+ logger.error("Unable to create directory please confirm folder permissions on " + securityTempDir.toString());
+ System.exit(1);
+ }
+ logger.info("security dir: {}", securityTempDir.getAbsolutePath());
File pkiDir = FileSystems.getDefault().getPath(config.getDir()).resolve("pki").toFile();
DefaultTrustListManager trustListManager = new DefaultTrustListManager(pkiDir);
@@ -222,12 +235,6 @@ public class OPCUAServer {
DefaultServerCertificateValidator certificateValidator =
new DefaultServerCertificateValidator(trustListManager);
- KeyPair httpsKeyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
-
- SelfSignedHttpsCertificateBuilder httpsCertificateBuilder = new SelfSignedHttpsCertificateBuilder(httpsKeyPair);
- httpsCertificateBuilder.setCommonName(HostnameUtil.getHostname());
- HostnameUtil.getHostnames("0.0.0.0").forEach(httpsCertificateBuilder::addDnsName);
- X509Certificate httpsCertificate = httpsCertificateBuilder.build();
UsernameIdentityValidator identityValidator = new UsernameIdentityValidator(
true,
@@ -240,22 +247,41 @@ public class OPCUAServer {
}
);
- X509IdentityValidator x509IdentityValidator = new X509IdentityValidator(c -> true);
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+
+ File serverKeyStore = securityTempDir.toPath().resolve(certificateFileName).toFile();
- // If you need to use multiple certificates you'll have to be smarter than this.
- X509Certificate certificate = certificateManager.getCertificates()
- .stream()
- .findFirst()
- .orElseThrow(() -> new UaRuntimeException(StatusCodes.Bad_ConfigurationError, "no certificate found"));
+ X509IdentityValidator x509IdentityValidator = new X509IdentityValidator(c -> true); //Fix this
+
+ CertificateKeyPair certificate = null;
+ if (!serverKeyStore.exists()) {
+ if (!cmd.hasOption("interactive")) {
+ logger.info("Please re-run with the -i switch to setup the security certificate key store");
+ System.exit(1);
+ }
+ certificate = Encryption.generateCertificate();
+ } else {
+ logger.info("Loading KeyStore at {}", serverKeyStore);
+
+ keyStore.load(new FileInputStream(serverKeyStore), passwordConfig.getSecurityPassword().toCharArray());
+ String alias = keyStore.aliases().nextElement();
+ KeyPair kp = new KeyPair((PublicKey) keyStore.getCertificate(alias).getPublicKey(),
+ (PrivateKey) keyStore.getKey(alias, passwordConfig.getSecurityPassword().toCharArray()));
+ certificate = new CertificateKeyPair(kp,(X509Certificate) keyStore.getCertificate(alias));
+ }
- // The configured application URI must match the one in the certificate(s)
String applicationUri = CertificateUtil
- .getSanUri(certificate)
+ .getSanUri(certificate.getCertificate())
.orElseThrow(() -> new UaRuntimeException(
StatusCodes.Bad_ConfigurationError,
"certificate is missing the application URI"));
- Set<EndpointConfiguration> endpointConfigurations = createEndpointConfigurations(certificate);
+ Set<EndpointConfiguration> endpointConfigurations = createEndpointConfigurations(certificate.getCertificate());
+
+ DefaultCertificateManager certificateManager = new DefaultCertificateManager(
+ certificate.getKeyPair(),
+ certificate.getCertificate()
+ );
OpcUaServerConfig serverConfig = OpcUaServerConfig.builder()
.setApplicationUri(applicationUri)
@@ -271,8 +297,6 @@ public class OPCUAServer {
.setCertificateManager(certificateManager)
.setTrustListManager(trustListManager)
.setCertificateValidator(certificateValidator)
- .setHttpsKeyPair(httpsKeyPair)
- .setHttpsCertificate(httpsCertificate)
.setIdentityValidator(new CompositeValidator(identityValidator, x509IdentityValidator))
.setProductUri("urn:eclipse:milo:plc4x:server")
.build();
@@ -313,15 +337,13 @@ public class OPCUAServer {
.setSecurityPolicy(SecurityPolicy.None)
.setSecurityMode(MessageSecurityMode.None);
endpointConfigurations.add(buildTcpEndpoint(noSecurityBuilder));
- endpointConfigurations.add(buildHttpsEndpoint(noSecurityBuilder));
} else {
- //Always add an unsecured endpoint to localhost, this is a work around for Milo throughing an exception if it isn't here.
+ //Always add an unsecured endpoint to localhost, this is a work around for Milo throwing an exception if it isn't here.
if (hostname.equals("127.0.0.1")) {
EndpointConfiguration.Builder noSecurityBuilder = builder.copy()
.setSecurityPolicy(SecurityPolicy.None)
.setSecurityMode(MessageSecurityMode.None);
endpointConfigurations.add(buildTcpEndpoint(noSecurityBuilder));
- endpointConfigurations.add(buildHttpsEndpoint(noSecurityBuilder));
}
}
@@ -332,13 +354,6 @@ public class OPCUAServer {
.setSecurityMode(MessageSecurityMode.SignAndEncrypt))
);
- // HTTPS Basic256Sha256 / Sign (SignAndEncrypt not allowed for HTTPS)
- endpointConfigurations.add(buildHttpsEndpoint(
- builder.copy()
- .setSecurityPolicy(SecurityPolicy.Basic256Sha256)
- .setSecurityMode(MessageSecurityMode.Sign))
- );
-
EndpointConfiguration.Builder discoveryBuilder = builder.copy()
.setPath("/discovery")
.setSecurityPolicy(SecurityPolicy.None)
@@ -346,7 +361,6 @@ public class OPCUAServer {
endpointConfigurations.add(buildTcpEndpoint(discoveryBuilder));
- endpointConfigurations.add(buildHttpsEndpoint(discoveryBuilder));
}
}
@@ -360,13 +374,6 @@ public class OPCUAServer {
.build();
}
- private EndpointConfiguration buildHttpsEndpoint(EndpointConfiguration.Builder base) {
- return base.copy()
- .setTransportProfile(TransportProfile.HTTPS_UABINARY)
- .setBindPort(config.getHttpPort())
- .build();
- }
-
public OpcUaServer getServer() {
return server;
}
diff --git a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/backend/Plc4xNamespace.java b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/backend/Plc4xNamespace.java
index 5360229..654ac4b 100644
--- a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/backend/Plc4xNamespace.java
+++ b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/backend/Plc4xNamespace.java
@@ -1,11 +1,20 @@
/*
- * Copyright (c) 2019 the Eclipse Milo Authors
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * SPDX-License-Identifier: EPL-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.plc4x.java.opcuaserver.backend;
diff --git a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/context/CertificateKeyPair.java b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/context/CertificateKeyPair.java
new file mode 100644
index 0000000..0aa3a70
--- /dev/null
+++ b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/context/CertificateKeyPair.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.plc4x.java.opcuaserver.context;
+
+import java.security.KeyPair;
+import java.security.cert.X509Certificate;
+
+public class CertificateKeyPair {
+
+ private final KeyPair keyPair;
+ private final X509Certificate certificate;
+
+ public CertificateKeyPair(KeyPair keyPair, X509Certificate certificate) {
+ this.keyPair = keyPair;
+ this.certificate = certificate;
+ }
+
+ public KeyPair getKeyPair() { return keyPair; }
+
+ public X509Certificate getCertificate() { return certificate; }
+}
diff --git a/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/context/Encryption.java b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/context/Encryption.java
new file mode 100644
index 0000000..7fbc5ba
--- /dev/null
+++ b/plc4j/integrations/opcua-server/src/main/java/org/apache/plc4x/java/opcuaserver/context/Encryption.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.plc4x.java.opcuaserver.context;
+
+import org.apache.commons.lang3.RandomUtils;
+import org.bouncycastle.asn1.DERSequence;
+import org.bouncycastle.asn1.x500.X500NameBuilder;
+import org.bouncycastle.asn1.x500.style.BCStyle;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.security.*;
+import java.security.cert.X509Certificate;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+public class Encryption<PKCS10CertificateRequest> {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Encryption.class);
+ private static final String APPURI = "urn:eclipse:milo:plc4x:server";
+
+ public static CertificateKeyPair generateCertificate() {
+ KeyPairGenerator kpg = null;
+ try {
+ kpg = KeyPairGenerator.getInstance("RSA");
+ } catch (NoSuchAlgorithmException e) {
+ LOGGER.error("Security Algorithim is unsupported for certificate");
+ }
+ kpg.initialize(2048);
+ KeyPair caKeys = kpg.generateKeyPair();
+ KeyPair userKeys = kpg.generateKeyPair();
+
+ X500NameBuilder nameBuilder = new X500NameBuilder();
+
+ nameBuilder.addRDN(BCStyle.CN, "Apache PLC4X Driver Client");
+ nameBuilder.addRDN(BCStyle.O, "Apache Software Foundation");
+ nameBuilder.addRDN(BCStyle.OU, "dev");
+ nameBuilder.addRDN(BCStyle.L, "");
+ nameBuilder.addRDN(BCStyle.ST, "DE");
+ nameBuilder.addRDN(BCStyle.C, "US");
+
+ BigInteger serial = new BigInteger(RandomUtils.nextBytes(40));
+
+ final Calendar calender = Calendar.getInstance();
+ calender.add(Calendar.DATE, -1);
+ Date startDate = calender.getTime();
+ calender.add(Calendar.DATE, 365*25);
+ Date expiryDate = calender.getTime();
+
+ KeyPairGenerator generator = null;
+ try {
+ generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048, new SecureRandom());
+ KeyPair keyPair = generator.generateKeyPair();
+
+ SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
+ keyPair.getPublic().getEncoded()
+ );
+
+ X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
+ nameBuilder.build(),
+ serial,
+ startDate,
+ expiryDate,
+ Locale.ENGLISH,
+ nameBuilder.build(),
+ subjectPublicKeyInfo
+ );
+
+ GeneralName[] gnArray = new GeneralName[] {new GeneralName(GeneralName.dNSName, InetAddress.getLocalHost().getHostName()), new GeneralName(GeneralName.uniformResourceIdentifier, APPURI)};
+
+
+ GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(gnArray));
+ certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
+
+ ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(keyPair.getPrivate());
+
+ X509CertificateHolder certificateHolder = certificateBuilder.build(sigGen);
+
+ JcaX509CertificateConverter certificateConvertor = new JcaX509CertificateConverter();
+ certificateConvertor.setProvider(new BouncyCastleProvider());
+
+ CertificateKeyPair ckp = new CertificateKeyPair(keyPair, certificateConvertor.getCertificate(certificateHolder));
+
+ return ckp;
+
+ } catch (Exception e) {
+ LOGGER.error("Security Algorithim is unsupported for certificate");
+ return null;
+ }
+ }
+}