Skip to main content

Certificate Generation and Configuration

Prerequisite Reading

Generate Client PFX​

CertificateManager is public static class, it does only one thing: "self-signing + caching." Actual members:

public static class CertificateManager
{
public const string SubjectName = "CN=DarraOpcUaClient, O=Darra, C=CN";
public const string ApplicationUri = "urn:darra:opcua:client"; // Write to SAN , URI cannot be modified
public const int ValidYears = 5;
public const int KeySizeBits = 2048;

public static string CacheDir { get; } // %AppData%/Darra/OpcUa/pki
public static string PfxPath { get; } // <CacheDir>/client.pfx

public static (string pfxPath, string password) EnsureClientCertificate();
public static (string pfxPath, string password) ForceRegenerate();
public static string DescribeCachedCertificate();
}
using DarraOpcUa_Client;

// If it already exists, return it directly; if it does not exist, generate it with a self-signed certificate; return the path PFX and password.
var (pfxPath, password) = CertificateManager.EnsureClientCertificate();

// When a new certificate is needed, force a self-signing renewal
var (newPfxPath, newPassword) = CertificateManager.ForceRegenerate();

// Cache Location / Certificate Information
Console.WriteLine(CertificateManager.CacheDir);
Console.WriteLine(CertificateManager.DescribeCachedCertificate());

The return value is the client's PFX path and password; pass these two values directly when creating the session.

EnsureClientCertificate() Caching rules (read through them once to understand when the certificate will be renewed):

SituationBehavior
<CacheDir>/client.pfx Already exists and can be loadedReuse it directly, and return it along with the saved password
The cache certificate is valid for less than 7 days.Reissue a new one
Cache Certificate Corrupted / Failed to LoadDelete and Rebuild (Including Password Files)
Cache entry does not existAutomatically Generated Signature

So it will not wait until the certificate's expiry day to rotate, and it will not silently swap out a certificate that still has 5 years of validity left — Replacement should only occur when the certificate is about to expire or the file is corrupted. After replacement, Subject / SAN / ApplicationUri remain unchanged; the only changes are to the key pair and thumbprint. The old entry in the server’s trust store must .der be reimported.

The password is random; do not hard-code

EnsureClientCertificate() it. The return value is passwordRandom Strong Passwords(32 bytes → base64), not a fixed value. It is stored in encrypted form <CacheDir>/client.pfx.pwd(on Windows, it is encrypted DPAPI using the LocalMachine scope). When constructing the Session clientKeyPath, you must pass the returned value to password; hard-coding the value "123456" will cause the load to fail.

The attributes of self-signed certificates are fixed, as shown in the table below:

PropertiesValue
SubjectCN=DarraOpcUaClient, O=Darra, C=CN
SAN URIurn:darra:opcua:client
SAN DNSlocalhost + This computer's name
SAN IP127.0.0.1
KeyUsageDigitalSignature / KeyEncipherment / NonRepudiation / DataEncipherment
ExtendedKeyUsage1.3.6.1.5.5.7.3.2 (clientAuth)
BasicConstraintsCA = false
KeyRSA 2048 / SHA256
Validity PeriodYesterday → 5 years from now

Use OpenSSL (as a substitute)​

When OpenSSL creating a certificate for personal use, The "Subject" field SAN URI must match the text in the table above word for word., otherwise the server's validation CreateSession ClientDescription.ApplicationUri will not SAN URI match the certificate, and the request will be rejected outright:

openssl req -newkey rsa:2048 -keyout key.pem -out cert.pem -days 1825 -nodes \
-subj "/CN=DarraOpcUaClient/O=Darra/C=CN" \
-addext "subjectAltName=URI:urn:darra:opcua:client,DNS:localhost" \
-addext "keyUsage=digitalSignature,keyEncipherment,nonRepudiation,dataEncipherment" \
-addext "extendedKeyUsage=clientAuth" \
-addext "basicConstraints=critical,CA:false"

openssl pkcs12 -export -out client.pfx -inkey key.pem -in cert.pem -password pass:123456

-addext "subjectAltName=URI:..." The one in there URIIt can only be urn:darra:opcua:client — Client ApplicationUri This is a fixed constant; it is not a customizable identifier.

Importing Trust on the Server Side​

Copy the client's public key (.der or .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)
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.

Darra Software PLC Server By default auto_accept_untrusted = false, no client certificates are automatically trusted: Client certificates not in the trust directory will be discarded %ProgramData%\Darra\PKI\rejected\certs\, and the connection will be rejected. .der Copy the certificates to the trust directory and restart trusted\certs\ the service for the changes to take effect.

Passed when the client is constructed PFX​

using DarraOpcUa_Client;

var (pfxPath, password) = CertificateManager.EnsureClientCertificate();

using var ua = new DarraOpcUa(
endpointUrl: "opc.tcp://server:4840",
securityMode: MessageSecurityMode.SignAndEncrypt,
clientCertPath: pfxPath,
clientKeyPath: password); // This is where you enter the PFX password, not the path to the private key file.
ua.Connect();

Server Certificate: Not provided = Auto-discovery; not "chain of trust verification"​

When serverCertPath is left blank, the connection is made in two steps:

  1. First, open a channel to send None the data GetEndpoints. Click "SecurityMode + Match SecurityPolicyUri All" to select the server certificate, then save it toMemory;
  2. Close the channel None and reopen the encrypted channel using this certificate.

