1 /*
2  * Copyright (c) 2023 O.S.Systems
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_DECLARE(updatehub, CONFIG_UPDATEHUB_LOG_LEVEL);
9 
10 #include "updatehub_integrity.h"
11 
12 #if defined(CONFIG_PSA_CRYPTO_CLIENT)
13 #define SUCCESS_VALUE PSA_SUCCESS
14 #else
15 #define SUCCESS_VALUE 0
16 #endif
17 
updatehub_integrity_init(updatehub_crypto_context_t * ctx)18 int updatehub_integrity_init(updatehub_crypto_context_t *ctx)
19 {
20 	int ret;
21 
22 	if (ctx == NULL) {
23 		LOG_DBG("Invalid integrity context");
24 		return -EINVAL;
25 	}
26 
27 #if defined(CONFIG_PSA_CRYPTO_CLIENT)
28 	*ctx = psa_hash_operation_init();
29 	ret = psa_hash_setup(ctx, PSA_ALG_SHA_256);
30 #else
31 	mbedtls_sha256_init(ctx);
32 	ret = mbedtls_sha256_starts(ctx, false);
33 #endif
34 	if (ret != SUCCESS_VALUE) {
35 		LOG_DBG("Failed to %s SHA-256 operation. (%d)", "set up", ret);
36 		return -EFAULT;
37 	}
38 
39 	return 0;
40 }
41 
updatehub_integrity_update(updatehub_crypto_context_t * ctx,const uint8_t * buffer,const uint32_t len)42 int updatehub_integrity_update(updatehub_crypto_context_t *ctx,
43 			       const uint8_t *buffer, const uint32_t len)
44 {
45 	int ret;
46 
47 	if (ctx == NULL || buffer == NULL) {
48 		return -EINVAL;
49 	}
50 
51 	/* bypass */
52 	if (len == 0) {
53 		return 0;
54 	}
55 
56 #if defined(CONFIG_PSA_CRYPTO_CLIENT)
57 	ret = psa_hash_update(ctx, buffer, len);
58 	if (ret != PSA_SUCCESS) {
59 		psa_hash_abort(ctx);
60 	}
61 #else
62 	ret = mbedtls_sha256_update(ctx, buffer, len);
63 	if (ret != 0) {
64 		mbedtls_sha256_free(ctx);
65 	}
66 #endif
67 
68 	if (ret != SUCCESS_VALUE) {
69 		LOG_DBG("Failed to %s SHA-256 operation. (%d)", "update", ret);
70 		return -EFAULT;
71 	}
72 
73 	return 0;
74 }
75 
updatehub_integrity_finish(updatehub_crypto_context_t * ctx,uint8_t * hash,const uint32_t size)76 int updatehub_integrity_finish(updatehub_crypto_context_t *ctx,
77 			       uint8_t *hash, const uint32_t size)
78 {
79 	int ret;
80 
81 	if (ctx == NULL || hash == NULL) {
82 		return -EINVAL;
83 	}
84 
85 	if (size < SHA256_BIN_DIGEST_SIZE) {
86 		LOG_DBG("HASH input buffer is to small to store the message digest");
87 		return -EINVAL;
88 	}
89 
90 #if defined(CONFIG_PSA_CRYPTO_CLIENT)
91 	size_t hash_len;
92 
93 	ret = psa_hash_finish(ctx, hash, size, &hash_len);
94 	if (ret != PSA_SUCCESS) {
95 		psa_hash_abort(ctx);
96 	}
97 #else
98 	ret = mbedtls_sha256_finish(ctx, hash);
99 	mbedtls_sha256_free(ctx);
100 #endif
101 	if (ret != SUCCESS_VALUE) {
102 		LOG_DBG("Failed to %s SHA-256 operation. (%d)", "finish", ret);
103 		return -EFAULT;
104 	}
105 
106 	return 0;
107 }
108