blob: 346679dac1c0191ac7385470e8d94651fa56096f [file] [log] [blame]
Harrison Mutai88d6ec82025-08-12 14:32:58 +00001/*
2 * Copyright (c) 2020-2025, Arm Limited. All rights reserved.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7#include <stddef.h>
8#include <stdint.h>
9#include <string.h>
10
11#include "event_log.h"
12
13const struct event_log_algorithm algorithms[] = {
14 { TPM_ALG_SHA256, "SHA256", SHA256_DIGEST_SIZE },
15 { TPM_ALG_SHA384, "SHA384", SHA384_DIGEST_SIZE },
16 { TPM_ALG_SHA512, "SHA512", SHA512_DIGEST_SIZE },
17};
18
19const struct event_log_algorithm *
20event_log_algorithm_lookup(uint16_t algorithm_id)
21{
22 for (size_t i = 0; i < sizeof(algorithms) / sizeof(algorithms[0]);
23 i++) {
24 if (algorithms[i].id == algorithm_id) {
25 return &algorithms[i];
26 }
27 }
28
29 return NULL;
30}
31
32size_t event_log_append_str(char *dst, size_t cap, size_t *pos, const char *s)
33{
34 size_t n = strlen(s);
35 size_t room = (*pos < cap) ? (cap - *pos) : 0;
36
37 if (room) {
38 /* copy as much as fits, leave NUL handled by caller if needed */
39 size_t to_copy = (n < room) ? n : (room - 1);
40 memcpy(dst + *pos, s, to_copy);
41 dst[*pos + to_copy] = '\0';
42 }
43 *pos += n;
44 return n;
45}
46
47size_t event_log_write_hex_spaced(char *dst, size_t dst_len, size_t nbytes,
48 const uint8_t *digest)
49{
50 static const char HEX[] = "0123456789abcdef";
51 size_t pos = 0;
52
53 if (nbytes > dst_len / 3) {
54 nbytes = dst_len / 3;
55 }
56
57 for (size_t i = 0; i < nbytes; i++) {
58 dst[pos++] = HEX[digest[i] >> 4];
59 dst[pos++] = HEX[digest[i] & 0x0F];
60 dst[pos++] = ' ';
61 }
62
63 if (dst_len > 0) {
64 if (pos >= dst_len) {
65 dst[dst_len - 1] = '\0';
66 } else {
67 dst[pos] = '\0';
68 }
69 }
70
71 return pos; /* count that WOULD have been written */
72}