Inicio rápido: Cifrar o descifrar texto con el SDK de MIP (C++)

En este inicio rápido se muestra cómo usar más SDK de MIP Protection. Con una de las plantillas de protección que enumera en la guía de inicio rápido anterior, use un controlador de Protection para cifrar texto ad hoc. La clase de controlador de Protection expone varias operaciones para aplicar o quitar protección.

Requisitos previos

Si todavía no lo ha hecho, complete los siguientes requisitos previos antes de continuar:

Implementación de una clase de observador para supervisar el objeto controlador de Protection

De forma similar al observador que implementó (para el perfil y motor de Protection) en el inicio rápido de inicialización de la aplicación, ahora implementa una clase de observador para los objetos del controlador de Protection.

Cree una implementación básica para una clase de observador de Protection mediante la ampliación de la clase mip::ProtectionHandler::Observer del SDK. El observador se crea una instancia y se usa más adelante para supervisar las operaciones del controlador de protección.

  1. Abra la solución de Visual Studio que ha creado en el artículo anterior "Inicio rápido completo: Enumerar plantillas de protección (C++)".

  2. Agregue una clase nueva al proyecto, que genera de manera automática los archivos header/.h e implementation/.cpp:

    • En el Explorador de soluciones, vuelva a hacer clic con el botón derecho en el nodo del proyecto, seleccione Agregar y después Clase.
    • En el cuadro de diálogo Agregar clase:
      • En el campo Nombre de clase, escriba "handler_observer". Observe que los campos Archivo .h y Archivo .cpp se rellenan automáticamente, en función del nombre que escriba.
      • Cuando termine, haga clic en el botón Aceptar.
  3. Después de generar los archivos .h y .cpp para la clase, se abren en las pestañas del grupo de editores. Ahora actualice cada archivo para implementar la nueva clase de observador:

    • Actualice "handler_observer.h"; para ello, seleccione o elimine la clase handler_observer generada. No quite las directivas de preprocesador generadas por el paso anterior (#pragma, #include). Después, copie y pegue el siguiente código en el archivo, después de las directivas de preprocesador existentes:

      #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;
           };
      
      
    • Actualice "handler_observer.cpp"; para ello, seleccione o elimine la implementación de la clase handler_observer generada. No quite las directivas de preprocesador generadas por el paso anterior (#pragma, #include). Después, copie y pegue el siguiente código en el archivo, después de las directivas de preprocesador existentes:

      #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. Opcionalmente, presione Ctrl+Mayús+B (Compilar solución) a fin de ejecutar una compilación o vínculo de prueba de la solución, para asegurarse de que se compila correctamente antes de continuar.

Incorporación de lógica para cifrar y descifrar texto ad hoc

Agregue lógica para cifrar y descifrar texto ad hoc con el objeto motor de Protection.

  1. Con el Explorador de soluciones, abra el archivo .cpp del proyecto que contiene la implementación del método main().

  2. Agregue las siguientes directivas #include y using, debajo de las directivas existentes correspondientes, en la parte superior del archivo:

      #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. Hacia la parte final del cuerpo de Main(), donde lo ha dejado en el inicio rápido anterior, inserte el código siguiente:

    //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. Hacia el final de main(), busque el bloque de cierre de la aplicación creado en el primer inicio rápido y agregue la líneas de controlador siguientes para liberar recursos de controlador:

     publishingHandler = nullptr;
     consumptionHandler = nullptr;
    
  5. Reemplace los valores de marcador de posición en el código fuente que se muestra a continuación con constantes de cadena:

    Marcador Valor
    <sample-text> Texto de ejemplo que le gustaría proteger, por ejemplo: "cipher text".
    <Template-Id> Identificador de plantilla que le gustaría usar para proteger el texto. Por ejemplo: "bb7ed207-046a-4caf-9826-647cff56b990"

Compilar y probar la aplicación

Compile y pruebe la aplicación cliente.

  1. Presione Ctrl+Mayús+B (Compilar solución) para compilar la aplicación cliente. Si no hay errores de compilación, presione F5 (Iniciar depuración) para ejecutar la aplicación.

  2. Si el proyecto se compila y se ejecuta correctamente, la aplicación solicita un token de acceso cada vez que el SDK llama al método AcquireOAuth2Token(). Como hizo anteriormente en la guía de inicio rápido "Enumerar plantillas de protección (C++)", ejecute el script de PowerShell para adquirir el token cada vez, con los valores proporcionados para $authority y $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 . . .