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

這個快速入門指南會教你如何使用更多 MIP 保護 SDK。 透過你在前述快速入門中列出的保護範本,你可以使用保護處理程式來加密臨時文字。 保護處理類別會揭露各種用於套用與移除保護的操作。

先決條件

如果你還沒完成,請務必在繼續前完成以下先決條件:

實作一個觀察者類別來監控保護處理物件

就像你在應用程式初始化快速啟動中為保護設定檔和引擎實作的觀察者一樣,現在你為保護處理物件實作了一個觀察者類別。

透過擴充 SDK 的 mip::ProtectionHandler::Observer 類別,建立保護處理常式觀察器的基本實作。 SDK 實例化並使用觀察器來監控保護處理程序的操作。

  1. 打開你在之前「快速入門:清單保護範本(C++)」文章中參與的 Visual Studio 解決方案。

  2. 為你的專案新增一個類別,該類別會同時產生標頭(.h)和實作(.cpp)檔案:

    • 在 方案總管 中,再次右鍵點擊專案節點,選擇新增,然後選擇類別。
    • 在 [ 新增類別 ] 對話框中:
      • 在 類別名稱 欄位輸入 handler_observer。 注意Visual Studio會根據你輸入的名稱自動填入 .h 檔案和 .cpp 檔案欄位。
      • 完成後,選取 [確定]。
  3. 產生 .h 和 .cpp 檔案後,Visual Studio 會在編輯器群組分頁中開啟兩個檔案。 現在更新每個檔案以實作新的觀察者類別:

    • 選取並刪除產生的 handler_observer.h 類別,以更新 handler_observer。 不要 移除前一步產生的預處理器指令(#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_descriptor_builder.h"
      #include "mip/protection_descriptor.h"
      #include "handler_observer.h"
    
      using mip::ProtectionDescriptor;
      using mip::ProtectionDescriptorBuilder;
      using mip::ProtectionHandler;
    
  3. 在 Main() body 的結尾附近,也就是你在上一個快速入門中停下的地方,插入下列程式碼:

    //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>();
    auto pHandlerPromise = std::make_shared<std::promise<std::shared_ptr<ProtectionHandler>>>();
    auto pHandlerFuture = pHandlerPromise->get_future();
    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 license, 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 serialized publishing license.
    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. 請以以下字串常數替換原始碼中的佔位值:

    Placeholder 值
    <範例文字> 你想保護的範例文字,例如: "cipher text"
    <模板-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.microsoftonline.com/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.microsoftonline.com/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 . . .
    

下一步