AES256 Decryption problem

Hello,
I came by most of this code on the forum after searching for long. I tried to modified it but unfortunately the decrypted text is incorrect. I am using AES in ECB mode

#include <Crypto.h>
#include <AES.h>

String RawData = "21.224959807829812,72.80706712431909,8043,5983,7585,8591,4889,9247";
AES256 Aes256;
BlockCipher* Cipher = &Aes256;

void setup()
{
	Serial1.begin(9600);

	byte Plaintext[RawData.length()];

	RawData.getBytes(Plaintext, RawData.length());

	byte Key[32] = {1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8};

	crypto_feed_watchdog();

	// Set the Encryption key
	Cipher->setKey(Key, Cipher->keySize());

	byte EncryptedBuffer[RawData.length()];
	byte DecryptedBuffer[RawData.length()];

	// Encryption
	Cipher->encryptBlock(EncryptedBuffer, Plaintext);

	// Print Original Data
	Serial1.print("Original Data: ");
	Serial1.println(reinterpret_cast<char*>(Plaintext));

	// Decryption
	Cipher->setKey(Key, Cipher->keySize());
	Cipher->decryptBlock(DecryptedBuffer, EncryptedBuffer);

	// Print decrypted data
	Serial1.print("Decrypted Data: ");
	Serial1.println((char*)DecryptedBuffer);
}

void loop()
{
}

The result is

Original Data: 21.224959807829812,72.80706712431909,8043,5983,7585,8591,4889,924
Decrypted Data: 21.2249598078298

I believe I am missing something for block encryption. All help is appreciated.

It is utterly pointless to use Strings. I recommend to start by studying the simple Arduino examples that come with the AES library.

Unfortunately,
There is no ECB example.

Your code works, it's just that you are only doing it in one block. AES-ECB works on 16 byte blocks. You encrypt the first 16 bytes, then the next 16 bytes, and so on.

You have to loop on the Plaintext in 16 byte increments to encrypt everything. Something like the following

uint8_t numBlocks = (number_of_bytes_in_Plaintext)/16;


for(count=0; count<numBlocks; count++)
{
	// Encryption
	Cipher->encryptBlock(EncryptedBuffer+(count*16), Plaintext+(count*16));

	// Print Original Data
	Serial1.print("Original Data: ");
	Serial1.println(reinterpret_cast<char*>(Plaintext+(count*16)));

	// Decryption
	Cipher->setKey(Key, Cipher->keySize());
	Cipher->decryptBlock(DecryptedBuffer+(count*16), EncryptedBuffer+(count*16));

	// Print decrypted data
	Serial1.print("Decrypted Data: ");
	Serial1.println((char*)(DecryptedBuffer+(count*16)));
}

The special case exist when your plaintext bytes is not a multiple of 16. But I supposed you can figure out what to do in that case.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.