Guida introduttiva: Crittografare/decrittografare il testo con MIP SDK (C++)

Questa guida introduttiva illustra come usare più SDK di protezione MIP. Usando uno dei modelli di protezione elencati nell'argomento di avvio rapido precedente, si usa un gestore protezione per crittografare il testo ad hoc. La classe del gestore protezione espone varie operazioni per l'applicazione o la rimozione della protezione.

Prerequisiti

Se non è già stato fatto, assicurarsi di completare i prerequisiti seguenti prima di continuare:

Implementare una classe observer per monitorare l'oggetto gestore protezione

Analogamente all'osservatore implementato (per il profilo di protezione e il motore) nella guida introduttiva all'inizializzazione dell'applicazione, ora si implementa una classe observer per gli oggetti gestore protezione.

Creare un'implementazione di base per un osservatore del gestore protezione estendendo la classe dell'SDK mip::ProtectionHandler::Observer . L'osservatore viene creata un'istanza e usata in un secondo momento per monitorare le operazioni del gestore protezione.

  1. Aprire la soluzione di Visual Studio in uso nell'articolo precedente "Guida introduttiva: Elencare i modelli di protezione (C++)".

  2. Aggiungere una nuova classe al progetto, che genera automaticamente i file header/.h e implementation/.cpp:

    • Nel Esplora soluzioni fare di nuovo clic con il pulsante destro del mouse sul nodo del progetto, selezionare Aggiungi e quindi selezionare Classe.
    • Nella finestra di dialogo Aggiungi classe :
      • Nel campo Nome classe immettere "handler_observer". Si noti che i campi del file con estensione h e cpp vengono popolati automaticamente in base al nome immesso.
      • Al termine, fare clic sul pulsante OK .
  3. Dopo aver generato i file con estensione h e cpp per la classe , entrambi i file vengono aperti nelle schede Gruppo editor. Aggiornare ora ogni file per implementare la nuova classe observer:

    • Aggiornare "handler_observer.h" selezionando/eliminando la classe generata handler_observer . Non rimuovere le direttive del preprocessore generate dal passaggio precedente (#pragma, #include). Copiare/incollare quindi l'origine seguente nel file, dopo eventuali direttive del preprocessore esistenti:

      #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;
           };
      
      
    • Aggiornare "handler_observer.cpp" selezionando/eliminando l'implementazione della classe generata handler_observer . Non rimuovere le direttive del preprocessore generate dal passaggio precedente (#pragma, #include). Copiare/incollare quindi l'origine seguente nel file, dopo eventuali direttive del preprocessore esistenti:

      #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. Facoltativamente, usare CTRL+MAIUSC+B (Compila soluzione) per eseguire una compilazione/collegamento di test della soluzione per assicurarsi che venga compilata correttamente prima di continuare.

Aggiungere la logica per crittografare e decrittografare testo ad hoc

Aggiungere la logica per crittografare e decrittografare testo ad hoc usando l'oggetto motore protezione.

  1. Usando Esplora soluzioni, aprire il file con estensione cpp nel progetto che contiene l'implementazione del main() metodo .

  2. Aggiungere i #include e le direttive using seguenti, sotto le direttive esistenti corrispondenti, all'inizio del file:

      #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. Verso la fine del Main() corpo, in cui è stata interrotta la guida introduttiva precedente, inserire il codice seguente:

    //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. Verso la fine del blocco di arresto dell'applicazione main() creato nella prima guida introduttiva e aggiungere le righe seguenti per rilasciare le risorse del gestore:

     publishingHandler = nullptr;
     consumptionHandler = nullptr;
    
  5. Sostituire i valori segnaposto nel codice sorgente come indicato di seguito, usando costanti stringa:

    Segnaposto Valore
    <sample-text> Testo di esempio da proteggere, ad esempio: "cipher text".
    <Template-ID> ID modello da usare per proteggere il testo. Ad esempio: "bb7ed207-046a-4caf-9826-647cff56b990"

Compilare e testare l'applicazione

Compilare e testare l'applicazione client.

  1. Usare CTRL+MAIUSC+B (Compila soluzione) per compilare l'applicazione client. Se non sono presenti errori di compilazione, usare F5 (Avvia debug) per eseguire l'applicazione.

  2. Se il progetto viene compilato ed eseguito correttamente, l'applicazione richiede un token di accesso, ogni volta che l'SDK chiama il AcquireOAuth2Token() metodo. Come in precedenza nella guida introduttiva "Elenca modelli di protezione", eseguire lo script di PowerShell per acquisire ogni volta il token, usando i valori forniti per $authority e $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 . . .