Key Points:

  • This certificate lives only in process memory: nothing is written to disk, no fingerprint is stored, and the next connection performs no comparison;
  • When reconnecting after a connection loss within the same process, the certificate in this memory is reused, so the connection is not re-established;
  • GetEndpoints If there is no matching certificate (SecurityMode, SecurityPolicyUri), the connection fails immediately, and the following is returned BadCertificateInvalid:;
  • The client uses this certificate only for channel encryption, decryption and signature verification, and does not build a certificate chain, validate the host name, or check the validity period, Trust store query. The trustworthiness of a server certificate depends entirely on whether the server recognizes your client certificate.
None TOFU

SDK The SDK has no TOFU mechanism — "save the fingerprint after the first trust, verify it later, reject on mismatch". It doesn't mean just serverCertPath "automatically GetEndpoints retrieving certificates," Does not constitute a man-in-the-middle attack. To fix the server's identity, you must hard-code the server certificate yourself and pass it explicitly; see the next section.

When explicitly specifying a server certificate, the following is passed: PFX (PKCS#12) File Path, Not DER — Press PFX to load, andImport with an empty password:

serverCertPath: @"C:\certs\server.pfx"
  • Load using an empty password; attempts with a password PFX will fail.
  • A loading failure will not result in an error message. —— Log only one "Warn" message, then automatically return to the GetEndpoints auto-discovery process described above. Therefore, passing it does not serverCertPath mean that "the server's identity has been verified": it does not SDK provide any indication of whether "the server certificate was loaded successfully." I want to confirm that, for this query interface, I can only PFX test-load X509Certificate2 it myself using before making the call.

Troubleshooting​

The StatusCode enumeration only registers part of the OPC UA standard codes. In the table below, only those marked with ✅ in the "Enumeration" column can be used in comparisons StatusCode.Xxx; those marked with ✗ are standard codes that the server may return. In C# enumerations,That name isn't listed, can only be compared by value or displayed VersionInfo.StatusName() using.

Exception Type:

public sealed class OpcUaException : Exception
{
public StatusCode StatusCode { get; }
public OpcUaException(string message, StatusCode code);
}

ex.Message It's already included at the end 0x{code:X8} {StatusName}; just check the log to see which code it is.

StatusCodeWithin the enumerationReasonResolve
BadCertificateUntrusted✗ (0x801A0000)The server does not trust the client.Import the client's public key into the server's trusted/certs/ directory.
BadCertificateInvalid✅ (0x80120000)Certificate expired / not yet valid / failed to load PFXRegenerate
BadCertificateUriInvalid✗ (0x80170000)Certificate SAN.URI Does Not ApplicationUri MatchTo regenerate the client certificate, it must SAN URI be urn:darra:opcua:client
BadCertificateHostNameInvalid✗ (0x80160000)The SAN.DNS certificate does not match the connected host.Connect using the hostname already specified in the certificate
BadSecurityChecksFailed✅ (0x80130000)General security validation failedCheck the server logs to determine the specific cause.
BadSecurityModeRejected✅ (0x80540000)The server does not support this SecurityModeGetEndpoints Check which ones the server actually supports
BadSecurityPolicyRejected✅ (0x80550000)The server does not support Basic256Sha256.Enable this policy in the server configuration
using DarraOpcUa_Client;

try { ua.Connect(); }
catch (OpcUaException ex)
{
// Within an enumeration: Direct comparison is possible
if (ex.StatusCode == StatusCode.BadSecurityChecksFailed) { /* ... */ }

// Outside enumerations (BadCertificateUntrusted etc.): Compare by value; the name is already included in the Message
if ((uint)ex.StatusCode == 0x801A0000u) { /* The server does not trust the client */ }

Console.WriteLine(ex.Message); // "...: 0x801A0000 BadCertificateUntrusted"
}

SAN URI Importance​

In OPC UA, the "Verify Client Certificate" SAN section must include the URI: field, and it must match ApplicationUri character for character. The client's ApplicationUri is a fixed constant:

ValueWhat is it used for?
urn:darra:opcua:clientClient Certificate SAN URI (CertificateManager.ApplicationUri)
urn:darra:opcua:clientSent to the server when establishing a connection ClientDescription.ApplicationUri

Two fields share the same value and cannot be changed to the company's name.SAN URI If they don't match → the server returns BadCertificateUriInvalid / BadSecurityChecksFailed, and the connection cannot be established.

View the currently cached certificate:

// Returns "Subject=...; Thumbprint=...; NotBefore=...; NotAfter=...; HasPrivateKey=..."
Console.WriteLine(CertificateManager.DescribeCachedCertificate());

DescribeCachedCertificate() Does not return a value SAN URI, nor does it have any other view SAN interfaces—please verify. SANPlease read the extension yourself X509Certificate2, or use the self-signed CertificateManager version directly (it is guaranteed to be correct).

Time Synchronization (NTP)​

The SDK performs no client-side clock-skew validation: there is no "reject when the skew exceeds N minutes" rule, and timestamps are not compared to the local clock. This constraint does not exist in C# SDK.

Time synchronization is still worth doing for two other reasons:

  • Certificate validity checks (NotBefore / NotAfter) are done by the server; if the local clock is badly off you may hit a premature-expiry error;
  • Historical values and event timestamps are provided by the server; if the local clock is inaccurate, it can cause the timeline on the trend chart to be misaligned.
w32tm /resync

Next Step​