#include <AESLib>
AESLib aesLib;
// AES Encryption Key (same key used for Encryption and Decryption)
const char* key = "0123456789ABCDEF"; // Must be a 16, 24 or 32 character string
// General initialization vector (same as in node-js example) (you must use your own IV's in production for full security!!!)
byte iv[N_BLOCK] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
// Generate IV (once)
void aes_init() {
aesLib.gen_iv(iv);
aesLib.set_paddingmode((paddingMode)0); // AES_PADDING_MODE_ZERO (default is PKCS7)
}
// Encrypts a string and returns the size of the encrypted data
int encrypt(char *msg, byte *encMsg) {
int msgLen = strlen(msg);
int paddedLen = aesLib.get_padded_len(msgLen);
aesLib.encrypt((byte*)msg, paddedLen, encMsg, (byte*)key, sizeof(key), iv);
return paddedLen;
}
// Decrypts a byte array and returns the original string
String decrypt(byte *encMsg, int encMsgLen) {
char msg[encMsgLen];
aesLib.decrypt(encMsg, encMsgLen, (byte*)key, sizeof(key), iv);
return String(msg);
}
void setup() {
Serial.begin(115200);
aes_init(); // Initialize AES
char msg[] = "This is a secret message"; // Message to be encrypted
byte encMsg[256]; // Buffer to hold the encrypted message
// Encrypt
int encMsgLen = encrypt(msg, encMsg);
// Decrypt
String decMsg = decrypt(encMsg, encMsgLen);
// Print encrypted and decrypted messages
Serial.println("Encrypted Message:");
for (int i = 0; i < encMsgLen; i++) {
Serial.print(encMsg[i], HEX);
Serial.print(" ");
}
Serial.println();
Serial.print("Decrypted Message: ");
Serial.println(decMsg);
}