NuMaker Pelion Device Management example

Fork of mbed-os-example-pelion by cc li

Revision:
14:0e7b5aeba173
Parent:
4:e564fd8be648
--- a/pre-main/provision.cpp	Mon Aug 31 09:28:57 2020 +0800
+++ b/pre-main/provision.cpp	Mon Sep 28 18:03:20 2020 +0800
@@ -19,12 +19,14 @@
 #include "mbed.h"
 #include "mbedtls/config.h"
 #include "entropy_poll.h"
-#include "psa/crypto.h"
 #include "kvstore_global_api.h"
 #include "KVStore.h"
 #include "TDBStore.h"
 #include "KVMap.h"
 #include "kv_config.h"
+#if MBED_MAJOR_VERSION >= 6
+#include "DeviceKey.h"
+#endif
 
 #ifndef __STDC_FORMAT_MACROS
 #define __STDC_FORMAT_MACROS
@@ -142,6 +144,33 @@
 #endif  /* !defined(MBEDTLS_ENTROPY_HARDWARE_ALT) */
 #endif  /* #if !DEVICE_TRNG && !TARGET_PSA */
 
+#if MBED_MAJOR_VERSION >= 6
+    /* Since Mbedd OS 6.0, device key is not installed automatically and silently, possibly via generate_derived_key(...). Install it manually. */
+    printf("Install device key...\r\n");
+
+    /* DeviceKey is a singleton */
+    DeviceKey &devkey = DeviceKey::get_instance();
+
+    /* To be compatible with mbed-bootloader, install 16-byte version. */
+    int device_key_status = devkey.generate_root_of_trust(DEVICE_KEY_16BYTE);
+    switch (device_key_status) {
+        case DEVICEKEY_SUCCESS:
+            printf("\rInstall device key...OK\r\n");
+            break;
+
+        case DEVICEKEY_ALREADY_EXIST:
+            printf("\rInstall device key...Already existed\r\n");
+            break;
+
+        case DEVICEKEY_GENERATE_RANDOM_ERROR:
+            MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_PLATFORM, MBED_ERROR_CODE_UNKNOWN), "No entropy sources and cannot generate device key");
+            MBED_FALLTHROUGH;
+
+        default:
+            MBED_ERROR1(MBED_MAKE_ERROR(MBED_MODULE_PLATFORM, MBED_ERROR_CODE_UNKNOWN), "Install device key failed", device_key_status);
+    }
+#endif
+
     /* Mark the device as provisioned */
     kv_status = inner_store->set(KV_KEY_PROVISION, "1", 1, KVStore::WRITE_ONCE_FLAG);
     if (kv_status != MBED_SUCCESS) {