Hello,
I am using AES-128_ECB encryption and I have imported the tropicssl library. I am encrypting it and then encoding it to Base64. But I am having a lot of extra padding. Is there any way to remove the padding, or customise the padding? Like I want to pad it with b’\x10’.
Here is the Base64 Output that I am getting- Ouril+UTDF8htLzEhiRj7wAPDw9PdXJpbCtVVERGOGg=
Converted- b’0123456789012345\xde8\x1d\xea\xc0\xc2d\x10z\xed0\xf6\x88\xaa\t\xfb’
And I should have got- b’Ouril+UTDF8htLzEhiRj7w==‘
Original Message- b’0123456789012345’
See the extra padding is something which I want to avoid/ remove/ customise… Any of those will work!
Here is the code-
size_t pad(unsigned char *buf, size_t messageLength) {
size_t paddedLength = (messageLength & ~15) + 16;
char pad = paddedLength - messageLength;
memset(buf + messageLength, pad, pad);
return paddedLength;
}
void demoAES() {
aes_context aes;
unsigned char key[17]="2222222222222222";
unsigned char buf[17];
Serial.println("Key:");
Serial.println((const char *)key);
// Our super secret message goes into buf
const char *original = "0123456789012345";
int length = strlen(original) + 1; // include null terminating byte
memcpy(buf, original, length);
unsigned char ta[]= "0000000000000000";
unsigned char *encoded= ta;
// Esoterica: add PKCS #7 padding
size_t paddedLength = pad(buf, length);
char *temp="0123456789012345";
// Print the plaintext directly
Serial.println("\nPlaintext:");
Serial.println((const char *)buf);
// buf is unsigned char[]
// encoded is char*
// original is const char*
// Encrypt
aes_setkey_enc(&aes, key, 128); // aes_context * ctx, const unsigned char *key, int keysize
aes_crypt_ecb(&aes, AES_ENCRYPT, buf, buf); // aes_context * ctx, int mode, const unsigned char input[16], unsigned char output[16]
base64_encode(encoded,buf,paddedLength); // char *output, char *input, int inputLen
// Print the ciphertext directly
Serial.println("\nBase64text:");
Serial.println((const char *)encoded);
// Decrypt
// IV has been modified, so use original copy
base64_decode(buf,encoded,16); // char * output, char * input, int inputLen
Serial.println("\nDECODED");
Serial.println((const char *)buf);
aes_setkey_dec(&aes, key, 128); // aes_context * ctx, const unsigned char *key, int keysize
aes_crypt_ecb(&aes, AES_DECRYPT, buf, buf); // aes_context * ctx, int mode, const unsigned char input[16], unsigned char output[16]
// Print the plaintext directly
Serial.println("\nPlaintext (after decrypting):");
Serial.println((const char *)buf);
Serial.println("\n-------------\n");
}