Skip to main content

Certificate Generation and Configuration

Prerequisite Reading

Generate Client PFX​

# 1. Generate a private key + self-signed certificate (PEM)
openssl req -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes \
-subj "/CN=MyClient/O=Darra/C=CN" \
-addext "subjectAltName=URI:urn:darra:opcua:client"

# 2. Forward PFX (PKCS#12, containing private key + public key + certificate chain)
openssl pkcs12 -export -out client.pfx -inkey key.pem -in cert.pem \
-password pass:123456

# 3. Export the public key in the specified DER format (for the server to import and trust)
openssl x509 -in cert.pem -outform DER -out client.der

Use keytool (JDK included)​

keytool -genkeypair -alias darra-client \
-keyalg RSA -keysize 2048 -validity 365 \
-dname "CN=MyClient, O=Darra, C=CN" \
-ext "san=uri:urn:darra:opcua:client" \
-keystore client.pfx -storetype PKCS12 \
-storepass 123456 -keypass 123456
SAN URI Only one fixed value can be entered.

The sent CreateSession by the client in is ApplicationUriHard-Coded Constants urn:darra:opcua:client, There is no field to change it. Therefore, the certificate's SAN URI: can only be set to this one value; if you create your own, the server will URI reject it as "SAN URI inconsistent ApplicationUri with ."

Importing Trust on the Server Side​

Copy the client's public key (client.der or client.pem) to the server's "Trusted Client Certificates" directory:

ServerPath
Darra Software PLC Server%ProgramData%\Darra\PKI\trusted\certs\ (Configuration option trust_list_dir; this is the default value; copy it and restart the service for the changes to take effect)
The customer's current serverImported by the remote operations team; the path is in the format <server>/pki/trusted/certs/ or uploaded to the management console.

By default auto_accept_untrusted = false, the Darra server does not automatically trust new client certificates; certificates not in the trusted directory are discarded %ProgramData%\Darra\PKI\rejected\certs\.

Passed when the client is constructed PFX​

import com.darra.opcua.*;

try (OpcUaSession ua = OpcUaSession.secureSignAndEncrypt(
"opc.tcp://server:4840", "C:\\certs\\client.pfx")) {
ua.connect();
}

Complete Structure​

try (OpcUaSession ua = new OpcUaSession(
"opc.tcp://server:4840",
Enums.MessageSecurityMode.SignAndEncrypt,
/* user */ null, /* password */ null,
/* sessionTimeoutMs */ 600_000,
/* requestTimeoutMs */ 10_000,
/* connectTimeoutMs */ 10_000,
/* keepAliveIntervalMs */ 10_000,
/* autoReconnect */ true,
/* autoPublishOnConnect */ true,
/* clientCertPath */ "C:\\certs\\client.pfx",
/* clientKeyPath */ null, // PFX Passphrase (the field name is a historical remnant; this is not the private key path!); Self-signed: PFX Pass null if no passphrase is required
/* serverCertPath */ null, // Optional: Server certificate PFX path (password-less); if not provided, it defaults to None→Secure and is automatically upgraded
/* securityPolicyUri */ null // null = Auto Basic256Sha256
)) {
ua.connect();
}

Server Certificate (Optional)​

serverCertPath This is an optional parameter: Use it to specify a server certificate to establish a fixed identity; if not provided (None), it defaults to Secure and automatically upgrades.

