受欢迎的博客标签

使用 MIP SDK 加密/解密文本 (C#)

Published

使用 MIP SDK 加密/解密文本 (C#)

 Visual Studio 开发

Install-Package Microsoft.InformationProtection.File
Install-Package Microsoft.InformationProtection.Policy
Install-Package Microsoft.InformationProtection.Protection

 

 

//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();

 

 

 

https://learn.microsoft.com/zh-cn/information-protection/develop/setup-configure-mip

https://learn.microsoft.com/zh-cn/information-protection/develop/quick-protection-encrypt-decrypt-text-csharp