Last active
June 30, 2022 17:01
-
-
Save vixtory09678/22e34e8347620c5d7ff8374c3ea817ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
#include <mbedtls/aes.h> | |
#define PROCESS_FAIL -1 | |
int encrypt(uint8_t *input, uint8_t size, uint8_t key[16], uint8_t *encrypt) { | |
mbedtls_aes_context encryptContext; | |
uint8_t iv[16] = {0}; | |
int ret = 0; | |
uint8_t msgBuff[size]; | |
memset(msgBuff, 0, size); | |
memcpy(msgBuff, input, size); | |
// initial context | |
mbedtls_aes_init(&encryptContext); | |
ret = mbedtls_aes_setkey_enc(&encryptContext, key, 256); | |
if (ret) return PROCESS_FAIL; | |
// encryption | |
ret = mbedtls_aes_crypt_cbc(&encryptContext, ESP_AES_ENCRYPT, size, iv, msgBuff, encrypt); | |
if (ret) return PROCESS_FAIL; | |
return size; | |
} | |
int decrypt(uint8_t *input, size_t size, uint8_t key[16], uint8_t *decrypt) { | |
mbedtls_aes_context decryptContext; | |
uint8_t iv[16] = {0}; | |
int ret = 0; | |
if (size % 16) return PROCESS_FAIL; | |
uint8_t msgBuff[size]; | |
memset(msgBuff, 0, size); | |
memcpy(msgBuff, input, size); | |
// initial context | |
mbedtls_aes_init(&decryptContext); | |
ret = mbedtls_aes_setkey_dec(&decryptContext, key, 256); | |
if (ret) return PROCESS_FAIL; | |
// decryption | |
ret = mbedtls_aes_crypt_cbc(&decryptContext, ESP_AES_DECRYPT, size, iv, msgBuff, decrypt); | |
if (ret) return PROCESS_FAIL; | |
return size; | |
} | |
size_t calAESBlockSize(size_t size) { | |
int blockSizeRemain = (size % 16 == 0) ? 0 : 16 - (size % 16); | |
int totalMsgBuffSize = size + blockSizeRemain; | |
return totalMsgBuffSize; | |
} | |
void setup() { | |
// put your setup code here, to run once: | |
Serial.begin(115200); | |
const char key[16] = "this is a key"; | |
String plaintext = "Welcome to I AM {TEAM}"; | |
int ret = PROCESS_FAIL; | |
size_t buffSize = calAESBlockSize(plaintext.length()); | |
uint8_t buffEncrypt[buffSize] = {0}; | |
uint8_t buffDecrypt[buffSize] = {0}; | |
ret = encrypt((uint8_t *)plaintext.c_str(), buffSize, (uint8_t *)key, buffEncrypt); | |
if (ret == PROCESS_FAIL) return; | |
ret = decrypt(buffEncrypt, buffSize, (uint8_t *)key, buffDecrypt); | |
if (ret == PROCESS_FAIL) return; | |
Serial.printf("before encrypt %s \nAfter encrypt ", plaintext.c_str()); | |
for (uint8_t buff : buffEncrypt) { | |
Serial.print((char)buff); | |
} Serial.println(); | |
Serial.printf("After decrypt "); | |
for (uint8_t buff : buffDecrypt) { | |
Serial.print((char)buff); | |
} Serial.println(); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment