我在使用自签名证书连接到 mqtt 服务器时遇到问题。我想将我的 mkr1000 安全地连接到我在 ubuntu 上的 mosquitto MQTT 服务器。我正在使用 ARDUINOECCX08CSR 示例在 mkr1000 上生成 CSR,并使用 ubuntu 的 CA 文件创建证书(.crt)。下面我将提到为我的项目生成 CA、CSR 和 CRT 文件的过程。
程序一
Ubuntu机器步骤
在 ubuntu 中生成证书颁发机构证书和密钥
openssl req -new -x509 -days 3650 -extensions v3_ca -keyout ca.key -out ca.crt
#### passphrase: abcd
在这里,我得到了 ca.key 和 ca.crt,其中我使用了通用名称中的“Ubuntu IP”
服务器:生成服务器密钥。
openssl genrsa -des3 -out server.key 2048
#passphrase :abcd
#I tried both ways with and without -des3
生成不加密的服务器密钥。
openssl genrsa -out server.key 2048
生成证书签名请求以发送到 CA。
openssl req -out server.csr -key server.key -new
在这里,我再次使用通用名称中的“Ubuntu IP”,并使用了我的订阅者 IP(原因,我没有域名)
将 CSR 发送给 CA,或使用您的 CA 密钥对其进行签名:
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
客户端/设备/MKR1000/ 生成 csr
: CSR generated by mkr1000(procedure given below)
如上所述,我们正在使用 mkr1000 设备将传感器数据发送到 mosquitto 代理。我正在使用的库是:
#include <PubSubClient.h>
#include <WiFi101.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "arduino_secrets.h"
#define ONE_WIRE_BUS 2
#For connecting to secure mqtt broker at port no 8883, we are generating ECCX08CSR example from #ArduinoECCX08 library for ECC508 & ECC608 crypto chips, examples in Arduino IDE.##
#Burned code example ECCX08CSR in mkr1000 board
#On serial monitor we filled the attributes
#“”””’Serial Monitor”””””””’
ECCX08 Serial Number = 012322619525B27AAF
#Hi there, in order to generate a new CSR for your board, we'll need the following information ...
Country Name (2 letter code) []:
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) [012322619525B27AAF]: 54.196.102.5########
#########54.196.102.5 is used as a common name
What slot would you like to use? (0 - 4) [0]: 0
Would you like to generate a new private key? (Y/n) [Y]: y
Here's your CSR, enjoy!
-----BEGIN CERTIFICATE REQUEST-----
MIHKMHICAQAwEDEOMAwGA1UEAxMFbXlta3IwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARo6lo/
SW6XJ3vWTptpq+xRfiGtVXlfx0H7PRfZqrQCEA6NCkD+DZUQA5hNekMPzveohJscta5PYqAwCQet
TxxhoAAwCgYIKoZIzj0EAwIDSAAwRQIgQbwP9SF10O1dVyXsrNhr/HIEP/o2YzRyN7aqeSYaSvQC
IQCaH6+svv9/oV9bfqePi67PrcDLX+PGkAXlTlZlwJD5ZA==
-----END CERTIFICATE REQUEST-----
“””””””“
在此之后,复制 CSR 并将其存储在 .txt 格式的文件中。该文件被提供给 CA 用于为 mkr1000 生成证书。
我再次使用公共名称中的 ubuntu IP,复制 client.csr 内容并将其粘贴到 UBUNTU 中具有相同名称 client.csr 的新文件中,我在其中运行以下命令以获取 client.crt
将 CSR 发送给 CA,或使用您的 CA 密钥对其进行签名:
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365
如果我将此 UBUNTU 生成的 client.crt 文件与 AWS IoT 生成的 CRT 文件进行比较,我发现 X509 内容丢失。为了添加X509 内容,我遵循了另一个我也尝试过的过程,但我仍然不明白为什么 MKR1000 在使用自签名 ssl 时没有与 Ubuntu 连接。即使当我没有使用 SSL 概念时它也能正常工作以下是我在 Ubuntu 终端中运行的 mosquitto 子命令
mosquitto_sub -h “UBUNTU IP” -t “Home” --cafile /home/ubuntu/client.crt -p 8333
获得 CA 生成并签名的 .crt 文件后,我们复制文件内容并将其粘贴到 const char SECRET_CERTIFICATE[] 变量中,如下所示
//////////////////////
const char SECRET_CERTIFICATE[] = R"(-----BEGIN CERTIFICATE-----
MIICZTCCAU0CCQDPGXh/GuZk5zANBgkqhkiG9w0BAQsFADB7MQswCQYDVQQGEwJV
UzENMAsGA1UECAwET2hpbzENMAsGA1UEBwwEb2hpbzEMMAoGA1UECgwDaW90MQsw
CQYDVQQLDAJDQTEzMDEGA1UEAwwqSXAtMTcyLTMxLTM0LTQzLnVzLWVhc3QtMi5j
b21wdXRlLmludGVybmFsMB4XDTIwMDEwNTE3MjkwOFoXDTMwMDEwMjE3MjkwOFow
OTE3MDUGA1UEAxMuZWMyLTMtMTQtMy0xMTIudXMtZWFzdC0yLmNvbXB1dGUuYW1h
em9uYXdzLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABDDoEdFWMR6ELTDC
R/8O1kle/6hVEmUA5q+OlSXeUID76FQ5aFG5PkdQcOOI1TfAwBDTTj3Ga+SIKey2
tXtdkGwwDQYJKoZIhvcNAQELBQADggEBAGNaTcYI2hnUXufV5LWtQPXxBwciPy7/
apRhd3e2T5j1HuxO9F1uJ5pT5pv+31Cn/d1Aqu/ZmXPMPHRVOl1845cGrm8cYWcj
ZY1puYQk91t3g9pLHmZbphvL5QeAXPgtZ/saqr3Jch36FvSJrMMy3w+1UXesYFFX
/lDpwSjSF0F6SqfcezRjp+JFZgl4CHUdXVA1j5K0hwZAm3p8dCdSZABn8SIVdNEc
jFq4lBxjCoivlTHpQSEeUu30pxyM/CEq0sdxjhIUeq2/74NbKVpGrZJpTRWOxkMG
lzW+H3txpiuCTedk5FluO4cqUsjlRrlqeC4cZAREVwz11SVhB5Hj8fE=
-----END CERTIFICATE-----
)"
////////////////////////
之后我们将代码上传到 MKR1000 中,代码如下:
'''
#include <PubSubClient.h>
#include <WiFi101.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "arduino_secrets.h"
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
String temp;
''' const char* ssid = "XXXXXX";
const char* password = "XXXX";
const char* certificate = SECRET_CERTIFICATE;
const char* mqtt_server = "";
'''
WiFiClient espClient;
'''BearSSLClient espClient1(espClient);
PubSubClient client(espClient1);
long lastMsg = 0;
char msg[100];
long long int Node_ID = 44;
int value = 0;
int i= 0;
long int tempint;
void setup_wifi()
{ delay(10);
// We start by connecting to a WiFi network
'''
while (!Serial);
if (!ECCX08.begin())
{
Serial.println("No ECCX08 present!");
while (1);
}'''
'''ArduinoBearSSL.onGetTime(getTime);
espClient1.setEccSlot(0, certificate);
Serial.print("Connecting to ");
Serial.println(ssid);
''' WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1')
{
// digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
}
else
{
// digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
'''
void reconnect()
{
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("accelout", "hello vinit");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(115200);
setup_wifi();
Serial.println("Dallas temp started");
sensors.begin();
client.setServer(mqtt_server, 8883);
client.setCallback(callback);
// Start the serial terminal
}
void loop()
{
i=++i;
if (!client.connected())
{
reconnect();
}
client.loop();
sensors.requestTemperatures();
long now = millis();
StaticJsonDocument<400> doc;
doc["ID"] = Node_ID;
doc["RN"] = i;
doc["Temp"] = sensors.getTempCByIndex(0);
Serial.println();
serializeJsonPretty(doc,msg);
Serial.println("Sending message to MQTT topic..");
Serial.println(msg);
client.publish("Home",msg);
unsigned long getTime()
{
// get the current time from the WiFi module
return WiFi.getTime();
}
#
烧录此代码后,我在串行监视器上连接到 wifi 消息,但 mkr1000 仍然无法连接到 mqtt 服务器,代码每 5 分钟重试一次连接到服务器。