Partilhar via


Guia de início rápido: criptografar/descriptografar texto usando o MIP SDK (C++)

Este Guia de início rápido mostra como usar mais SDKs de proteção MIP. Usando 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 do manipulador de proteção expõe várias operações para aplicar/remover a proteção.

Pré-requisitos

Se ainda não o fez, certifique-se de que preenche 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 o mecanismo de proteção) no Guia de início rápido de inicialização do aplicativo, agora você implementa uma classe de observador para objetos do manipulador de proteção.

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

  1. Abra a solução do Visual Studio em que você trabalhou no artigo anterior "Guia de início rápido: modelos de proteção de lista (C++)".

  2. Adicione uma nova classe ao seu projeto, que gera os arquivos header/.h e implementation/.cpp para você:

    • No Gerenciador de Soluções, clique com o botão direito do mouse no nó do projeto novamente, selecione Adicionar e, em seguida, selecione Classe.
    • Na caixa de diálogo Adicionar classe:
      • No campo Nome da classe, digite "handler_observer". Observe que os campos de arquivo .h e arquivo .cpp são preenchidos automaticamente, com base no nome inserido.
      • Quando terminar, clique no botão OK .
  3. Depois de gerar os arquivos .h e .cpp para a classe, ambos os arquivos são abertos nas guias Grupo de Editores. Agora atualize cada arquivo para implementar sua nova classe de observador:

    • Atualize "handler_observer.h", selecionando/excluindo a classe gerada handler_observer . Não remova as diretivas de pré-processador geradas pela etapa anterior (#pragma, #include). Em seguida, copie/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/excluindo a implementação da classe gerada handler_observer . Não remova as diretivas de pré-processador geradas pela etapa anterior (#pragma, #include). Em seguida, copie/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/link de teste da sua solução, para garantir que ela seja compilada com êxito antes de continuar.

Adicionar lógica para criptografar e descriptografar texto ad hoc

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

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

  2. Adicione as seguintes #include e usando diretivas, abaixo das diretivas existentes correspondentes, na parte superior do arquivo:

      #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. No final do corpo, onde você parou no Guia de Main() 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>();
    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. No final de localizar o bloco de desligamento do main() aplicativo criado no primeiro início rápido e adicionar as linhas abaixo para liberar recursos do manipulador:

     publishingHandler = nullptr;
     consumptionHandler = nullptr;
    
  5. Substitua os valores de espaço reservado no código-fonte da seguinte forma, usando constantes de cadeia de caracteres:

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

Crie e teste 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 fez anteriormente no Guia de início rápido "Modelos de proteção de lista", execute o script do PowerShell para adquirir o token sempre, 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.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 . . .