#include <DHT.h>
#include <mbedtls/aes.h> // Include mbedTLS for AES encryption
// Define DHT11 Sensor
#define DHTPIN 4 // GPIO pin for DHT11
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// AES Key (128-bit key for AES-128)
const unsigned char aes_key[16] = {
0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0,
0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0
};
void setup() {
Serial.begin(115200);
dht.begin();
delay(1000);
Serial.println("ESP32 DHT11 with AES Encryption (mbedTLS)");
}
void loop() {
// Read temperature and humidity
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if the reading failed
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
delay(2000);
return;
}
// Display the original temperature and humidity readings
Serial.print("Original Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Original Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Convert data to a string format: "temperature,humidity"
String data = String(temperature) + "," + String(humidity);
char dataArray[16] = {0}; // Ensure it's 16 bytes
data.toCharArray(dataArray, 16);
// Prepare AES context
mbedtls_aes_context aes;
mbedtls_aes_init(&aes);
mbedtls_aes_setkey_enc(&aes, aes_key, 128);
// Encrypt the data
unsigned char encryptedData[16];
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, (unsigned char*)dataArray, encryptedData);
// Print encrypted data in HEX format
Serial.print("Encrypted Data: ");
for (int i = 0; i < 16; i++) {
Serial.print(encryptedData[i], HEX);
Serial.print(" ");
}
Serial.println();
// Decrypt the data
char decryptedData[16] = {0};
mbedtls_aes_setkey_dec(&aes, aes_key, 128);
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_DECRYPT, encryptedData, (unsigned char*)decryptedData);
// Print decrypted data as a string
Serial.print("Decrypted Data: ");
Serial.println(decryptedData);
// Free AES context
mbedtls_aes_free(&aes);
// Delay before next reading
delay(2000);
}