

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 보안 스토리지를 위한 사용자 지정 인증서 핸들러 생성
<a name="managedintegrations-sdk-v2-cookbook-certhandler"></a>

디바이스 인증서 관리는 관리형 통합 허브를 온보딩할 때 매우 중요합니다. 인증서는 기본적으로 파일 시스템에 저장되지만 보안 강화 및 유연한 자격 증명 관리를 위해 사용자 지정 인증서 핸들러를 생성할 수 있습니다.

관리형 통합 엔드 디바이스 SDK는 공유 객체(.so) 라이브러리로 구현할 수 있는 보안 스토리지 인터페이스에 대한 인증서 핸들러를 제공합니다. 인증서를 읽고 쓰도록 보안 스토리지 구현을 구축한 다음 런타임에 라이브러리 파일을 HubOnboarding 프로세스에 연결합니다.

## API 정의 및 구성 요소
<a name="managedintegrations-sdk-v2-cookbook-certhandler-api"></a>

다음 `secure_storage_cert_handler_interface.hpp` 파일을 검토하여 구현을 위한 API 구성 요소 및 요구 사항을 이해합니다.

**Topics**
+ [API 정의](#managedintegrations-sdk-v2-cookbook-certhandler-apidef)
+ [핵심 구성 요소](#managedintegrations-sdk-v2-cookbook-certhandler-apicomp)

### API 정의
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apidef"></a>

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

### 핵심 구성 요소
<a name="managedintegrations-sdk-v2-cookbook-certhandler-apicomp"></a>
+ CERT\_TYPE\_T - 허브에 있는 다양한 유형의 인증서입니다.
  + 클레임 - 원래 허브에 있는 클레임 인증서는 영구 인증서로 교환됩니다.
  + DHA - 지금은 사용되지 않습니다.
  + 영구 - 관리형 통합 엔드포인트와 연결하기 위한 영구 인증서입니다.
+ read\_cert\_and\_private\_key - (FUNCTION TO BE IMPLEMENTED) 참조 입력에 대한의 인증서 및 키 값을 읽습니다. 이 함수는 CLAIM 및 PERMANENT 인증서를 모두 읽을 수 있어야 하며 위에서 언급한 인증서 유형으로 구분됩니다.
+ write\_permanent\_cert\_and\_private\_key - (FUNCTION TO BE IMPLEMENTED) 영구 인증서와 키 값을 원하는 위치에 씁니다.

## 예제 빌드
<a name="managedintegrations-sdk-v2-cookbook-exbuild"></a>

내부 구현 헤더를 퍼블릭 인터페이스(`secure_storage_cert_handler_interface.hpp`)와 분리하여 깨끗한 프로젝트 구조를 유지합니다. 이러한 분리를 통해 인증서 핸들러를 구축하는 동안 퍼블릭 및 프라이빗 구성 요소를 관리할 수 있습니다.

**참고**  
공개`secure_storage_cert_handler_interface.hpp`로 선언합니다.

**Topics**
+ [프로젝트 구조](#managedintegrations-sdk-v2-cookbook-proj)
+ [인터페이스 상속](#managedintegrations-sdk-v2-cookbook-interface)
+ [구현](#managedintegrations-sdk-v2-cookbook-interimpl)
+ [CMakeList.txt](#managedintegrations-sdk-v2-cookbook-cmakelist)

### 프로젝트 구조
<a name="managedintegrations-sdk-v2-cookbook-proj"></a>

![관리형 통합 인증서 핸들러 프로젝트 구조입니다.](http://docs.aws.amazon.com/ko_kr/iot-mi/latest/devguide/images/iot-managedintegrations-cert-handler-projstruct.png)


### 인터페이스 상속
<a name="managedintegrations-sdk-v2-cookbook-interface"></a>

인터페이스를 상속하는 구체적인 클래스를 생성합니다. 빌드 시 프라이빗 헤더와 퍼블릭 헤더를 쉽게 구분할 수 있도록 별도의 디렉터리에서이 헤더 파일과 기타 파일을 숨깁니다.

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

### 구현
<a name="managedintegrations-sdk-v2-cookbook-interimpl"></a>

위에 정의된 스토리지 클래스를 구현합니다`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;
  }
```

인터페이스에 정의된 팩토리 함수를 구현합니다`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
      )
```

## 사용법
<a name="managedintegrations-sdk-v2-cookbook-certhandler-usage"></a>

컴파일 후 `libSecureStorageCertHandler.so` 공유 객체 라이브러리 파일과 관련 심볼 링크가 있습니다. 라이브러리 파일과 심볼 링크를 모두 HubOnboarding 바이너리에서 예상되는 라이브러리 위치에 복사합니다.

**Topics**
+ [주요 고려 사항](#managedintegrations-sdk-v2-cookbook-certhandler-useconsider)
+ [보안 스토리지 사용](#managedintegrations-sdk-v2-cookbook-certhandler-usagehowto)

### 주요 고려 사항
<a name="managedintegrations-sdk-v2-cookbook-certhandler-useconsider"></a>
+ 사용자 계정에 HubOnboarding 바이너리와 `libSecureStorageCertHandler.so` 라이브러리 모두에 대한 읽기 및 쓰기 권한이 있는지 확인합니다.
+ `secure_storage_cert_handler_interface.hpp`를 유일한 퍼블릭 헤더 파일로 유지합니다. 다른 모든 헤더 파일은 프라이빗 구현에 남아 있어야 합니다.
+ 공유 객체 라이브러리 이름을 확인합니다. 를 빌드하는 동안 `libSecureStorageCertHandler.so` HubOnboarding은 파일 이름에와 같은 특정 버전이 필요할 수 있습니다`libSecureStorageCertHandler.so.1.0`. `ldd` 명령을 사용하여 라이브러리 종속성을 확인하고 필요에 따라 심볼 링크를 생성합니다.
+ 공유 라이브러리 구현에 외부 종속성이 있는 경우 디렉터리와 같이 HubOnboarding이 액세스할 수 있는 `/usr/lib or the iotmi_common` 디렉터리에 저장합니다.

### 보안 스토리지 사용
<a name="managedintegrations-sdk-v2-cookbook-certhandler-usagehowto"></a>

`iot_claim_cert_path` 및를 모두 `iot_claim_pk_path`로 설정하여 `iotmi_config.json` 파일을 업데이트합니다**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"
  }
}
```