Hızlı Başlangıç: MIP SDK'sı (C++) kullanarak metin şifreleme ve şifresini çözme

Bu hızlı başlangıçta MIP Koruması SDK'larının daha fazlasını nasıl kullanacağınız gösterilmektedir. Önceki hızlı başlangıçta listelediğiniz koruma şablonlarından birini kullanarak geçici metni şifrelemek için bir Koruma işleyicisi kullanırsınız. Koruma işleyici sınıfı, koruma uygulamak ve kaldırmak için çeşitli işlemleri kullanıma sunar.

Önkoşullar

Henüz yapmadıysanız devam etmeden önce aşağıdaki önkoşulları tamamladığınızdan emin olun:

Koruma işleyici nesnesini izlemek için bir gözlemci sınıfı uygulama

Uygulama başlatma hızlı başlangıcında Koruma profili ve altyapısı için uyguladığınız gözlemciye benzer şekilde, şimdi Koruma işleyici nesneleri için bir gözlemci sınıfı uygularsınız.

SDK'nın mip::ProtectionHandler::Observer sınıfını genişleterek Koruma işleyicisi gözlemcisi için temel bir uygulama oluşturun. SDK daha sonra koruma işleyicisi işlemlerini izlemek için gözlemciyi oluşturur ve kullanır.

  1. Önceki "Hızlı Başlangıç: Liste koruma şablonları (C++)" makalesinde üzerinde çalıştığınız Visual Studio çözümünü açın.

  2. Projenize, sizin için hem üst bilgi (.h) hem de uygulama (.cpp) dosyaları oluşturan yeni bir sınıf ekleyin:

    • Çözüm Gezgini proje düğümüne yeniden sağ tıklayın, Ekle'yi ve ardından Sınıf'ı seçin.
    • Sınıf Ekle iletişim kutusunda:
      • Sınıf Adı alanına girinhandler_observer. Visual Studio'nun, girdiğiniz ada göre hem .h dosyası hem de .cpp dosyası alanlarını otomatik olarak doldurduğunu unutmayın.
      • İşiniz bittiğinde Tamamseçin.
  3. sınıfı için .h ve .cpp dosyalarını oluşturup Visual Studio her iki dosyayı da Düzenleyici Grubu sekmelerinde açar. Şimdi her dosyayı yeni gözlemci sınıfınızı uygulayacak şekilde güncelleştirin:

    • Oluşturulan handler_observer.h sınıfını seçip silerek handler_observer öğesini güncelleştirin. Önceki adımın oluşturduğu önişlemci yönergelerini kaldırmayın (#pragma, #include). Ardından aşağıdaki kaynağı kopyalayıp mevcut önişlemci yönergelerinden sonra dosyaya yapıştırı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;
           };
      
      
    • Oluşturulan handler_observer sınıf uygulamasını seçip silerek güncelleştirinhandler_observer.cpp. Önceki adımın oluşturduğu önişlemci yönergelerini kaldırmayın (#pragma, #include). Ardından aşağıdaki kaynağı kopyalayıp mevcut önişlemci yönergelerinden sonra dosyaya yapıştırı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. İsteğe bağlı olarak, devam etmeden önce başarılı bir şekilde derlendiğini doğrulamak üzere çözümünüzün bir test derlemesini ve bağlantısını çalıştırmak için Ctrl+Shift+B (Derleme Çözümü) tuşlarını kullanın.

Geçici metni şifrelemek ve şifre çözmek için mantık ekleyin.

Koruma altyapısı nesnesini kullanarak geçici metni şifrelemek ve şifresini çözmek için mantık ekleyin.

  1. Çözüm Gezgini'ni kullanarak, projenizde yönteminin uygulanmasını main() içeren .cpp dosyasını açın.

  2. Aşağıdaki #include ve using yönergelerini dosyanın üst kısmındaki ilgili mevcut yönergelerin altına ekleyin:

      #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. Önceki hızlı başlangıçta bıraktığınız yer olan Main() gövdesinin sonuna doğru aşağıdaki kodu ekleyin:

    //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. main() sonlarına doğru, ilk hızlı başlangıç kılavuzunun oluşturduğu uygulama kapatma bloğunu bulun ve işleyiciye ait kaynakları serbest bırakmak için aşağıdaki satırları ekleyin:

     publishingHandler = nullptr;
     consumptionHandler = nullptr;
    
  5. Aşağıdaki dize sabitlerini kullanarak kaynak koddaki yer tutucu değerlerini değiştirin:

    Yer tutucu Değer
    <örnek metin> Korumak istediğiniz örnek metin, örneğin: "cipher text".
    <Şablon Kimliği> Metni korumak için kullanmak istediğiniz şablon kimliği. Örneğin: "bb7ed207-046a-4caf-9826-647cff56b990"

Uygulamayı derleme ve test etme

İstemci uygulamanızı derleyin ve test edin.

  1. İstemci uygulamanızı derlemek için Ctrl+Shift+B (Derleme Çözümü) tuşlarını kullanın. Derleme hataları yoksa, uygulamanızı çalıştırmak için F5 (Hata ayıklamayı başlat) kullanın.

  2. Projeniz başarıyla derlenip çalıştırılırsa, SDK yönteminizi AcquireOAuth2Token() her çağırdığında uygulama bir erişim belirteci ister. Daha önce "Liste koruma şablonları" hızlı başlangıcında yaptığınız gibi, $authority ve $resourceUrl için sağlanan değerleri kullanarak belirteci her seferinde almak için PowerShell betiğinizi çalıştırın.

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

Sonraki Adımlar