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-2022 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 "aes/esp_aes_internal.h"
18 #include "mbedtls/aes.h"
19 #include "hal/aes_hal.h"
20 #include "hal/aes_types.h"
21 #include "soc/soc_caps.h"
22 #include "mbedtls/error.h"
23 
24 #include <string.h>
25 #include "mbedtls/platform.h"
26 
27 #if SOC_AES_GDMA
28 #include "esp_aes_dma_priv.h"
29 #endif
30 
valid_key_length(const esp_aes_context * ctx)31 bool valid_key_length(const esp_aes_context *ctx)
32 {
33     bool valid_len = (ctx->key_bytes == AES_128_KEY_BYTES) || (ctx->key_bytes == AES_256_KEY_BYTES);
34 
35 #if SOC_AES_SUPPORT_AES_192
36     valid_len |= ctx->key_bytes == AES_192_KEY_BYTES;
37 #endif
38 
39     return valid_len;
40 }
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 }
47 
esp_aes_free(esp_aes_context * ctx)48 void esp_aes_free( esp_aes_context *ctx )
49 {
50     if ( ctx == NULL ) {
51         return;
52     }
53 
54     bzero( ctx, sizeof( esp_aes_context ) );
55 }
56 
57 /*
58  * AES key schedule (same for encryption or decryption, as hardware handles schedule)
59  *
60  */
esp_aes_setkey(esp_aes_context * ctx,const unsigned char * key,unsigned int keybits)61 int esp_aes_setkey( esp_aes_context *ctx, const unsigned char *key,
62                     unsigned int keybits )
63 {
64 #if !SOC_AES_SUPPORT_AES_192
65     if (keybits == 192) {
66         return MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED;
67     }
68 #endif
69     if (keybits != 128 && keybits != 192 && keybits != 256) {
70         return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
71     }
72     ctx->key_bytes = keybits / 8;
73     memcpy(ctx->key, key, ctx->key_bytes);
74     ctx->key_in_hardware = 0;
75     return 0;
76 }
77