다음을 통해 공유


빠른 시작: MIP SDK를 사용하여 텍스트 암호화/암호 해독(C++)

이 빠른 시작에서는 MIP Protection SDK를 더 많이 사용하는 방법을 보여 줍니다. 이전 빠른 시작에서 나열한 보호 템플릿 중 하나를 사용하여 보호 처리기를 사용하여 임시 텍스트를 암호화합니다. 보호 처리기 클래스는 보호를 적용/제거하기 위한 다양한 작업을 노출합니다.

필수 조건

아직 완료하지 않은 경우 계속하기 전에 다음 필수 조건을 완료해야 합니다.

  • 빠른 시작 완료: 먼저 시작 Visual Studio 솔루션을 빌드하는 보호 템플릿(C++)을 나열 하여 인증된 사용자가 사용할 수 있는 보호 템플릿을 나열합니다. 이 "텍스트 암호화/암호 해독" Quickstart는 이전 Quickstart를 기반으로 합니다.
  • 선택 사항: MIP SDK 개념에서 보호 처리기를 검토합니다.

보호 처리기 개체를 모니터링하는 관찰자 클래스 구현

애플리케이션 초기화 빠른 시작에서 구현한 관찰자(보호 프로필 및 엔진용)와 마찬가지로 이제 Protection 처리기 개체에 대한 관찰자 클래스를 구현합니다.

