1 /*
2 * Copyright (c) 2023 Nordic Semiconductor ASA
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7
8 /* This file provides an (internal-use-only) credential digest function that backends storing
9 * raw credentials can use.
10 */
11
12 #include <string.h>
13
14 #include <zephyr/init.h>
15 #include <zephyr/kernel.h>
16 #include "tls_internal.h"
17 #include "tls_credentials_digest_raw.h"
18
19 #if defined(CONFIG_PSA_WANT_ALG_SHA_256) && defined(CONFIG_BASE64)
20
21 #include <psa/crypto.h>
22 #include <zephyr/sys/base64.h>
23
credential_digest_raw(struct tls_credential * credential,void * dest,size_t * len)24 int credential_digest_raw(struct tls_credential *credential, void *dest, size_t *len)
25 {
26 int err = 0;
27 size_t written = 0;
28 uint8_t digest_buf[32];
29 size_t digest_len;
30 psa_status_t status;
31
32 /* Compute digest. */
33 status = psa_hash_compute(PSA_ALG_SHA_256, credential->buf, credential->len,
34 digest_buf, sizeof(digest_buf), &digest_len);
35 if (status != PSA_SUCCESS) {
36 return -EIO;
37 }
38
39 /* Attempt to encode digest to destination.
40 * Will return -ENOMEM if there is not enough space in the destination buffer.
41 */
42 err = base64_encode(dest, *len, &written, digest_buf, sizeof(digest_buf));
43 *len = err ? 0 : written;
44
45 /* Clean up. */
46 memset(digest_buf, 0, sizeof(digest_buf));
47
48 return err;
49 }
50
51 #else
52
credential_digest_raw(struct tls_credential * credential,void * dest,size_t * len)53 int credential_digest_raw(struct tls_credential *credential, void *dest, size_t *len)
54 {
55 *len = 0;
56 return -ENOTSUP;
57 }
58
59 #endif
60