

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Crie um manipulador de certificados personalizado para armazenamento seguro
<a name="managedintegrations-sdk-v2-cookbook-certhandler"></a>

O gerenciamento de certificados de dispositivos é crucial ao integrar o hub de integrações gerenciadas. Embora os certificados sejam armazenados no sistema de arquivos por padrão, você pode criar um manipulador de certificados personalizado para maior segurança e gerenciamento flexível de credenciais.

O SDK de dispositivo final de integrações gerenciadas fornece um manipulador de certificados para proteger a interface de armazenamento que você pode implementar como uma biblioteca de objetos compartilhados (.so). Crie sua implementação de armazenamento seguro para ler e gravar certificados e, em seguida, vincule o arquivo da biblioteca ao HubOnboarding processo em tempo de execução.

## Definição e componentes da API
<a name="managedintegrations-sdk-v2-cookbook-certhandler-api"></a>

Analise o `secure_storage_cert_handler_interface.hpp` arquivo a seguir para entender os componentes e os requisitos da API para sua implementação

**Topics**
+ [Definição de API](#managedintegrations-sdk-v2-cookbook-certhandler-apidef)
+ [Componentes principais](#managedintegrations-sdk-v2-cookbook-certhandler-apicomp)

### Definição de API
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apidef"></a>

**Conteúdo 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 principais
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apicomp"></a>
+ CERT\$1TYPE\$1T - diferentes tipos de certificados no hub.
  + RECLAMAÇÃO - o certificado de reclamação, originalmente no hub, será trocado por um certificado permanente.
  + DHA - não usado por enquanto.
  + PERMANENTE - certificado permanente para conexão com o endpoint de integrações gerenciadas.
+ read\$1cert\$1and\$1private\$1key - (FUNÇÃO A SER IMPLEMENTADA) Lê o certificado e o valor da chave na entrada de referência. Essa função deve ser capaz de ler tanto o certificado CLAIM quanto o PERMANENT e é diferenciada pelo tipo de certificado mencionado acima.
+ write\$1permanent\$1cert\$1and\$1private\$1key - (FUNÇÃO A SER IMPLEMENTADA) grava o certificado permanente e o valor da chave no local desejado.

## Exemplo de construção
<a name="managedintegrations-sdk-v2-cookbook-exbuild"></a>

Separe seus cabeçalhos de implementação internos da interface pública (`secure_storage_cert_handler_interface.hpp`) para manter uma estrutura de projeto limpa. Com essa separação, você pode gerenciar componentes públicos e privados enquanto cria seu manipulador de certificados.

**nota**  
Declare `secure_storage_cert_handler_interface.hpp` como público.

**Topics**
+ [Estrutura do projeto](#managedintegrations-sdk-v2-cookbook-proj)
+ [Herde a interface](#managedintegrations-sdk-v2-cookbook-interface)
+ [Implementação](#managedintegrations-sdk-v2-cookbook-interimpl)
+ [CMakeList.txt](#managedintegrations-sdk-v2-cookbook-cmakelist)

### Estrutura do projeto
<a name="managedintegrations-sdk-v2-cookbook-proj"></a>

![\[Estrutura do projeto do manipulador de certificados de integrações gerenciadas.\]](http://docs.aws.amazon.com/pt_br/iot-mi/latest/devguide/images/iot-managedintegrations-cert-handler-projstruct.png)


### Herde a interface
<a name="managedintegrations-sdk-v2-cookbook-interface"></a>

Crie uma classe concreta que herde a interface. Oculte esse arquivo de cabeçalho e outros arquivos em um diretório separado para que os cabeçalhos privados e públicos possam ser diferenciados facilmente durante a criação.

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

### Implementação
<a name="managedintegrations-sdk-v2-cookbook-interimpl"></a>

Implemente a classe de armazenamento definida acima,`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 a função de fábrica definida na 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
      )
```

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

Após a compilação, você terá um arquivo de biblioteca de objetos `libSecureStorageCertHandler.so` compartilhados e seus links simbólicos associados. Copie o arquivo da biblioteca e os links simbólicos para a localização da biblioteca esperada pelo HubOnboarding binário.

**Topics**
+ [Considerações importantes](#managedintegrations-sdk-v2-cookbook-certhandler-useconsider)
+ [Use armazenamento seguro](#managedintegrations-sdk-v2-cookbook-certhandler-usagehowto)

### Considerações importantes
<a name="managedintegrations-sdk-v2-cookbook-certhandler-useconsider"></a>
+ Verifique se sua conta de usuário tem permissões de leitura e gravação para o HubOnboarding binário e a `libSecureStorageCertHandler.so` biblioteca.
+ Mantenha `secure_storage_cert_handler_interface.hpp` como seu único arquivo de cabeçalho público. Todos os outros arquivos de cabeçalho devem permanecer em sua implementação privada.
+ Verifique o nome da sua biblioteca de objetos compartilhados. Enquanto você cria`libSecureStorageCertHandler.so`, HubOnboarding pode exigir uma versão específica no nome do arquivo, como. `libSecureStorageCertHandler.so.1.0` Use o `ldd` comando para verificar as dependências da biblioteca e criar links simbólicos conforme necessário.
+ Se sua implementação da biblioteca compartilhada tiver dependências externas, armazene-as em um diretório que HubOnboarding possa ser acessado, como `/usr/lib or the iotmi_common` diretório.

### Use armazenamento seguro
<a name="managedintegrations-sdk-v2-cookbook-certhandler-usagehowto"></a>

Atualize seu `iotmi_config.json` arquivo configurando `iot_claim_cert_path` e `iot_claim_pk_path` para**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"
  }
}
```