Início Rápido: Criptografar e descriptografar texto usando o SDK do MIP (C++)

Este guia de início rápido mostra como usar mais os SDKs de Proteção do MIP. Ao usar um dos modelos de proteção listados no guia de início rápido anterior, você usa um manipulador de proteção para criptografar texto ad hoc. A classe de manipulador Proteção expõe várias operações para aplicar e remover a proteção.

Pré-requisitos

Caso ainda não tenha feito isso, certifique-se de concluir os seguintes pré-requisitos antes de continuar:

Implementar uma classe de observador para monitorar o objeto do manipulador de proteção

Semelhante ao observador que você implementou (para o perfil e mecanismo Proteção) no Início Rápido de inicialização de aplicativo, agora você implementa uma classe de observador para objetos de manipulador de Proteção.

Crie uma implementação básica para um observador de manipulador de proteção estendendo a classe mip::ProtectionHandler::Observer do SDK. O SDK instancia e usa o observador posteriormente para monitorar as operações do Protection handler.

  1. Abra a solução do Visual Studio na qual você trabalhou no artigo anterior "Início Rápido: Listar modelos de proteção (C++)".

  2. Adicione uma nova classe ao projeto, que gera os arquivos de cabeçalho (.h) e implementação (.cpp) para você:

    • Em Gerenciador de Soluções, clique com o botão direito do mouse no nó do projeto novamente, selecione Adicionar e selecione Classe.
    • Na caixa de diálogo Adicionar Classe :
      • No campo Nome da Classe , insira handler_observer. Observe que Visual Studio preenche automaticamente os campos de arquivo .h e .cpp com base no nome inserido.
      • Ao terminar, selecione OK.
  3. Depois de gerar os arquivos .h e .cpp para a classe, Visual Studio abre os dois arquivos nas guias Grupo do Editor. Agora atualize cada arquivo para implementar sua nova classe de observador:

    • Atualize handler_observer.h selecionando e excluindo a classe gerada handler_observer . Não remova as diretivas de pré-processador que a etapa anterior gerou (#pragma, #include). Em seguida, copie e cole a seguinte fonte no arquivo após quaisquer diretivas de pré-processador 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;
           };
      
      
    • Atualize handler_observer.cpp selecionando e excluindo a implementação de classe gerada handler_observer . Não remova as diretivas de pré-processador que a etapa anterior gerou (#pragma, #include). Em seguida, copie e cole a seguinte fonte no arquivo após quaisquer diretivas de pré-processador 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, use Ctrl+Shift+B (Build Solution) para executar uma compilação de teste e um link de sua solução para verificar se ela é compilada com êxito antes de continuar.

Adicionar lógica para criptografar e descriptografar texto ad hoc

Adicione lógica para criptografar e descriptografar o texto ad hoc usando o objeto do mecanismo de proteção.

  1. Usando o Gerenciador de Soluções, abra o arquivo .cpp em seu projeto que contém a implementação do main() método.

  2. Adicione as seguintes diretivas #include e using abaixo das diretivas correspondentes já existentes no início do arquivo:

      #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. No final do corpo de Main(), onde você parou no Início Rápido anterior, insira o seguinte código:

    //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. No final, localize o bloco de desligamento do main()aplicativo que o primeiro início rápido criou e adicione as seguintes linhas aos recursos do manipulador de lançamento:

     publishingHandler = nullptr;
     consumptionHandler = nullptr;
    
  5. Substitua os valores de marcador de posição no código-fonte usando as seguintes constantes de string:

    Espaço reservado Valor
    <exemplo de texto> Exemplo de texto que você gostaria de proteger, por exemplo: "cipher text".
    <ID do modelo> ID do modelo que você gostaria de usar para proteger o texto. Por exemplo: "bb7ed207-046a-4caf-9826-647cff56b990"

Criar e testar o aplicativo

Crie e teste seu aplicativo cliente.

  1. Use Ctrl+Shift+B (Build Solution) para criar seu aplicativo cliente. Se você não tiver erros de compilação, use F5 (Iniciar depuração) para executar seu aplicativo.

  2. Se o projeto for compilado e executado com êxito, o aplicativo solicitará um token de acesso sempre que o SDK chamar seu AcquireOAuth2Token() método. Como você fez anteriormente no guia de início rápido "Listar modelos de proteção", execute seu script do PowerShell para obter o token todas as vezes, usando os valores fornecidos para $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.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 . . .
    

Próximas Etapas