// 引入所需的库
#include <Wire.h> // 用于I2C通信
#include <LiquidCrystal_I2C.h> // 用于控制I2C连接的LCD显示屏
#include "mbedtls/aes.h" // 加密算法库,不在本代码中使用
#include <stdio.h>
#define BTN_PIN 5
// 创建LiquidCrystal_I2C对象,设置I2C地址为0x27,LCD显示屏为16x2的
int LCDaddr = 0x27; // LCD显示屏的I2C地址
int LCDColumns = 16; // LCD显示屏的列数
int LCDRows = 2; // LCD显示屏的行数
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(LCDaddr, LCDColumns, LCDRows);
// 进行AES加密和解密的函数
void enc(){
printf("================= aes加解密演示开始 =================\n");
printf("AES-ECB 加密-数据块(128位),偏移量为0\n");
mbedtls_aes_context aes_ctx;
// 密钥数值
unsigned char key[16] = {'e', 'c', 'b', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd', '1', '2', '3', '4'};
// 明文空间
unsigned char plain[16] = "test1234";
// 解密后明文的空间
unsigned char dec_plain[16] = {0};
// 密文空间
unsigned char cipher[16] = {0};
mbedtls_aes_init(&aes_ctx);
mbedtls_aes_setkey_enc(&aes_ctx, key, 128);
printf("要加密的数据: %s\n", plain);
printf("加密的密码: %s\n", key);
mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, plain, cipher);
printf("加密结果,二进制表示: ");
for(int loop = 0; loop < 16; loop++)
{
LCD.setCursor((loop%8)*2, loop/8);
char buf[32];
sprintf(buf, "%02x" , cipher[loop]); // 格式化文本并将其存储在buffer
LCD.print(buf);
printf("%02x", cipher[loop]);
}
delay(1000); // 延迟1秒
LCD.clear();
printf("\r\n");
// 设置解密密钥
mbedtls_aes_setkey_dec(&aes_ctx, key, 128);
mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_DECRYPT, cipher, dec_plain);
printf("解密后的数据: %s\n", dec_plain);
char buffer[20]; // 创建一个足够大的字符数组来存储格式化后的文本
sprintf(buffer, "Value: %s", dec_plain); // 格式化文本并将其存储在buffer中
LCD.print(buffer); // 打印buffer中的文本到液晶显示屏
mbedtls_aes_free(&aes_ctx);
printf("================= aes加解密演示结束 =================\n");
}
void setup() {
pinMode(BTN_PIN, INPUT_PULLUP);
Serial.begin(115200); // 初始化串口通信,波特率设置为115200
LCD.init(); // 初始化LCD显示屏
LCD.backlight(); // 打开LCD背光
LCD.setCursor(0, 0); // 设置LCD光标位置到第1行第1列
}
int tmp = 1;
void loop() {
if (digitalRead(BTN_PIN) == LOW) {
printf("次数 %d\n", tmp);
tmp++;
LCD.clear();
enc();
delay(1000); // 延迟1秒
}
}