SDK mip::ProtectionHandler::Observer 의 클래스를 확장하여 보호 처리기 관찰자에 대한 기본 구현을 만듭니다. 관찰자는 인스턴스화되고 나중에 보호 처리기 작업을 모니터링하는 데 사용됩니다.

  1. 이전 "빠른 시작: 보호 템플릿 나열(C++)" 문서에서 작업한 Visual Studio 솔루션을 엽니다.

  2. 헤더/.h 및 구현/.cpp 파일을 모두 생성하는 새 클래스를 프로젝트에 추가합니다.

    • 솔루션 탐색기에서 프로젝트 노드를 다시 마우스 오른쪽 단추로 클릭하고 추가를 선택한 다음 클래스 선택합니다.
    • 클래스 추가 대화 상자에서 다음을 수행합니다.
      • 클래스 이름 필드에 "handler_observer"를 입력합니다. 입력한 이름에 따라 .h 파일.cpp 파일 필드가 모두 자동으로 채워집니다.
      • 완료되면 확인 단추를 클릭합니다.
  3. 클래스에 대한 .h 및 .cpp 파일을 생성한 후 두 파일이 모두 편집기 그룹 탭에서 열립니다. 이제 새 관찰자 클래스를 구현하도록 각 파일을 업데이트합니다.

    • "handler_observer 클래스를 선택/삭제하여 'handler_observer.h'를 업데이트합니다." 이전 단계(#pragma, #include)에서 생성된 전처리기 지시문을 제거하지 마세요. 그런 다음, 기존 전처리기 지시문 다음에 다음 소스를 복사하여 파일에 붙여넣습니다.

      #include <memory>
      #include "mip/protection/protection_engine.h"
      using std::shared_ptr;
      using std::exception_ptr;
      
      class ProtectionHandlerObserver final : public mip::ProtectionHandler::Observer {
           public:
           ProtectionHandlerObserver() { }
           void OnCreateProtectionHandlerSuccess(const shared_ptr<mip::ProtectionHandler>& protectionHandler, const shared_ptr<void>& context) override;
           void OnCreateProtectionHandlerFailure(const exception_ptr& Failure, const shared_ptr<void>& context) override;
           };
      
      
    • "handler_observer.cpp" 파일의 생성된 handler_observer 클래스 구현을 선택하거나 삭제하여 업데이트합니다. 이전 단계(#pragma, #include)에서 생성된 전처리기 지시문을 제거하지 마세요. 그런 다음, 기존 전처리기 지시문 다음에 다음 소스를 복사하여 파일에 붙여넣습니다.

      #include "handler_observer.h"
      using std::shared_ptr;
      using std::promise;
      using std::exception_ptr;
      
      void ProtectionHandlerObserver::OnCreateProtectionHandlerSuccess(
           const shared_ptr<mip::ProtectionHandler>& protectionHandler,const shared_ptr<void>& context) {
                auto createProtectionHandlerPromise = static_cast<promise<shared_ptr<mip::ProtectionHandler>>*>(context.get());
                createProtectionHandlerPromise->set_value(protectionHandler);
                };
      
      void ProtectionHandlerObserver::OnCreateProtectionHandlerFailure(
           const exception_ptr& Failure, const shared_ptr<void>& context) {
                auto createProtectionHandlerPromise = static_cast<promise<shared_ptr<mip::ProtectionHandler>>*>(context.get())
                createProtectionHandlerPromise->set_exception(Failure);
                };
      
      
  4. 필요에 따라 Ctrl+Shift+B(솔루션 빌드)를 사용하여 솔루션의 테스트 컴파일/링크를 실행하여 계속하기 전에 성공적으로 빌드되는지 확인합니다.

임시 텍스트를 암호화 및 암호 해독하는 논리 추가

보호 엔진 개체를 사용하여 임시 텍스트를 암호화하고 해독하는 논리를 추가합니다.

  1. 솔루션 탐색기를 사용하여 메서드 구현 main() 이 포함된 프로젝트에서 .cpp 파일을 엽니다.

  2. 파일 맨 위에 해당하는 기존 지시문 아래에 다음 #include 및 using 지시문을 추가합니다.

      #include "mip/protection/protection_descriptor_builder.h"
      #include "mip/protection_descriptor.h"
      #include "handler_observer.h"
    
      using mip::ProtectionDescriptor;
      using mip::ProtectionDescriptorBuilder;
      using mip::ProtectionHandler;
    
  3. 이전 빠른 시작에서 중단한 본문의 Main() 끝 부분에 다음 코드를 삽입합니다.

    //Encrypt/Decrypt text:
    string templateId = "<Template-ID>";//Template ID from previous QuickStart e.g. "bb7ed207-046a-4caf-9826-647cff56b990"
    string inputText = "<Sample-Text>";//Sample Text
    
    //Refer to ProtectionDescriptor docs for details on creating the descriptor
    auto descriptorBuilder = mip::ProtectionDescriptorBuilder::CreateFromTemplate(templateId);
    const std::shared_ptr<mip::ProtectionDescriptor>& descriptor = descriptorBuilder->Build();
    
    //Create Publishing settings using a descriptor
    mip::ProtectionHandler::PublishingSettings publishingSettings = mip::ProtectionHandler::PublishingSettings(descriptor);
    
    //Create a publishing protection handler using Protection Descriptor
    auto handlerObserver = std::make_shared<ProtectionHandlerObserver>();
    engine->CreateProtectionHandlerForPublishingAsync(publishingSettings, handlerObserver, pHandlerPromise);
    auto publishingHandler = pHandlerFuture.get();
    
    std::vector<uint8_t> inputBuffer(inputText.begin(), inputText.end());
    
    //Show action plan
    cout << "Applying Template ID " + templateId + " to: " << endl << inputText << endl;
    
    //Encrypt buffer using Publishing Handler
    std::vector<uint8_t> encryptedBuffer;
    encryptedBuffer.resize(static_cast<size_t>(publishingHandler->GetProtectedContentLength(inputText.size(), true)));
    
    publishingHandler->EncryptBuffer(0,
                          &inputBuffer[0],
                          static_cast<int64_t>(inputBuffer.size()),
                          &encryptedBuffer[0],
                          static_cast<int64_t>(encryptedBuffer.size()),
                          true);
    
    std::string encryptedText(encryptedBuffer.begin(), encryptedBuffer.end());
    cout << "Encrypted Text :" + encryptedText;
    
    //Show action plan
    cout << endl << "Decrypting string: " << endl << endl;
    
    //Generate publishing licence, so it can be used later to decrypt text.
    auto serializedPublishingLicense = publishingHandler->GetSerializedPublishingLicense();
    
    //Use same PL to decrypt the encryptedText.
    auto cHandlerPromise = std::make_shared<std::promise<std::shared_ptr<ProtectionHandler>>>();
    auto cHandlerFuture = cHandlerPromise->get_future();
    shared_ptr<ProtectionHandlerObserver> cHandlerObserver = std::make_shared<ProtectionHandlerObserver>();
    
    //Create consumption settings using serialised publishing licence.
    mip::ProtectionHandler::ConsumptionSettings consumptionSettings = mip::ProtectionHandler::ConsumptionSettings(serializedPublishingLicense);
    engine->CreateProtectionHandlerForConsumptionAsync(consumptionSettings, cHandlerObserver, cHandlerPromise);
    
    auto consumptionHandler = cHandlerFuture.get();
    
    //Use consumption handler to decrypt the text.
    std::vector<uint8_t> decryptedBuffer(static_cast<size_t>(encryptedText.size()));
    
    int64_t decryptedSize = consumptionHandler->DecryptBuffer(
         0,
         &encryptedBuffer[0],
         static_cast<int64_t>(encryptedBuffer.size()),
         &decryptedBuffer[0],
         static_cast<int64_t>(decryptedBuffer.size()),
         true);
    
    decryptedBuffer.resize(static_cast<size_t>(decryptedSize));
    
    std::string decryptedText(decryptedBuffer.begin(), decryptedBuffer.end());
    
    // Output decrypted content. Should match original input text.
    cout << "Decrypted Text :" + decryptedText << endl;
    
    
  4. main()의 끝부분에서 첫 번째 빠른 시작에서 만든 애플리케이션 종료 블록을 찾아 처리기 리소스를 해제하기 위해 아래 줄을 추가합니다.

     publishingHandler = nullptr;
     consumptionHandler = nullptr;
    
  5. 문자열 상수로 소스 코드의 자리 표시자 값을 다음과 같이 바꿉니다.

    자리 표시자 가치
    <샘플-텍스트> 보호하려는 샘플 텍스트(예: "cipher text".
    <Template-Id> 텍스트를 보호하는 데 사용할 템플릿 ID입니다. 예: "bb7ed207-046a-4caf-9826-647cff56b990"

애플리케이션 빌드 및 테스트

클라이언트 애플리케이션을 빌드하고 테스트합니다.

  1. Ctrl+Shift+B(솔루션 빌드)를 사용하여 클라이언트 애플리케이션을 빌드합니다. 빌드 오류가 없는 경우 F5(디버깅 시작)를 사용하여 애플리케이션을 실행합니다.

  2. 프로젝트가 성공적으로 빌드되고 실행되면 애플리케이션은 SDK가 메서드를 호출할 때마다 액세스 토큰을 묻는 메시지를 표시합니다 AcquireOAuth2Token() . 이전에 "보호 템플릿 나열" 빠른 시작에서 했던 것처럼 PowerShell 스크립트를 실행하여 매번 $authority 및 $resourceUrl 제공된 값을 사용하여 토큰을 획득합니다.

    *** Template List:
    Name: Confidential \ All Employees : a74f5027-f3e3-4c55-abcd-74c2ee41b607
    Name: Highly Confidential \ All Employees : bb7ed207-046a-4caf-9826-647cff56b990
    Name: Confidential : 174bc02a-6e22-4cf2-9309-cb3d47142b05
    Name: Contoso Employees Only : 667466bf-a01b-4b0a-8bbf-a79a3d96f720
    Applying Template ID bb7ed207-046a-4caf-9826-647cff56b990 to:
    <Sample-Text>
    Encrypted Text :y¬╩$Ops7Γ╢╖¢t
    Decrypting string:
    
    Run the PowerShell script to generate an access token using the following values, then copy/paste it below:
    Set $authority to: https://login.windows.net/common/oauth2/authorize
    Set $resourceUrl to: https://aadrm.com
    Sign in with user account: user1@tenant.onmicrosoft.com
    Enter access token: <paste-access-token-here>
    Press any key to continue . . .
    
    Run the PowerShell script to generate an access token using the following values, then copy/paste it below:
    Set $authority to: https://login.windows.net/94f69844-8d34-4794-bde4-3ac89ad2b664/oauth2/authorize
    Set $resourceUrl to: https://aadrm.com
    Sign in with user account: user1@tenant.onmicrosoft.com
    Enter access token: <paste-access-token-here>
    Press any key to continue . . .
    
    Decrypted Text :<Sample-Text>
    C:\MIP Sample Apps\ProtectionQS\Debug\ProtectionQS.exe (process 8252) exited with code 0.
    To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
    Press any key to close this window . . .