クイック スタート: MIP SDK を使用してテキストを暗号化および暗号化解除する (C++)

このクイック スタートでは、より多くの MIP Protection SDK を使用する方法について説明します。 前のクイック スタートで示した保護テンプレートのいずれかを使用して、保護ハンドラーを使用してアドホック テキストを暗号化します。 Protection ハンドラー クラスは、保護を適用および削除するためのさまざまな操作を公開します。

前提条件

まだ行っていない場合は、続行する前に次の前提条件を満たしていることを確認してください。

オブザーバー クラスを実装して保護ハンドラー オブジェクトを監視する

アプリケーションの初期化クイックスタートで保護プロファイルとエンジンに実装したオブザーバーと同様に、保護ハンドラー オブジェクトのオブザーバー クラスを実装します。

SDK の mip::ProtectionHandler::Observer クラスを拡張して、保護ハンドラー オブザーバーの基本的な実装を作成します。 SDK は後でオブザーバーをインスタンス化して使用し、保護ハンドラーの操作を監視します。

  1. 前の「クイック スタート: リスト保護テンプレート (C++)」の記事で作業したVisual Studio ソリューションを開きます。

  2. プロジェクトに新しいクラスを追加すると、ヘッダー (.h) ファイルと実装 (.cpp) ファイルの両方が生成されます。

    • ソリューション エクスプローラーで、プロジェクト ノードをもう一度右クリックし、[追加] を選択して、[クラス] を選択します。
    • [ クラスの追加 ] ダイアログで、次の手順を実行します。
      • [ クラス名] フィールドに「 handler_observer」と入力します。 入力した名前に基づいて、Visual Studio によって .h ファイル フィールドと .cpp ファイル フィールドの両方に自動的に入力されることに注意してください。
      • 終わったら、 [OK] を選択します。
  3. クラスの .h ファイルと .cpp ファイルを生成した後、Visual Studioエディター グループ タブで両方のファイルを開きます。 次に、新しいオブザーバー クラスを実装するように各ファイルを更新します。

    • 生成された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_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>();
    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. 次の文字列定数を使用して、ソース コードのプレースホルダー値を置き換えます。

    プレースホルダー 価値
    <サンプルテキスト> 保護するサンプル テキスト (例: "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.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 . . .
    

次のステップ