[PATCH v2 2/2] crypto: asymmetric_keys - simplify asymmetric_key_hex_to_key_id

From: Thorsten Blum

Date: Sun Oct 12 2025 - 16:39:08 EST


Use struct_size() to calculate the number of bytes to allocate for the
asymmetric key id. Add a local variable to store the hex data length
instead of recalculating it.

Return and forward the error code from __asymmetric_key_hex_to_key_id()
directly instead of manually returning -EINVAL.

No functional change.

Signed-off-by: Thorsten Blum <thorsten.blum@xxxxxxxxx>
---
Changes in v2:
- Keep 'ret' and forward the errno from __asymmetric_key_hex_to_key_id()
as suggested by Lukas
- Link to v1: https://lore.kernel.org/lkml/20251007185220.234611-3-thorsten.blum@xxxxxxxxx/
---
crypto/asymmetric_keys/asymmetric_type.c | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/crypto/asymmetric_keys/asymmetric_type.c b/crypto/asymmetric_keys/asymmetric_type.c
index bd96f799757d..abd5cf419f83 100644
--- a/crypto/asymmetric_keys/asymmetric_type.c
+++ b/crypto/asymmetric_keys/asymmetric_type.c
@@ -229,6 +229,7 @@ struct asymmetric_key_id *asymmetric_key_hex_to_key_id(const char *id)
{
struct asymmetric_key_id *match_id;
size_t asciihexlen;
+ size_t hexlen;
int ret;

if (!*id)
@@ -237,14 +238,14 @@ struct asymmetric_key_id *asymmetric_key_hex_to_key_id(const char *id)
if (asciihexlen & 1)
return ERR_PTR(-EINVAL);

- match_id = kmalloc(sizeof(struct asymmetric_key_id) + asciihexlen / 2,
- GFP_KERNEL);
+ hexlen = asciihexlen / 2;
+ match_id = kmalloc(struct_size(match_id, data, hexlen), GFP_KERNEL);
if (!match_id)
return ERR_PTR(-ENOMEM);
- ret = __asymmetric_key_hex_to_key_id(id, match_id, asciihexlen / 2);
+ ret = __asymmetric_key_hex_to_key_id(id, match_id, hexlen);
if (ret < 0) {
kfree(match_id);
- return ERR_PTR(-EINVAL);
+ return ERR_PTR(ret);
}
return match_id;
}
--
2.51.0