blob: 59edcb517df5c62966d754c35b03a62428cf6427 [file] [log] [blame]
Raymond Maof51f3552024-10-03 14:50:19 -07001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Hash shim layer on MbedTLS Crypto library
4 *
5 * Copyright (c) 2024 Linaro Limited
6 * Author: Raymond Mao <raymond.mao@linaro.org>
7 */
8#ifndef USE_HOSTCC
9#include <cyclic.h>
10#endif /* USE_HOSTCC */
11#include <u-boot/sha256.h>
12
Philippe Reynes496c0062024-12-19 14:05:50 +010013#include <mbedtls/md.h>
14
Philippe Reynes843a1e72024-12-19 14:05:52 +010015#if CONFIG_IS_ENABLED(HKDF_MBEDTLS)
16#include <mbedtls/hkdf.h>
17#endif
18
Raymond Maof51f3552024-10-03 14:50:19 -070019const u8 sha256_der_prefix[SHA256_DER_LEN] = {
20 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
21 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
22 0x00, 0x04, 0x20
23};
24
25void sha256_starts(sha256_context *ctx)
26{
27 mbedtls_sha256_init(ctx);
28 mbedtls_sha256_starts(ctx, 0);
29}
30
31void
32sha256_update(sha256_context *ctx, const uint8_t *input, uint32_t length)
33{
34 mbedtls_sha256_update(ctx, input, length);
35}
36
37void sha256_finish(sha256_context *ctx, uint8_t digest[SHA256_SUM_LEN])
38{
39 mbedtls_sha256_finish(ctx, digest);
40 mbedtls_sha256_free(ctx);
41}
Philippe Reynes496c0062024-12-19 14:05:50 +010042
43int sha256_hmac(const unsigned char *key, int keylen,
44 const unsigned char *input, unsigned int ilen,
45 unsigned char *output)
46{
47 const mbedtls_md_info_t *md;
48
49 md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
50 if (!md)
51 return MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE;
52
53 return mbedtls_md_hmac(md, key, keylen, input, ilen, output);
54}
Philippe Reynes843a1e72024-12-19 14:05:52 +010055
56#if CONFIG_IS_ENABLED(HKDF_MBEDTLS)
57int sha256_hkdf(const unsigned char *salt, int saltlen,
58 const unsigned char *ikm, int ikmlen,
59 const unsigned char *info, int infolen,
60 unsigned char *output, int outputlen)
61{
62 const mbedtls_md_info_t *md;
63
64 md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
65 if (!md)
66 return MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE;
67
68 return mbedtls_hkdf(md, salt, saltlen,
69 ikm, ikmlen,
70 info, infolen,
71 output, outputlen);
72}
73#endif