Thanks for your answer.
For my purposes I don't need the tweak in the Flash encrypting. And tried to adapt the algorithm of the Pythonscript.
I am despairing.
I'm just trying to encrypt a file with Python and with the ESP32 and expect the same result.
No matter if I use ECB or CBC mode. The result doesn't match. I don't see what I'm doing wrong.
Can someone help me?
Code: Select all
#include <Arduino.h>
#include "mbedtls/aes.h"
mbedtls_aes_context aes;
unsigned char key[32] ={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x01,0x02 };
unsigned char iv[16]={0};
size_t iv_off=0;
unsigned char input [16]={"this is my test"};
unsigned char output[32];
size_t output_len = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println(String(key, 32));
esp_aes_init(&aes);
esp_aes_setkey( &aes, key, 256 );
/*
esp_aes_crypt_ecb( &aes, ESP_AES_ENCRYPT, input, output );
esp_aes_crypt_ecb( &aes, ESP_AES_DECRYPT, &input[16], &output[16] );
*/
esp_aes_crypt_cbc(&aes, ESP_AES_ENCRYPT, sizeof(input), iv, input, output);
Serial.println(String(output, sizeof(output)));
}
Python:
Code: Select all
def encrypt(output_file, input_file, keyfile):
do_decrypt=False
key = keyfile.read()
backend = default_backend()
iv=[0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
iv= bytes(iv)
cipher = None
block_offs = 0x00
while True:
block = input_file.read(16)
if len(block) == 0:
break
elif len(block) < 16:
if do_decrypt:
raise esptool.FatalError("Data length is not a multiple of 16 bytes")
pad = 16 - len(block)
block = block + os.urandom(pad)
print("Note: Padding with %d bytes of random data (encrypted data must be multiple of 16 bytes long)" % pad)
if block_offs % 32 == 0 or cipher is None:
# each bit of the flash encryption key is XORed with tweak bits derived from the offset of 32 byte block of flash
#block_key = _flash_encryption_tweak_key(key, block_offs, tweak_range)
#block_key = key
test=key
print("key: %s" % test)
print("Decrypt?: %s" % do_decrypt)
if cipher is None: # first pass
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend)
# note AES is used inverted for flash encryption, so
# "decrypting" flash uses AES encrypt algorithm and vice
# versa. (This does not weaken AES.)
actor = cipher.encryptor() if do_decrypt else cipher.decryptor()
output = actor.update(block) + actor.finalize()
#output_file.write(block[::-1]) # reverse output block byte order
#print("Code: %s" % output)
output_file.write(output)
block_offs += 16
- key.txt
- (32 Bytes) Downloaded 196 times