aesesp32esp-idfmbedtlsecb

mbedtls AES 128 ECB mode encryption give wrong results


I'm tryng to encrypt mac address that's used as ssid for my esp32 but i'm having hard times. I've tried several encryption services online and they give all the same result as output in base 64; my code run but i get a different result. What am i doing wrong? please help

void aes_encrypt_and_base64_mac(const uint8_t *input, const uint8_t *key, char *output_base64, size_t output_size) {
    mbedtls_aes_context aes;
    uint8_t encrypted[16]; // AES encrypts blocks of 16 bytes
    mbedtls_aes_init(&aes);
    mbedtls_aes_setkey_enc(&aes, key, 128);
    mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, input, encrypted);
    mbedtls_aes_free(&aes);

    size_t len = 0;
    mbedtls_base64_encode((unsigned char *)output_base64, output_size, &len, encrypted, sizeof(encrypted));
    ESP_LOGI(TAG, "Encrypted Base64 output: %s", output_base64);
}

void change_ssid_to_mac(){
    uint8_t mac[6];
    char dynamic_ssid[33]; // Buffer of 32 characters + 1 for the null terminator

    // Get the device MAC address
    esp_wifi_get_mac(ESP_IF_WIFI_STA, mac);  // WIFI_IF_STA

    // Log the MAC address in hexadecimal format
    ESP_LOGI(TAG, "MAC Address before encryption: %02X:%02X:%02X:%02X:%02X:%02X",
             mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    // Prepare the input for encryption
    uint8_t mac_padded[16] = {0};
    memcpy(mac_padded, mac, sizeof(mac)); // Note: This padding might not be necessary for AES, but ensure the input is 16 bytes.

    // AES secret key (16 characters = 128 bits)
    const uint8_t aes_key[16] = "1234567891234567";

    // Buffer for the Base64 output
    char encrypted_base64[26]; // Larger to accommodate Base64 output

    // Encrypt and encode to Base64
    aes_encrypt_and_base64_mac(mac_padded, aes_key, encrypted_base64, sizeof(encrypted_base64));

    // Build the SSID with the prefix "F_"
    snprintf(dynamic_ssid, sizeof(dynamic_ssid), "F_%s", encrypted_base64);

    // Log and various updates
    ESP_LOGI(TAG, "Generated SSID: %s", dynamic_ssid);
    strncpy((char *)wifi_settings.ap_ssid, dynamic_ssid, sizeof(wifi_settings.ap_ssid) - 1);
    wifi_settings.ap_ssid[sizeof(wifi_settings.ap_ssid) - 1] = '\0'; // Ensure string termination
}

Solution

  • i solved it, i was using 0 for padding, but pkcs#7 is required for padding