1 /*
2 * Copyright (c) 2022 Espressif Systems (Shanghai) Co., Ltd.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/printk.h>
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/flash.h>
11 #include <zephyr/storage/flash_map.h>
12
13 #include <esp_flash.h>
14 #include <spi_flash_mmap.h>
15 #include <soc.h>
16
17 #include <zephyr/logging/log.h>
18 LOG_MODULE_REGISTER(flash_encryption, CONFIG_LOG_DEFAULT_LEVEL);
19
20 #if !defined(CONFIG_SOC_SERIES_ESP32)
21 #error Flash encryption feature is only available for ESP32 SOC yet.
22 #endif
23
main(void)24 int main(void)
25 {
26 uint8_t buffer[32];
27 const struct device *flash_device;
28 off_t address = FIXED_PARTITION_OFFSET(storage_partition);
29
30 flash_device = DEVICE_DT_GET(DT_CHOSEN(zephyr_flash_controller));
31 if (!device_is_ready(flash_device)) {
32 printk("%s: device not ready.\n", flash_device->name);
33 return 0;
34 }
35
36 for (int k = 0; k < 32; k++) {
37 buffer[k] = k;
38 }
39 LOG_HEXDUMP_INF(buffer, sizeof(buffer), "WRITE BUFFER CONTENT");
40
41 /* erase flash content */
42 flash_erase(flash_device, address, 4096);
43
44 /* this writes encrypted data into flash */
45 flash_write(flash_device, address, &buffer, sizeof(buffer));
46
47 /* read flash content without decrypting content */
48 memset(buffer, 0, sizeof(buffer));
49 esp_flash_read(NULL, &buffer, address, sizeof(buffer));
50 LOG_HEXDUMP_INF(buffer, sizeof(buffer), "FLASH RAW DATA (Encrypted)");
51
52 /* read flash content and decrypt */
53 memset(buffer, 0, sizeof(buffer));
54 flash_read(flash_device, address, &buffer, sizeof(buffer));
55 LOG_HEXDUMP_INF(buffer, sizeof(buffer), "FLASH DECRYPTED DATA");
56 return 0;
57 }
58