在本页

创建支持安全功能的 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 Viewer 示例中的代码:

    voidMainWindow::setupPkiConfiguration() {constQDirpkidir=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.setPrivateKeyFile(pkidir.absoluteFilePath("own/private/opcuaviewer.pem"));m_pkiConfig.setTrustListDirectory(pkidir.absoluteFilePath("trusted/certs"));m_pkiConfig.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"));constQStringListtoCreate={ 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 Viewer 示例

客户端接受服务器证书后,可以尝试再次连接。现在,服务器可能会拒绝客户端的证书。通用错误代码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.