

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Créez un gestionnaire de certificats personnalisé pour un stockage sécurisé
<a name="managedintegrations-sdk-v2-cookbook-certhandler"></a>

La gestion des certificats des appareils est cruciale lors de l'intégration au hub d'intégrations gérées. Bien que les certificats soient stockés dans le système de fichiers par défaut, vous pouvez créer un gestionnaire de certificats personnalisé pour une sécurité renforcée et une gestion flexible des informations d'identification.

Le SDK End Device pour les intégrations gérées fournit un gestionnaire de certificats pour une interface de stockage sécurisée que vous pouvez implémenter sous la forme d'une bibliothèque d'objets partagés (.so). Créez votre implémentation de stockage sécurisé pour lire et écrire des certificats, puis liez le fichier de bibliothèque au HubOnboarding processus lors de l'exécution.

## Définition et composants de l'API
<a name="managedintegrations-sdk-v2-cookbook-certhandler-api"></a>

Consultez le `secure_storage_cert_handler_interface.hpp` fichier suivant pour comprendre les composants de l'API et les exigences de votre implémentation

**Topics**
+ [Définition de l'API](#managedintegrations-sdk-v2-cookbook-certhandler-apidef)
+ [Composants clés](#managedintegrations-sdk-v2-cookbook-certhandler-apicomp)

### Définition de l'API
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apidef"></a>

**Contenu de `secure_storage_cert_hander_interface.hpp`**

```
/* 
    * Copyright 2024 Amazon.com, Inc. or its affiliates. All rights reserved. 
    *
    * AMAZON PROPRIETARY/CONFIDENTIAL 
    *
    * You may not use this file except in compliance with the terms and
    * conditions set forth in the accompanying LICENSE.txt file.
    *
    * THESE MATERIALS ARE PROVIDED ON AN "AS IS" BASIS. AMAZON SPECIFICALLY 
    * DISCLAIMS, WITH RESPECT TO THESE MATERIALS, ALL WARRANTIES, EXPRESS, 
    * IMPLIED, OR STATUTORY, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, 
    * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. 
    */ 
    #ifndef SECURE_STORAGE_CERT_HANDLER_INTERFACE_HPP
    #define SECURE_STORAGE_CERT_HANDLER_INTERFACE_HPP 
    
    #include <iostream>
    #include <memory>
    
    namespace IoTManagedIntegrationsDevice { 
    namespace CertHandler {
    /**
     * @enum CERT_TYPE_T
     * @brief enumeration defining certificate types. 
     */ 
     typedef enum { CLAIM = 0, DHA = 1, PERMANENT = 2 } CERT_TYPE_T;
     class SecureStorageCertHandlerInterface {
      public:
       /** 
        * @brief Read certificate and private key value of a particular certificate
        * type from secure storage.
        */ 
        virtual bool read_cert_and_private_key(const CERT_TYPE_T cert_type, 
                                              std::string &cert_value, 
                                              std::string &private_key_value) = 0; 
        /** 
          * @brief Write permanent certificate and private key value to secure storage.
          */
        virtual bool write_permanent_cert_and_private_key(
            std::string_view cert_value, std::string_view private_key_value) = 0; 
        };
        std::shared_ptr<SecureStorageCertHandlerInterface> createSecureStorageCertHandler();
    } //namespace CertHandler
    } //namespace IoTManagedIntegrationsDevice
  
    #endif //SECURE_STORAGE_CERT_HANDLER_INTERFACE_HPP
```

### Composants clés
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apicomp"></a>
+ CERT\_TYPE\_T : différents types de certificats sur le hub.
  + RÉCLAMATION - le certificat de réclamation initialement enregistré sur le hub sera échangé contre un certificat permanent.
  + DHA : inutilisé pour le moment.
  + PERMANENT - certificat permanent pour se connecter au point de terminaison des intégrations gérées.
+ read\_cert\_and\_private\_key - (FONCTION À IMPLÉMENTER) Lit le certificat et la valeur de la clé dans l'entrée de référence. Cette fonction doit être capable de lire à la fois le certificat CLAIM et le certificat PERMANENT, et elle est différenciée par le type de certificat mentionné ci-dessus.
+ write\_permanent\_cert\_and\_private\_key - (FONCTION À IMPLÉMENTER) écrit le certificat permanent et la valeur de la clé à l'emplacement souhaité.

## Exemple de construction
<a name="managedintegrations-sdk-v2-cookbook-exbuild"></a>

Séparez vos en-têtes d'implémentation internes de l'interface publique (`secure_storage_cert_handler_interface.hpp`) pour conserver une structure de projet propre. Grâce à cette séparation, vous pouvez gérer les composants publics et privés lors de la création de votre gestionnaire de certificats.

**Note**  
Déclarer `secure_storage_cert_handler_interface.hpp` comme public.

**Topics**
+ [Structure du projet](#managedintegrations-sdk-v2-cookbook-proj)
+ [Hériter de l'interface](#managedintegrations-sdk-v2-cookbook-interface)
+ [Mise en œuvre](#managedintegrations-sdk-v2-cookbook-interimpl)
+ [CMakeList.txt](#managedintegrations-sdk-v2-cookbook-cmakelist)

### Structure du projet
<a name="managedintegrations-sdk-v2-cookbook-proj"></a>

![Structure du projet du gestionnaire de certificats d'intégrations gérées.](http://docs.aws.amazon.com/fr_fr/iot-mi/latest/devguide/images/iot-managedintegrations-cert-handler-projstruct.png)


### Hériter de l'interface
<a name="managedintegrations-sdk-v2-cookbook-interface"></a>

Créez une classe concrète qui hérite de l'interface. Masquez ce fichier d'en-tête et les autres fichiers dans un répertoire distinct afin de différencier facilement les en-têtes privés et publics lors de la création.

```
#ifndef IOTMANAGEDINTEGRATIONSDEVICE_SDK_STUB_SECURE_STORAGE_CERT_HANDLER_HPP
  #define IOTMANAGEDINTEGRATIONSDEVICE_SDK_STUB_SECURE_STORAGE_CERT_HANDLER_HPP 
  
  #include "secure_storage_cert_handler_interface.hpp" 
  
  namespace IoTManagedIntegrationsDevice::CertHandler { 
    class StubSecureStorageCertHandler : public SecureStorageCertHandlerInterface { 
      public:
        StubSecureStorageCertHandler() = default; 
        
        bool read_cert_and_private_key(const CERT_TYPE_T cert_type,
                                      std::string &cert_value, 
                                      std::string &private_key_value) override; 
                                      
        bool write_permanent_cert_and_private_key(
            std::string_view cert_value, std::string_view private_key_value) override; 
            /*
            * any other resource for function you might need 
            */
            
            
          }; 
      } 
    #endif //IOTMANAGEDINTEGRATIONSDEVICE_SDK_STUB_SECURE_STORAGE_CERT_HANDLER_HPP
```

### Mise en œuvre
<a name="managedintegrations-sdk-v2-cookbook-interimpl"></a>

Implémentez la classe de stockage définie ci-dessus,`src/stub_secure_storage_cert_handler.cpp`.

```
/* 
  * Copyright 2024 Amazon.com, Inc. or its affiliates. All rights reserved. 
  * 
  * AMAZON PROPRIETARY/CONFIDENTIAL 
  *
  * You may not use this file except in compliance with the terms and
  * conditions set forth in the accompanying LICENSE.txt file. 
  * 
  * THESE MATERIALS ARE PROVIDED ON AN "AS IS" BASIS. AMAZON SPECIFICALLY 
  * DISCLAIMS, WITH RESPECT TO THESE MATERIALS, ALL WARRANTIES, EXPRESS, 
  * IMPLIED, OR STATUTORY, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, 
  * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. 
  */

  #include "stub_secure_storage_cert_handler.hpp" 
  
  using namespace IoTManagedIntegrationsDevice::CertHandler;
  
  bool StubSecureStorageCertHandler::write_permanent_cert_and_private_key( 
              std::string_view cert_value, std::string_view private_key_value) { 
            // TODO: implement write function 
            return true;
  }
  
  bool StubSecureStorageCertHandler::read_cert_and_private_key(const CERT_TYPE_T cert_type, 
                                                          std::string &cert_value,
                                                          std::string &private_key_value) {
          std::cout<<"Using Stub Secure Storage Cert Handler, returning dummy values";
          cert_value = "StubCertVal"; 
          private_key_value = "StubKeyVal"; 
          // TODO: implement read function 
          return true;
  }
```

Implémentez la fonction d'usine définie dans l'interface,`src/secure_storage_cert_handler.cpp`.

```
#include "stub_secure_storage_cert_handler.hpp"
        
        std::shared_ptr<IoTManagedIntegrationsDevice::CertHandler::SecureStorageCertHandlerInterface>
        IoTManagedIntegrationsDevice::CertHandler::createSecureStorageCertHandler() { 
          // TODO: replace with your implementation 
        return std::make_shared<IoTManagedIntegrationsDevice::CertHandler::StubSecureStorageCertHandler>(); 
      }
```

### CMakeList.txt
<a name="managedintegrations-sdk-v2-cookbook-cmakelist"></a>

```
#project name must stay the same
      project(SecureStorageCertHandler) 
      
      # Public Header files. The interface definition must be in top level with exactly the same name 
      #ie. Not in anotherDir/secure_storage_cert_hander_interface.hpp 
      set(PUBLIC_HEADERS
                ${PROJECT_SOURCE_DIR}/include 
      )
      
      # private implementation headers.
      set(PRIVATE_HEADERS 
                ${PROJECT_SOURCE_DIR}/internal/stub 
      )
      
      #set all sources 
      set(SOURCES 
                ${PROJECT_SOURCE_DIR}/src/secure_storage_cert_handler.cpp 
                ${PROJECT_SOURCE_DIR}/src/stub_secure_storage_cert_handler.cpp 
        )
        
      # Create the shared library
      add_library(${PROJECT_NAME} SHARED ${SOURCES})
      target_include_directories( 
                ${PROJECT_NAME} 
                PUBLIC
                    ${PUBLIC_HEADERS} 
                PRIVATE 
                    ${PRIVATE_HEADERS}
      )
      
      # Set the library output location. Location can be customized but version must stay the same
      set_target_properties(${PROJECT_NAME} PROPERTIES 
                LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/../lib 
                VERSION 1.0 
                SOVERSION 1
      )
      
      # Install rules
      install(TARGETS ${PROJECT_NAME} 
                LIBRARY DESTINATION lib 
                ARCHIVE DESTINATION lib 
      )
      
      install(FILES ${HEADERS} 
                DESTINATION include/SecureStorageCertHandler
      )
```

## Utilisation
<a name="managedintegrations-sdk-v2-cookbook-certhandler-usage"></a>

Après la compilation, vous disposerez d'un fichier de bibliothèque d'objets `libSecureStorageCertHandler.so` partagé et de ses liens symboliques associés. Copiez le fichier de bibliothèque et les liens symboliques vers l'emplacement de bibliothèque attendu par le HubOnboarding binaire.

**Topics**
+ [Considérations clés](#managedintegrations-sdk-v2-cookbook-certhandler-useconsider)
+ [Utilisez un stockage sécurisé](#managedintegrations-sdk-v2-cookbook-certhandler-usagehowto)

### Considérations clés
<a name="managedintegrations-sdk-v2-cookbook-certhandler-useconsider"></a>
+ Vérifiez que votre compte utilisateur dispose d'autorisations de lecture et d'écriture à la fois pour le HubOnboarding binaire et pour la `libSecureStorageCertHandler.so` bibliothèque.
+ `secure_storage_cert_handler_interface.hpp`Conservez-le comme seul fichier d'en-tête public. Tous les autres fichiers d'en-tête doivent rester dans votre implémentation privée.
+ Vérifiez le nom de votre bibliothèque d'objets partagés. Lors de la compilation`libSecureStorageCertHandler.so`, le nom de fichier HubOnboarding peut nécessiter une version spécifique, telle que`libSecureStorageCertHandler.so.1.0`. Utilisez la `ldd` commande pour vérifier les dépendances des bibliothèques et créer des liens symboliques selon les besoins.
+ Si votre implémentation de la bibliothèque partagée comporte des dépendances externes, stockez-les dans un répertoire HubOnboarding accessible, tel qu'un `/usr/lib or the iotmi_common` répertoire.

### Utilisez un stockage sécurisé
<a name="managedintegrations-sdk-v2-cookbook-certhandler-usagehowto"></a>

Mettez à jour votre `iotmi_config.json` fichier en configurant à la fois `iot_claim_cert_path` et `iot_claim_pk_path` sur**SECURE\_STORAGE**.

```
{
  "ro": { 
    "iot_provisioning_method": "FLEET_PROVISIONING", 
    "iot_claim_cert_path": "SECURE_STORAGE",
    "iot_claim_pk_path": "SECURE_STORAGE", 
    "fp_template_name": "device-integration-example",
    "iot_endpoint_url": "[{{ACCOUNT-PREFIX}}]-ats.iot.{{AWS-REGION}}.amazonaws.com", 
    "SN": "1234567890", 
    "UPC": "1234567890" 
  },
  "rw": { 
    "iot_provisioning_state": "NOT_PROVISIONED"
  }
}
```