

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Cree un controlador de certificados personalizado para un almacenamiento seguro
<a name="managedintegrations-sdk-v2-cookbook-certhandler"></a>

La gestión de los certificados de los dispositivos es crucial a la hora de incorporar el centro de integraciones gestionadas. Si bien los certificados se almacenan en el sistema de archivos de forma predeterminada, puede crear un controlador de certificados personalizado para mejorar la seguridad y una administración flexible de las credenciales.

El SDK para dispositivos finales de integraciones administradas proporciona un controlador de certificados para proteger la interfaz de almacenamiento que puede implementar como una biblioteca de objetos compartidos (.so). Cree su implementación de almacenamiento seguro para leer y escribir certificados y, a continuación, vincule el archivo de la biblioteca al HubOnboarding proceso en tiempo de ejecución.

## Definición y componentes de la API
<a name="managedintegrations-sdk-v2-cookbook-certhandler-api"></a>

Revise el siguiente `secure_storage_cert_handler_interface.hpp` archivo para comprender los componentes y requisitos de la API para su implementación

**Topics**
+ [Definición de API](#managedintegrations-sdk-v2-cookbook-certhandler-apidef)
+ [Componentes principales](#managedintegrations-sdk-v2-cookbook-certhandler-apicomp)

### Definición de API
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apidef"></a>

**Contenido 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
```

### Componentes principales
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apicomp"></a>
+ CERT\$1TYPE\$1T: diferentes tipos de certificados en el hub.
  + RECLAMACIÓN: el certificado de reclamación que originalmente estaba en el centro se cambiará por un certificado permanente.
  + DHA: no se ha utilizado por el momento.
  + PERMANENTE: certificado permanente para conectarse con el punto final de integraciones gestionadas.
+ read\$1cert\$1and\$1private\$1key - (FUNCIÓN A IMPLEMENTAR) Lee el certificado y el valor de la clave en la entrada de referencia. Esta función debe poder leer tanto el certificado CLAIM como el PERMANENTE, y se diferencia por el tipo de certificado mencionado anteriormente.
+ write\$1permanent\$1cert\$1and\$1private\$1key: (FUNCIÓN POR IMPLEMENTAR) escribe el certificado permanente y el valor de la clave en la ubicación deseada.

## Ejemplo de compilación
<a name="managedintegrations-sdk-v2-cookbook-exbuild"></a>

Separe los encabezados de implementación internos de la interfaz pública (`secure_storage_cert_handler_interface.hpp`) para mantener una estructura de proyecto limpia. Con esta separación, puede administrar los componentes públicos y privados mientras crea su controlador de certificados.

**nota**  
`secure_storage_cert_handler_interface.hpp`Declárelo como público.

**Topics**
+ [Estructura del proyecto](#managedintegrations-sdk-v2-cookbook-proj)
+ [Herede la interfaz](#managedintegrations-sdk-v2-cookbook-interface)
+ [Implementación](#managedintegrations-sdk-v2-cookbook-interimpl)
+ [CMakeList.txt](#managedintegrations-sdk-v2-cookbook-cmakelist)

### Estructura del proyecto
<a name="managedintegrations-sdk-v2-cookbook-proj"></a>

![\[Estructura del proyecto del gestor de certificados de integraciones gestionadas.\]](http://docs.aws.amazon.com/es_es/iot-mi/latest/devguide/images/iot-managedintegrations-cert-handler-projstruct.png)


### Herede la interfaz
<a name="managedintegrations-sdk-v2-cookbook-interface"></a>

Cree una clase concreta que herede la interfaz. Oculte este archivo de encabezado y otros archivos en un directorio independiente para que los encabezados privados y públicos se puedan diferenciar fácilmente al crear.

```
#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
```

### Implementación
<a name="managedintegrations-sdk-v2-cookbook-interimpl"></a>

Implemente la clase de almacenamiento definida anteriormente,`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;
  }
```

Implemente la función de fábrica definida en la interfaz,`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
      )
```

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

Tras la compilación, dispondrá de un archivo de biblioteca de objetos `libSecureStorageCertHandler.so` compartido y sus enlaces simbólicos asociados. Copie el archivo de la biblioteca y los enlaces simbólicos en la ubicación de la biblioteca que espera el HubOnboarding binario.

**Topics**
+ [Consideraciones clave](#managedintegrations-sdk-v2-cookbook-certhandler-useconsider)
+ [Utilice un almacenamiento seguro](#managedintegrations-sdk-v2-cookbook-certhandler-usagehowto)

### Consideraciones clave
<a name="managedintegrations-sdk-v2-cookbook-certhandler-useconsider"></a>
+ Compruebe que su cuenta de usuario tenga permisos de lectura y escritura tanto para el archivo HubOnboarding binario como para la `libSecureStorageCertHandler.so` biblioteca.
+ Manténgalo `secure_storage_cert_handler_interface.hpp` como único archivo de encabezado público. Todos los demás archivos de encabezado deben permanecer en su implementación privada.
+ Verifica el nombre de la biblioteca de objetos compartidos. Mientras compilas`libSecureStorageCertHandler.so`, HubOnboarding es posible que necesites una versión específica en el nombre del archivo, por ejemplo`libSecureStorageCertHandler.so.1.0`. Usa el `ldd` comando para comprobar las dependencias de la biblioteca y crear enlaces simbólicos según sea necesario.
+ Si la implementación de la biblioteca compartida tiene dependencias externas, guárdelas en un directorio al que HubOnboarding pueda acceder, como `/usr/lib or the iotmi_common` un directorio.

### Utilice un almacenamiento seguro
<a name="managedintegrations-sdk-v2-cookbook-certhandler-usagehowto"></a>

Actualice `iotmi_config.json` el archivo configurando ambos `iot_claim_cert_path` valores como y `iot_claim_pk_path`**SECURE\$1STORAGE**.

```
{
  "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"
  }
}
```