1 /*
2  * AES block cipher, ESP hardware accelerated version, common
3  * Based on mbedTLS FIPS-197 compliant version.
4  *
5  * SPDX-FileCopyrightText: The Mbed TLS Contributors
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  *
9  * SPDX-FileContributor: 2016-2023 Espressif Systems (Shanghai) CO LTD
10  */
11 /*
12  *  The AES block cipher was designed by Vincent Rijmen and Joan Daemen.
13  *
14  *  http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf
15  *  http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
16  */
17 #include "sdkconfig.h"
18 #include "aes/esp_aes_internal.h"
19 #include "mbedtls/aes.h"
20 #include "hal/aes_hal.h"
21 #include "hal/aes_types.h"
22 #include "soc/soc_caps.h"
23 #include "mbedtls/error.h"
24 
25 #include <string.h>
26 #include "mbedtls/platform.h"
27 
28 #if SOC_AES_SUPPORT_DMA
29 #include "esp_aes_dma_priv.h"
30 #endif
31 
valid_key_length(const esp_aes_context * ctx)32 bool valid_key_length(const esp_aes_context *ctx)
33 {
34     bool valid_len = (ctx->key_bytes == AES_128_KEY_BYTES) || (ctx->key_bytes == AES_256_KEY_BYTES);
35 
36 #if SOC_AES_SUPPORT_AES_192
37     valid_len |= ctx->key_bytes == AES_192_KEY_BYTES;
38 #endif
39 
40     return valid_len;
41 }
42 
esp_aes_init(esp_aes_context * ctx)43 void esp_aes_init(esp_aes_context *ctx)
44 {
45     bzero(ctx, sizeof(esp_aes_context));
46 #if SOC_AES_SUPPORT_DMA && CONFIG_MBEDTLS_AES_USE_INTERRUPT
47     esp_aes_intr_alloc();
48 #endif
49 }
50 
esp_aes_free(esp_aes_context * ctx)51 void esp_aes_free( esp_aes_context *ctx )
52 {
53     if ( ctx == NULL ) {
54         return;
55     }
56 
57     bzero( ctx, sizeof( esp_aes_context ) );
58 }
59 
60 /*
61  * AES key schedule (same for encryption or decryption, as hardware handles schedule)
62  *
63  */
esp_aes_setkey(esp_aes_context * ctx,const unsigned char * key,unsigned int keybits)64 int esp_aes_setkey( esp_aes_context *ctx, const unsigned char *key,
65                     unsigned int keybits )
66 {
67 #if !SOC_AES_SUPPORT_AES_192
68     if (keybits == 192) {
69         return MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED;
70     }
71 #endif
72     if (keybits != 128 && keybits != 192 && keybits != 256) {
73         return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
74     }
75     ctx->key_bytes = keybits / 8;
76     memcpy(ctx->key, key, ctx->key_bytes);
77     ctx->key_in_hardware = 0;
78     return 0;
79 }
80