Security 加密
本节是 SDK 加密相关 API 与证书工具.
子页跳转
- 生成证书 / 服务端互信配置 / 故障排查请参考 证书生成与配置.
- Session 构造时如何传安全参数请参考 构造函数.
- 服务端支持的安全模式探测请参考 GetEndpoints.
三种 SecurityMode
enum class MessageSecurityMode : int {
Invalid = 0,
None = 1,
Sign = 2,
SignAndEncrypt = 3
};
构造 Session 时传:
#include <darra/opcua/client.hpp>
ConnectionConfig cfg;
cfg.endpoint_url = "opc.tcp://server:4840";
cfg.security_mode = MessageSecurityMode::SignAndEncrypt;
cfg.client_cert_path = "C:/certs/client.pfx"; // 客户端 PFX, 内含私钥
cfg.client_key_path = "123456"; // 该 PFX 的密码 (字段名是历史遗留, 不是私钥路径)
Session s(cfg);
client_key_path 不是私钥路径client_key_path 装的是 client_cert_path 那个 PFX 的密码。私钥已经打在 PFX 里, 不用也不能另给一个私钥文件。PFX 无密码就留空串。
| Mode | 数据完整性 | 机密性 | 适用 |
|---|---|---|---|
| None | × | × | 开发期 / 内网 / 调试 |
| Sign | ✓ | × | 防篡改, 不防嗅探 |
| SignAndEncrypt | ✓ | ✓ | 生产推荐 |
Sign / SignAndEncrypt 必须给 client_cert_path, 否则 Connect() 直接失败。
SecurityPolicyUri
当前实现只支持两条:
http://opcfoundation.org/UA/SecurityPolicy#Nonehttp://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256(主用)
security_policy_uri 留空时按 security_mode 自动选 (None → #None, 其他 → #Basic256Sha256); 显式填了就用你填的。
UserToken
enum class UserTokenType : int {
Anonymous = 0,
Username = 1,
Certificate = 2,
Issued = 3
};
通过 ConnectionConfig 选择:
| Token | 字段 | 实现状态 |
|---|---|---|
| Anonymous | 不设 username (默认) | 可用 |
| Username | username = "...", password = "..." | 可用 |
| Certificate | — | 暂未实现 |
| Issued | — | 暂未实现 |
username 优先
只要 username 非空, Session 构造就强制用 Username 令牌, user_token_type 字段被忽略。
证书生成 (OpenSSL)
C++ SDK 当前不内置证书工具, 推荐用 OpenSSL 生成 PFX, 详细见 证书生成与配置.
简化命令:
openssl req -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes \
-subj "/CN=MyClient/O=Darra/C=CN" \
-addext "subjectAltName=URI:urn:darra:opcua:client"
openssl pkcs12 -export -out client.pfx -inkey key.pem -in cert.pem -password pass:123456
SAN URI 必须是
urn:darra:opcua:client客户端上报的 ApplicationUri 是写死常量 urn:darra:opcua:client, 不读配置、不可改。证书 SAN 的 URI 项必须逐字写成这个值, 自己编一个 (例如 urn:my-company:my-client) 会让服务端判定 BadCertificateUriInvalid, 加密通道建不起来。