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:

Incorporación de lógica para establecer y obtener una plantilla de protección

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

  1. Con el Explorador de soluciones, abra el archivo .cs del proyecto que contiene la implementación del método Main(). De manera predeterminada, tiene el mismo nombre que el proyecto que lo contiene, que especificó al crear el proyecto.

  2. Hacia la parte final del cuerpo de Main(), donde lo ha dejado en el inicio rápido anterior, inserte el código siguiente:

    //Set text to encrypt and template ID
    string inputText = "<Sample-text>";
    string templateId = "<template-id>";
    //Create a template based publishing descriptor
    ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
    
    //Create publishing settings using protection descriptor
    PublishingSettings publishingSettings = new PublishingSettings(protectionDescriptor);
    
    //Generate Protection Handler for publishing
    var publishingHandler = Task.Run(async() => await protectionEngine.CreateProtectionHandlerForPublishingAsync(publishingSettings)).Result;
    
    //Encrypt text using Publishing handler
    long bufferSize = publishingHandler.GetProtectedContentLength(inputText.Length, true);
    byte[] inputTextBuffer = Encoding.ASCII.GetBytes(inputText);
    byte[] encryptedTextBuffer = new byte[bufferSize];
    publishingHandler.EncryptBuffer(0, inputTextBuffer, encryptedTextBuffer, true);
    Console.WriteLine("Original text: {0}", inputText);
    Console.WriteLine("Encrypted text: {0}", Encoding.UTF8.GetString(encryptedTextBuffer));
    
    //Create a Protection handler for consumption using the same publishing licence
    var serializedPublishingLicense = publishingHandler.GetSerializedPublishingLicense();
    PublishingLicenseInfo plInfo = PublishingLicenseInfo.GetPublishingLicenseInfo(serializedPublishingLicense);
    ConsumptionSettings consumptionSettings = new ConsumptionSettings(plInfo);
    var consumptionHandler = protectionEngine.CreateProtectionHandlerForConsumption(consumptionSettings);
    
    //Use the handler to decrypt the encrypted text
    long buffersize = encryptedTextBuffer.Length;
    byte[] decryptedBuffer = new byte[bufferSize];
    var bytesDecrypted = consumptionHandler.DecryptBuffer(0, encryptedTextBuffer, decryptedBuffer, true);
    byte[] OutputBuffer = new byte[bytesDecrypted];
    for (int i = 0; i < bytesDecrypted; i++){
       OutputBuffer[i] = decryptedBuffer[i];
    }
    
    Console.WriteLine("Decrypted content: {0}", Encoding.UTF8.GetString(OutputBuffer));
    Console.WriteLine("Press a key to quit.");
    Console.ReadKey();
    
    
  3. Hacia el final de Main(), busque el bloque de cierre de la aplicación creado en el primer inicio rápido y agregue líneas de controlador:

    // Application Shutdown
    publishingHandler = null;
    consumptionHandler = null;
    protectionEngine = null;
    protectionProfile = null;
    mipContext = null;
    
  4. Reemplace los valores de marcador de posición del código fuente por los valores siguientes:

    Marcador Valor
    <sample-text> Texto de ejemplo que le gustaría cifrar, por ejemplo: My secure text.
    <template-id> Identificador de plantilla, copiado de la salida de la consola en el inicio rápido anterior, 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 ejecuta correctamente, es posible que la aplicación solicite autenticación mediante ADAL cada vez que el SDK llame al método AcquireToken(). Si ya existen credenciales en caché, no se le pedirá que inicie sesión y verá la lista de etiquetas, seguida de la información sobre la etiqueta aplicada y el archivo modificado.

 Original content: My secure text
 Encrypted content: c?_hp???Q??+<?
 Decrypted content: My secure text
 Press a key to quit.