Files
ESPC3-wireless/app/utils/sb_aes.c
2025-07-09 15:41:50 +08:00

89 lines
2.5 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mbedtls/aes.h"
#define RAWDATALEN 16
// uint8_t rawData[RAWDATALEN];
uint8_t aes_iv[16];
// aes key加密和解密要用同样的key
uint8_t aes_key[16] = {0xFE, 0x63, 0x96, 0xF9, 0x5C, 0xEF, 0xB8, 0xF4, 0x07, 0x05, 0xD1, 0xB6, 0xEB, 0xAB, 0xEA, 0x07};
uint8_t aes_iv_original[16] = {0x3D, 0x27, 0x4E, 0x83, 0x43, 0x5D, 0x30, 0xEC, 0x62, 0xEB, 0x90, 0x3A, 0xAC, 0x60, 0x12, 0xF5};
mbedtls_aes_context aes;
void sb_aes_init()
{
// 初始化aes上下文
mbedtls_aes_init(&aes);
}
void reset_iv()
{
// 该函数用于每次加密、解密前重置iv值iv值的内容是随意定的只要起到不是随便就能猜中的IV值即可。
// 加、解密所用的iv值必须相同。此处把iv值设置为0~15
memcpy(aes_iv, aes_iv_original, 16);
}
int sb_aes_encrypt(uint8_t *crypt_data, int crypt_len, uint8_t *output_data)
{
int ret;
// 设置加密的key
mbedtls_aes_setkey_enc(&aes, aes_key, 128);
reset_iv(); // 因为调用mbedtls_aes_crypt_cbc后传入的iv值会有变化重置iv值会有变化
ret = mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_ENCRYPT, crypt_len, aes_iv, crypt_data, output_data);
if (ret)
{
return -1;
}
return crypt_len;
}
int sb_aes_decrypt(uint8_t *crypt_data, int crypt_len, uint8_t *output_data)
{
int ret;
// 设置解密的key
mbedtls_aes_setkey_dec(&aes, aes_key, 128);
reset_iv(); // 因为调用mbedtls_aes_crypt_cbc后传入的iv值会有变化重置iv值会有变化
ret = mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, crypt_len, aes_iv, crypt_data, output_data);
if (ret)
{
return -1;
}
return crypt_len;
}
// void app_main(void)
//{
// uint8_t encData[RAWDATALEN] = { 0 };
// uint8_t decData[RAWDATALEN] = { 0 };
// sb_aes_init(); // 初始化aes上下文
// // 打印原始数据
// printf("rawData:\t");
// for (int i = 0; i < RAWDATALEN; i++) {
// printf("%02x, ", rawData[i]);
// }
// printf("\n");
// // 加密
// int encresult = sb_aes_encrypt(rawData, sizeof(rawData), encData);
// printf("enc data(%d):\t", encresult);
// for (int i = 0; i < RAWDATALEN; i++) {
// printf("%02x, ", encData[i]);
// }
// printf("\n");
// // 解密
// int decresult = sb_aes_decrypt(encData, RAWDATALEN, decData);
// printf("dec data(%d):\t", decresult);
// for (int i = 0; i < RAWDATALEN; i++) {
// printf("%02x, ", decData[i]);
// }
// printf("\n");
//}