1
+ /*
2
+ * Copyright (c) 2018 ARM Limited. All rights reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ * Licensed under the Apache License, Version 2.0 (the License); you may
5
+ * not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
12
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ #include " mbed.h"
18
+ #include " DeviceKey.h"
19
+
20
+ // Print a unsigned char buffer in hex format
21
+ void print_buffer (unsigned char *buf, size_t size)
22
+ {
23
+ for (size_t i = 0 ; i < size; i++) {
24
+ printf (" %02X" , buf[i]);
25
+ }
26
+ }
27
+
28
+ // Injection of a dummy key when there is no TRNG
29
+ int inject_rot_key ()
30
+ {
31
+ uint32_t key[DEVICE_KEY_16BYTE / sizeof (uint32_t )];
32
+
33
+ memset (key, 0 , DEVICE_KEY_16BYTE);
34
+ memcpy (key, " ABCDEF1234567890" , DEVICE_KEY_16BYTE);
35
+ int size = DEVICE_KEY_16BYTE;
36
+ DeviceKey& devkey = DeviceKey::get_instance ();
37
+ return devkey.device_inject_root_of_trust (key, size);
38
+ }
39
+
40
+ // Entry point for the example
41
+ int main ()
42
+ {
43
+ unsigned char derive_key1 [DEVICE_KEY_32BYTE];
44
+ unsigned char salt1[] = " SALT1 ----- SALT1 ------ SALT1" ;
45
+ int ret = DEVICEKEY_SUCCESS;
46
+
47
+ printf (" \n Mbed OS DeviceKey example \n " );
48
+
49
+ // DeviceKey is a singleton
50
+ DeviceKey& devkey = DeviceKey::get_instance ();
51
+
52
+ #if !defined(DEVICE_TRNG)
53
+
54
+ // If TRNG is not available it is a must to inject the ROT before the first call to derive key method.
55
+ printf (" No TRNG support for this device. injecting ROT.\n " );
56
+ ret = inject_rot_key ();
57
+ if (DEVICEKEY_SUCCESS != ret && DEVICEKEY_ALREADY_EXIST != ret) {
58
+ printf (" Error, injection of ROT key has failed with status %d\n " , ret);
59
+ return -1 ;
60
+ }
61
+
62
+ if ( DEVICEKEY_ALREADY_EXIST == ret ) {
63
+ printf (" ROT Key already exists in the persistent memory.\n " , ret);
64
+ } else {
65
+ printf (" ROT Key injected and stored in persistent memory.\n " , ret);
66
+ }
67
+
68
+ #endif
69
+
70
+ printf (" Salt for key derivation: %s \n " , salt1);
71
+
72
+ // 16 byte key derivation.
73
+ ret = devkey.generate_derived_key (salt1, sizeof (salt1), derive_key1, DEVICE_KEY_16BYTE);
74
+ if (DEVICEKEY_SUCCESS != ret) {
75
+ printf (" Error, derive key failed with error code %d \n " , ret);
76
+ return -1 ;
77
+ }
78
+
79
+ printf (" 16-byte Derived key is: " );
80
+ print_buffer (derive_key1, DEVICE_KEY_16BYTE);
81
+ printf (" \n " );
82
+
83
+ printf (" Mbed OS DeviceKey example done.\n " );
84
+
85
+ return 0 ;
86
+ }
0 commit comments