Monday, June 04, 2012

Using the DPAPI through ProtectedData Class in .Net Framework 2.0

Introduction:

The objective of this tutorial is to show how the DPAPI can be used to encrypt and decrypt data:

Encrypt some data using ProtectedData Class in System.Security.Cryptography namespace and save it to a file. 

Show that the data can be decrypted using the same class but deferent method. 

Login as a different user, and show that the data cannot be decrypted.
Encrypting Data:

Here we will encrypt some data, and write it to a file.

Open the attached project WriteSecretData which you will find in the WriteSecretData folder. This is a skeleton C# console application that you will use to encrypt data using the DPAPI support in .NET 2.0. 

Add using directives for System.Security.Cryptography and System.IO to the other usings at the top of the file: 

// Needed for encryption
using System.Security.Cryptography;
// Needed for file I/O
using System.IO;

Note you may need to add a reference to System.Security.dll, do that if needed. 

Note how the code asks for some code to encrypt, and a string to use as an extra encryption key (the 'entropy').

If an entropy string isn't used, anyone logging in with the same user ID will be able to decrypt the secret data. 

At the first TODO comment, insert code to turn the strings into byte arrays:

byte[] plainBytes = Encoding.Unicode.GetBytes(plainText); 
byte[] entropyBytes = Encoding.Unicode.GetBytes(entropyText); 

At the second TODO comment in the code, add a call to encrypt the data so that it can only be retrieved by the current user: 

byte[] encryptedBytes = ProtectedData.Protect(plainBytes, entropyBytes, DataProtectionScope.CurrentUser); 

Read more: C# Corner
QR: Inline image 1

Posted via email from Jasper-Net