共用方式為


快速入門:使用 MIP SDK 加密/解密文字 (C++)

本快速入門說明如何使用更多 MIP 保護 SDK。 使用您在上一個快速入門中列出的其中一個保護範本,您可以使用保護處理常式來加密臨機操作文字。 Protection 處理常式類別會公開套用/移除保護的各種作業。

必要條件

如果您尚未完成,請務必先完成下列必要條件,再繼續進行:

  • 完成 快速入門:先列出保護範本 (C++) 以建置入門 Visual Studio 解決方案,以列出已驗證使用者可用的保護範本。 本「加密/解密文字」快速入門是以上一個快速入門為基礎。
  • 選擇性:檢閱 MIP SDK 概念中的保護處理常式。

實作觀察者類別來監視 Protection 處理常式物件

類似于您在應用程式初始化快速入門中實作的觀察者(針對保護設定檔和引擎),現在您會為 Protection 處理常式物件實作觀察者類別。

藉由擴充 SDK 的 類別,為保護處理常式觀察者建立基本實作 mip::ProtectionHandler::Observer 。 觀察者會具現化及稍後使用,以監視保護處理常式作業。

  1. 開啟您在先前的「快速入門:清單保護範本(C++)》文章中處理過的 Visual Studio 解決方案。

  2. 將新類別新增至您的專案,這會為您產生標頭/.h 和 implementation/.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 類別實作,以更新 「handler_observer.cpp」。 請勿 移除上一個步驟所產生的預處理器指示詞(#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. 使用字串常數取代原始程式碼中的預留位置值:

    預留位置
    <sample-text> 您想要保護的範例文字,例如: "cipher text"
    <Template-Id> 您想要用來保護文字的範本識別碼。 例如:"bb7ed207-046a-4caf-9826-647cff56b990"

建置及測試應用程式

建置及測試用戶端應用程式。

  1. 使用 Ctrl+Shift+B ( 建置解決方案 )來建置用戶端應用程式。 如果您沒有建置錯誤,請使用 F5 ( 開始偵錯 ) 來執行應用程式。

  2. 如果您的專案建置並成功執行,應用程式會在每次 SDK 呼叫您的 AcquireOAuth2Token() 方法時,提示輸入存取權杖。 如同您先前在「清單保護範本」快速入門中所做的,請使用針對$authority和$resourceUrl提供的值,執行 PowerShell 腳本以每次取得權杖。

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