一、kepserver增加密码与用户名
进入kepserver的设置选择用户管理器:
右击Server Users 选择添加用户设置用户名跟密码:
至此完成服务端的用户名与密码配置。
二、open62541客户端配置
1、open62541的编译
open62541提供OpenSSL加密通信,在对源码编译时需要开启对应功能可通过cmake..实现:
cmake -DUA_ENABLE_AMALGAMATION=ON -DUA_ENABLE_ENCRYPTION=ON ..
编译过程中缺少mbedtls库文件可以下指令安装:
sudo apt-get install libmbedtls-dev
编译:
make
2、生成证书与密钥
通过python3运行脚本文件:
python3 create_self-signed.py ./
3.open62541接口函数修改
三、客户端对应源码
1、初始化
UA_Client* client = nullptr;
// 加载client的证书和私匙
UA_ByteString certificate = LoadFile("server_cert.der");
UA_ByteString privateKey = LoadFile("server_key.der");
size_t trustListSize = 0;
UA_STACKARRAY(UA_ByteString, trustList, trustListSize);
UA_ByteString *revocationList = NULL;
size_t revocationListSize = 0;
client = UA_Client_new();
UA_ClientConfig *config = UA_Client_getConfig(client);
// openssl加密通信配置
UA_ClientConfig_setDefaultEncryption(config, certificate, privateKey, trustList,
trustListSize, revocationList, revocationListSize);
UA_ByteString_clear(&certificate);
UA_ByteString_clear(&privateKey);
LoadFile函数如下:
UA_ByteString LoadFile(const char *const path) {
UA_ByteString fileContents = UA_STRING_NULL;
/* Open the file */
FILE *fp = fopen(path, "rb");
if(!fp) {
exit(0);
// return fileContents;
}
/* Get the file length, allocate the data and read */
fseek(fp, 0, SEEK_END);
fileContents.length = (size_t)ftell(fp);
fileContents.data = (UA_Byte *)UA_malloc(fileContents.length * sizeof(UA_Byte));
if(fileContents.data) {
fseek(fp, 0, SEEK_SET);
size_t read = fread(fileContents.data, sizeof(UA_Byte), fileContents.length, fp);
if(read != fileContents.length){
UA_ByteString_clear(&fileContents);
}
}
else {
fileContents.length = 0;
}
fclose(fp);
return fileContents;
}
2、客户端连接
bool OpcConnect() {
UA_StatusCode retval;
retval = UA_Client_connect_username(client, ip.c_str(), username.c_str(), password.c_str());
if (retval != UA_STATUSCODE_GOOD) {
UA_Client_delete(client);
std::cout << "Connect Opc Server Failed!!!!" << std::endl ;
return false;
}
return true;
}
未打印报错及连接成功。