Rövid útmutató: Szöveg titkosítása/visszafejtése a MIP SDK használatával (C++)

Ez a rövid útmutató bemutatja, hogyan használhat több MIP Protection SDK-t. Az előző rövid útmutatóban felsorolt védelmi sablonok egyikével egy Védelmi kezelővel titkosíthatja az alkalmi szövegeket. A Védelmi kezelő osztály különböző műveleteket tesz elérhetővé a védelem alkalmazásához/eltávolításához.

Előfeltételek

Ha még nem tette meg, a folytatás előtt mindenképpen végezze el a következő előfeltételeket:

Megfigyelőosztály implementálása a Védelmi kezelő objektum figyeléséhez

Az alkalmazás inicializálásának rövid útmutatójában (a Védelmi profilhoz és a motorhoz) implementált megfigyelőhöz hasonlóan most egy megfigyelőosztályt implementál a Védelmi kezelő objektumokhoz.

Hozzon létre egy alapszintű implementációt egy Védelmi kezelő megfigyelő számára az SDK osztályának mip::ProtectionHandler::Observer kibővítésével. A megfigyelő példányosítása és használata később történik a Védelmi kezelő műveleteinek figyeléséhez.

  1. Nyissa meg az előző "Rövid útmutató: Listavédelmi sablonok (C++)" című cikkben dolgozott Visual Studio-megoldást.

  2. Adjon hozzá egy új osztályt a projekthez, amely a fejléc/.h és a implementáció/.cpp fájlokat is létrehozza Önnek:

    • A Megoldáskezelő kattintson ismét a jobb gombbal a projektcsomópontra, válassza a Hozzáadás, majd az Osztály lehetőséget.
    • Az Osztály hozzáadása párbeszédpanelen:
      • Az Osztálynév mezőbe írja be a "handler_observer" kifejezést. Figyelje meg, hogy a .h fájl és a .cpp fájlmező is automatikusan ki lesz töltve a megadott név alapján.
      • Ha végzett, kattintson az OK gombra.
  3. Az osztály .h és .cpp fájljainak létrehozása után mindkét fájl megnyílik a Szerkesztőcsoport lapon. Most frissítse az egyes fájlokat az új megfigyelői osztály implementálásához:

    • Frissítse a "handler_observer.h" értéket a létrehozott handler_observer osztály kiválasztásával/törlésével. Ne távolítsa el az előző lépés (#pragma, #include) által létrehozott előprocesszor-irányelveket. Ezután másolja/illessze be a következő forrást a fájlba a meglévő előfeldolgozási irányelvek után:

      #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;
           };
      
      
    • Frissítse a "handler_observer.cpp" fájlt a létrehozott handler_observer osztály implementációjának kiválasztásával/törlésével. Ne távolítsa el az előző lépés (#pragma, #include) által létrehozott előprocesszor-irányelveket. Ezután másolja/illessze be a következő forrást a fájlba a meglévő előfeldolgozási irányelvek után:

      #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. Ha szeretné, a Ctrl+Shift+B (Build Solution) billentyűkombinációval futtathatja a megoldás fordítását/csatolását, hogy a folytatás előtt meggyőződjön arról, hogy a buildelés sikeres.

Logika hozzáadása alkalmi szövegek titkosításához és visszafejtéséhez

Adjon hozzá logikát az alkalmi szövegek titkosításához és visszafejtéséhez a Védelmi motor objektum használatával.

  1. A Megoldáskezelő használatával nyissa meg a metódus implementálását tartalmazó .cpp fájlt a main() projektben.

  2. Adja hozzá a következő #include és a megfelelő meglévő irányelvek alá tartozó irányelveket a fájl tetején:

      #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. A törzs vége Main() felé, ahol az előző rövid útmutatóban abbahagyta, szúrja be a következő kódot:

    //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. Az első rövid útmutatóban létrehozott alkalmazásleállítási blokk megkeresésének main() vége felé adja hozzá az alábbi sorokat a kezelőerőforrások felszabadításához:

     publishingHandler = nullptr;
     consumptionHandler = nullptr;
    
  5. Cserélje le a helyőrző értékeket a forráskódban az alábbiak szerint, sztringállandók használatával:

    Helyőrző Value
    <mintaszöveg> A védeni kívánt mintaszöveg, például: "cipher text".
    <Sablonazonosító> A szöveg védelméhez használni kívánt sablonazonosító. Például: "bb7ed207-046a-4caf-9826-647cff56b990"

Az alkalmazás létrehozása és tesztelése

Hozza létre és tesztelje az ügyfélalkalmazást.

  1. A Ctrl+Shift+B (Build Solution) billentyűkombinációval hozhatja létre az ügyfélalkalmazást. Ha nincsenek buildelési hibái, használja az F5 (Hibakeresés indítása) lehetőséget az alkalmazás futtatásához.

  2. Ha a projekt sikeresen épül és fut, az alkalmazás hozzáférési jogkivonatot kér minden alkalommal, amikor az SDK meghívja a metódust AcquireOAuth2Token() . Ahogyan korábban a "Listavédelmi sablonok" rövid útmutatóban is tette, futtassa a PowerShell-szkriptet a jogkivonat minden alkalommal történő beszerzéséhez a $authority és $resourceUrl megadott értékek használatával.

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