1 /* Copyright (c) 2024 Nordic Semiconductor
2 * SPDX-License-Identifier: Apache-2.0
3 */
4 #include <zephyr/secure_storage/its/store.h>
5 #include <zephyr/secure_storage/its/transform.h>
6 #include <zephyr/sys/util.h>
7 #include <string.h>
8
9 static struct {
10 secure_storage_its_uid_t uid;
11 size_t data_length;
12 uint8_t data[SECURE_STORAGE_ITS_TRANSFORM_MAX_STORED_DATA_SIZE];
13 } s_its_entries[100];
14
get_existing_entry_index(secure_storage_its_uid_t uid)15 static int get_existing_entry_index(secure_storage_its_uid_t uid)
16 {
17 __ASSERT_NO_MSG(uid.uid != 0);
18
19 for (unsigned int i = 0; i != ARRAY_SIZE(s_its_entries); ++i) {
20 if (!memcmp(&uid, &s_its_entries[i].uid, sizeof(uid))) {
21 return i;
22 }
23 }
24 return -1;
25 }
26
secure_storage_its_store_set(secure_storage_its_uid_t uid,size_t data_length,const void * data)27 psa_status_t secure_storage_its_store_set(secure_storage_its_uid_t uid,
28 size_t data_length, const void *data)
29 {
30 __ASSERT_NO_MSG(data_length <= sizeof(s_its_entries[0].data));
31 int index = get_existing_entry_index(uid);
32
33 if (index == -1) {
34 for (unsigned int i = 0; i != ARRAY_SIZE(s_its_entries); ++i) {
35 if (s_its_entries[i].uid.uid == 0) {
36 index = i;
37 break;
38 }
39 }
40 if (index == -1) {
41 return PSA_ERROR_INSUFFICIENT_STORAGE;
42 }
43 s_its_entries[index].uid = uid;
44 }
45
46 s_its_entries[index].data_length = data_length;
47 memcpy(s_its_entries[index].data, data, data_length);
48 return PSA_SUCCESS;
49 }
50
secure_storage_its_store_get(secure_storage_its_uid_t uid,size_t data_size,void * data,size_t * data_length)51 psa_status_t secure_storage_its_store_get(secure_storage_its_uid_t uid, size_t data_size,
52 void *data, size_t *data_length)
53 {
54 const int index = get_existing_entry_index(uid);
55
56 if (index == -1) {
57 return PSA_ERROR_DOES_NOT_EXIST;
58 }
59 *data_length = MIN(data_size, s_its_entries[index].data_length);
60 memcpy(data, s_its_entries[index].data, *data_length);
61 return PSA_SUCCESS;
62 }
63
secure_storage_its_store_remove(secure_storage_its_uid_t uid)64 psa_status_t secure_storage_its_store_remove(secure_storage_its_uid_t uid)
65 {
66 const int index = get_existing_entry_index(uid);
67
68 if (index == -1) {
69 return PSA_ERROR_DOES_NOT_EXIST;
70 }
71 s_its_entries[index].uid.uid = 0;
72 return PSA_SUCCESS;
73 }
74