[PATCH v2 10/28] hash: integrate hash on mbedtls

Ilias Apalodimas ilias.apalodimas at linaro.org
Thu May 9 10:31:58 CEST 2024


On Tue, 7 May 2024 at 20:56, Raymond Mao <raymond.mao at linaro.org> wrote:
>
> Integrate common/hash.c on the hash shim layer so that hash APIs
> from mbedtls can be leveraged by boot/image and efi_loader.
>
> Signed-off-by: Raymond Mao <raymond.mao at linaro.org>
> ---
> Changes in v2
> - Use the original head files instead of creating new ones.
>
>  common/hash.c | 134 ++++++++++++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 134 insertions(+)
>
> diff --git a/common/hash.c b/common/hash.c
> index 3d6b84de473..6b8815da237 100644
> --- a/common/hash.c
> +++ b/common/hash.c
> @@ -36,6 +36,132 @@
>  #include <u-boot/sha512.h>
>  #include <u-boot/md5.h>
>
> +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO)
> +
> +static int hash_init_sha1(struct hash_algo *algo, void **ctxp)
> +{
> +       int ret;
> +       mbedtls_sha1_context *ctx = malloc(sizeof(mbedtls_sha1_context));
> +
> +       mbedtls_sha1_init(ctx);

The alloc might fail. What happens if ctx is NULL in mbedTLS?
If that's ok, add a comment to explain why.

> +       ret = mbedtls_sha1_starts(ctx);
> +       if (!ret) {
> +               *ctxp = ctx;
> +       } else {
> +               mbedtls_sha1_free(ctx);
> +               free(ctx);
> +       }
> +
> +       return ret;
> +}
> +
> +static int hash_update_sha1(struct hash_algo *algo, void *ctx, const void *buf,
> +                           unsigned int size, int is_last)
> +{
> +       return mbedtls_sha1_update((mbedtls_sha1_context *)ctx, buf, size);
> +}
> +
> +static int
> +hash_finish_sha1(struct hash_algo *algo, void *ctx, void *dest_buf, int size)
> +{
> +       int ret;
> +
> +       if (size < algo->digest_size)
> +               return -1;
> +
> +       ret = mbedtls_sha1_finish((mbedtls_sha1_context *)ctx, dest_buf);
> +       if (!ret) {
> +               mbedtls_sha1_free((mbedtls_sha1_context *)ctx);
> +               free(ctx);
> +       }
> +
> +       return ret;
> +}
> +
> +static int hash_init_sha256(struct hash_algo *algo, void **ctxp)
> +{
> +       int ret;
> +       int is224 = algo->digest_size == SHA224_SUM_LEN ? 1 : 0;
> +       mbedtls_sha256_context *ctx = malloc(sizeof(mbedtls_sha256_context));

Since we are trying to save as much space as we can, you could pass
this value directly to mbedtls_sha256_starts()

[...]


Thanks
/Ilias


More information about the U-Boot mailing list