[PATCH 2/2] crypto: aes - helper function to validate key length for AES algorithms

From: Iuliana Prodan
Date: Thu Jul 25 2019 - 14:06:46 EST


Add inline helper function to check key length for AES algorithms.
The key can be 128, 192 or 256 bits size.
This function is used in the generic aes and aes_ti implementations.

Signed-off-by: Iuliana Prodan <iuliana.prodan@xxxxxxx>
---
crypto/aes_generic.c | 7 ++++---
crypto/aes_ti.c | 8 ++++----
include/crypto/aes.h | 17 +++++++++++++++++
3 files changed, 25 insertions(+), 7 deletions(-)

diff --git a/crypto/aes_generic.c b/crypto/aes_generic.c
index f217568..f5b7cf6 100644
--- a/crypto/aes_generic.c
+++ b/crypto/aes_generic.c
@@ -1219,10 +1219,11 @@ int crypto_aes_expand_key(struct crypto_aes_ctx *ctx, const u8 *in_key,
unsigned int key_len)
{
u32 i, t, u, v, w, j;
+ int err;

- if (key_len != AES_KEYSIZE_128 && key_len != AES_KEYSIZE_192 &&
- key_len != AES_KEYSIZE_256)
- return -EINVAL;
+ err = check_aes_keylen(key_len);
+ if (err)
+ return err;

ctx->key_length = key_len;

diff --git a/crypto/aes_ti.c b/crypto/aes_ti.c
index 1ff9785b..786311c 100644
--- a/crypto/aes_ti.c
+++ b/crypto/aes_ti.c
@@ -172,11 +172,11 @@ static int aesti_expand_key(struct crypto_aes_ctx *ctx, const u8 *in_key,
{
u32 kwords = key_len / sizeof(u32);
u32 rc, i, j;
+ int err;

- if (key_len != AES_KEYSIZE_128 &&
- key_len != AES_KEYSIZE_192 &&
- key_len != AES_KEYSIZE_256)
- return -EINVAL;
+ err = check_aes_keylen(key_len);
+ if (err)
+ return err;

ctx->key_length = key_len;

diff --git a/include/crypto/aes.h b/include/crypto/aes.h
index 0fdb542..c3a92ca 100644
--- a/include/crypto/aes.h
+++ b/include/crypto/aes.h
@@ -33,6 +33,23 @@ extern const u32 crypto_fl_tab[4][256] ____cacheline_aligned;
extern const u32 crypto_it_tab[4][256] ____cacheline_aligned;
extern const u32 crypto_il_tab[4][256] ____cacheline_aligned;

+/*
+ * validate key length for AES algorithms
+ */
+static inline int check_aes_keylen(unsigned int keylen)
+{
+ switch (keylen) {
+ case AES_KEYSIZE_128:
+ case AES_KEYSIZE_192:
+ case AES_KEYSIZE_256:
+ break;
+ default:
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
int crypto_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len);
int crypto_aes_expand_key(struct crypto_aes_ctx *ctx, const u8 *in_key,
--
2.1.0