Qt OPC UA X509 Support

Shows how to generate keys and certificate signing requests.

This example shows how client applications can generate their own self-signed certificate or generate a certificate signing request.

Generating RSA key

At first, an RSA key is generated:

 QOpcUaKeyPair key;
 key.generateRsaKey(QOpcUaKeyPair::RsaKeyStrength::Bits2048);

The private key can be saved to a file for further usage:

 QByteArray keyData = key.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Unencrypted, QString());

 QFile keyFile(u"privateKey.pem"_s);
 keyFile.open(QFile::WriteOnly);
 keyFile.write(keyData);
 keyFile.close();

Generating certificate signing requests

Next, a certificate signing request is created. It is also necessary to set the subject of the certificate and add all the extensions needed for OPC UA.

 QOpcUaX509CertificateSigningRequest csr;

 // Set the subject of the certificate
 QOpcUaX509DistinguishedName dn;
 dn.setEntry(QOpcUaX509DistinguishedName::Type::CommonName, u"QtOpcUaViewer"_s);
 dn.setEntry(QOpcUaX509DistinguishedName::Type::CountryName, u"DE"_s);
 dn.setEntry(QOpcUaX509DistinguishedName::Type::LocalityName, u"Berlin"_s);
 dn.setEntry(QOpcUaX509DistinguishedName::Type::StateOrProvinceName, u"Berlin"_s);
 dn.setEntry(QOpcUaX509DistinguishedName::Type::OrganizationName, u"The Qt Company"_s);
 csr.setSubject(dn);

Now there are two options:

1. When you need to get your certificate signing request signed by a certificate authority, you have to use the request data.

 QByteArray certificateSigningRequestData = csr.createRequest(key);

2. When there is no certificate authority, you have to self-sign the request.

 QByteArray selfSignedCertificateData = csr.createSelfSignedCertificate(key);

Files: