创建支持安全功能的 OPC UA 客户端
OPC UA 的核心功能之一是支持安全性,这意味着我们能够获得经过加密和数字签名的协议,以及用户身份验证和授权支持。
为了使这些功能正常工作,每个应用程序实例(程序的安装)都需要拥有自己的Application Instance Certificate 以及相应的私钥。
应用程序可以自行生成自签名证书(参见Qt OPC UA X509 支持),也可以通过 OPC UA GDS 从证书颁发机构获取证书,或者直接配置用户手动创建的证书。
配置 UA 应用程序
为了使客户端能够使用安全连接,必须
- 配置正确的应用程序标识
m_identity = m_pkiConfig.applicationIdentity(); - 配置 PKI 位置,以便 SDK 能够找到证书、私钥、信任列表等。
例如,请参阅“Qt OPC UA ”查看器示例中的代码:
voidMainWindow::setupPkiConfiguration() { constQDir pkidir= QDir(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)+ "/pki"); if(!pkidir.exists()&& !copyDirRecursively(":/pki",pkidir.path())) qFatal("Could not set up directory %s!", qUtf8Printable(pkidir.path())); m_pkiConfig.setClientCertificateFile(pkidir.absoluteFilePath("own/certs/opcuaviewer.der")); m_pkiConfig.setPrivateKeyFile(pkidir.absoluteFilePath("own/private/opcuaviewer.pem")); m_pkiConfig.setTrustListDirectory(pkidir.absoluteFilePath("trusted/certs")); m_pkiConfig.setRevocationListDirectory(pkidir.absoluteFilePath("trusted/crl")); m_pkiConfig.setIssuerListDirectory(pkidir.absoluteFilePath("issuers/certs")); m_pkiConfig.setIssuerRevocationListDirectory(pkidir.absoluteFilePath("issuers/crl")); constQStringList toCreate={ m_pkiConfig.issuerListDirectory(), m_pkiConfig.issuerRevocationListDirectory() }; for(constQString&dir: toCreate) { if(!QDir().mkpath(dir)) qFatal("Could not create directory %s!", qUtf8Printable(dir)); } }在此示例中,我们将预配置的自有证书和受信任证书从 Qt 资源系统中提取到文件系统中的可写位置。其余用于存储签发者(撤销)列表的目录需手动创建。
首次连接
首次连接时,客户端需要信任服务器证书。
客户端应显示证书警告(包含证书详细信息),并提供将证书保存到其受信任列表中的选项。示例请参见Qt OPC UA 查看器示例。
当客户端接受服务器证书后,您可以尝试再次连接。此时,服务器可能会拒绝客户端的证书。这将通过通用错误代码BadSecurityChecksFailed 表示。服务器通常会将被拒绝的证书存储在专门的rejected 文件夹中。管理员可将这些证书移至信任列表中以信任客户端。这样可以避免手动将客户端证书复制到服务器上。
一旦服务器信任了客户端,您就应该能够安全地建立连接。
© 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.