It must be PFX(PKCS#12) and passwordless; it must not be DER

The protocol stack loads the server certificate via DarraUa_Sec_LoadPfx(path, NULL) — the password is always set to NULL, so this one PFX No password is allowed.. Transmission .der / .pem MeetingLoading will inevitably fail。

new OpcUaSession(endpoint, mode, user, pwd,
600_000, 10_000, 10_000, 10_000, true, true,
"client.pfx", null,
"C:\\certs\\server.pfx", // serverCertPath Explicitly specify (PFX, no password)
null);
If loading fails, it will silently fall back without reporting an error.

When loading PFX the preset fails, SDKPrint only one WARN message (Server cert PFX load failed, will discover via None channel) It automatically reverts to None→Secure. Note that no exception is thrown, and there is no API to verify which certificate was ultimately used. If you submit an invalid format, please check the logs to see if this WARN message appears.

No TOFU, do not save fingerprints

Behavior when it is not passed: open a channel with SecurityMode=None (plaintext) → GetEndpoints to fetch the server's self-reported certificate → close the channel and reconnect → open the encrypted channel again. The SDK does not write to disk, does not store fingerprints, and does not compare across connections — there is no TOFU implementation at all. So "not passing it = the man-in-the-middle attack is already prevented" is wrong; to pin "only this one server is accepted" you must pass serverCertPath explicitly.

Troubleshooting​

The first column of the table below isOPC UA Standard code name returned by the server, Not all of them can be directly copied as Java constants: Enums.StatusCode only 4 of them are registered; the rest are written this way Enums.StatusCode.BadCertificateUntrusted, which won't compile. At runtime, use to retrieve the source code OpcUaException.rawCode, use to look up registered enumerations Enums.StatusCode.fromCode(int), and use to get the human-readable name for any code OpcUaStack.statusName(int).

OPC UA Standard code returned by the serverHow do I retrieve it in [...] SDK,ReasonResolve
BadCertificateUntrustedNot registered in Enums.StatusCode; OpcUaStack.statusName(ex.rawCode)The server does not trust the client.Copy client.der to the server's trusted/certs/ directory.
BadCertificateInvalidEnums.StatusCode.BadCertificateInvalidCertificate has expired / is not yet validRegenerate
BadCertificateUriInvalidNot registered in Enums.StatusCode; OpcUaStack.statusName(ex.rawCode)Certificate SAN.URI Does Not ApplicationUri MatchEnsure consistency applicationUri when regenerating
BadCertificateHostNameInvalidNot registered in Enums.StatusCode; OpcUaStack.statusName(ex.rawCode)The SAN.DNS certificate does not match the connected host.When generating, add subjectAltName=DNS:server.example.com
BadSecurityChecksFailedEnums.StatusCode.BadSecurityChecksFailedGeneral security validation failedCheck the server logs to determine the specific cause.
BadSecurityModeRejectedEnums.StatusCode.BadSecurityModeRejectedThe server does not support this SecurityModeOpcUaDiscovery.getEndpoints See which services the server actually supports
BadSecurityPolicyRejectedEnums.StatusCode.BadSecurityPolicyRejectedThe server does not support Basic256Sha256.Enable this policy in the server configuration

SAN URI Importance​

In OPC UA, the "Verify Client Certificate" SAN section must contain the URI: field and its value must match the ApplicationUri. This is the key defence against forgery and must be configured correctly. This SDK's ApplicationUri is the hard-coded constant urn:darra:opcua:client, so the SAN can only be that value.

Verify OpenSSL using PFX:

# View the contents of the certificate
openssl pkcs12 -in client.pfx -nokeys -password pass:123456 | openssl x509 -text

# You should be able to see:
# X509v3 Subject Alternative Name:
# URI:urn:darra:opcua:client

Or use keytool:

keytool -list -v -keystore client.pfx -storepass 123456

Time Synchronization (NTP)​

This does not SDK perform timestamp / clock offset verification.

Do not expect to be " SDK stopped" if there is an offset. Status codes BadCertificateTimeInvalid (0x80140000) / BadInvalidTimestamp (0x80230000) This SDK Will not return, so there is no threshold to set for "rejecting entries if the deviation exceeds a certain number of minutes.BadCertificateTimeInvalid " SinceServer-side It determines the certificate's validity period based on its own system clock. So you should NTP still do what you normally do, but that's to ensure the server verifies that the certificate hasn't expired—it's not meant SDK to block anything.

w32tm /resync

Complete Example — Using to Automatically GetEndpoints Select an Encrypted Endpoint​

import com.darra.opcua.*;
import java.util.List;

public class SecureConnectDemo {
public static void main(String[] args) {
// 1. Discovery
List<EndpointDescription> eps =
OpcUaDiscovery.getEndpoints("opc.tcp://server:4840");

// 2. Select SignAndEncrypt + Basic256Sha256
EndpointDescription pick = eps.stream()
.filter(ep -> ep.getSecurityMode() == Enums.MessageSecurityMode.SignAndEncrypt
&& ep.getSecurityPolicyUri() != null
&& ep.getSecurityPolicyUri().endsWith("#Basic256Sha256"))
.findFirst()
.orElse(null);

if (pick == null) {
System.err.println("No suitable encrypted endpoint");
return;
}

// 3. Encrypted Connection
try (OpcUaSession ua = OpcUaSession.secureSignAndEncrypt(
pick.getEndpointUrl(), "C:\\certs\\client.pfx")) {
ua.connect();
System.out.println("Connected with " + ua.getSecurityMode());
} catch (OpcUaException ex) {
System.err.println("Secure connect failed: " + ex.statusCode);
}
}
}

Next Step​