+/* Encrypt or decrypt the environment before writing or reading it. */
+static int env_aes_cbc_crypt(char *payload, const int enc)
+{
+ uint8_t *data = (uint8_t *)payload;
+ const int len = getenvsize();
+ uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
+ uint32_t aes_blocks;
+
+ /* First we expand the key. */
+ aes_expand_key(aes_key, key_exp);
+
+ /* Calculate the number of AES blocks to encrypt. */
+ aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
+
+ if (enc)
+ aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
+ else
+ aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
+
+ return 0;
+}
+