Qt OPC UA X.509 支持
介绍如何生成密钥和证书签名请求。
本示例演示了客户端应用程序如何生成自己的自签名证书或生成证书签名请求。
生成 RSA 密钥
首先,生成一个 RSA 密钥:
QOpcUaKeyPair key;
key.generateRsaKey(QOpcUaKeyPair::RsaKeyStrength::Bits2048);私钥可保存到文件中以备后续使用:
QByteArray keyData = key.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Unencrypted, QString());
QFile keyFile(u"privateKey.pem"_s);
if (!keyFile.open(QFile::WriteOnly))
return EXIT_FAILURE;
keyFile.write(keyData);
keyFile.close();生成证书签名请求
接下来,创建一个证书签名请求。同时还需要设置证书的主体,并添加 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);现在有两种选择:
1. 若需由证书颁发机构(CA)对证书签名请求进行签名,则必须使用该请求数据。
QByteArray certificateSigningRequestData = csr.createRequest(key);2. 如果没有证书颁发机构,则必须对请求进行自签名。
QByteArray selfSignedCertificateData = csr.createSelfSignedCertificate(key);© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.