|
DPAPI generates two
keys: a key for the user credential, and a master key. It also uses random
session key when you call CryptProtectData. Combine with all these keys, data is
protected. When you change the password, DPAPI will hook up to the password
change event and does the re-encryption whole again. DPAPI works at both the
machine-level and user-level encryption access scenarios.
In .NET 2.0 and later versions, a set
of wrapper classes have been introduced to encrypt data by simple means using
the current user account or computer accessing DPAPI. You need not have to use
the P/Invoke to work with the DPAPI methods and the encryption-decryption is not
just limited to user credentials.
ProtectedMemory
The ProtectedMemory class may be used
to encrypt an array of in-memory bytes. This functionality is available in
Microsoft Windows XP and later operating systems. You can specify that memory
encrypted by the current process can be decrypted by the current process only,
by all processes, or from the same user context. The MemoryProtectionScope
enumeration is available for this purpose.
To perform encryption and decryption of
data stored in-memory, you may use the methods Protect and UnProtect
methods.
Example:
To demonstrate this, create a new
console application and add reference to System.Security.dll. In the program.cs,
add the following code:
static void Main(string[]
args)
{
byte[] myData = new
byte[32];
System.Text.ASCIIEncoding ae =
new ASCIIEncoding();
// Protecting and
Un-protecting data in memory
Console.Write("Enter some
text: ");
string text =
Console.ReadLine();
if (text.Length <
myData.Length)
text =
text.PadRight(myData.Length, ' ');
else
text =
text.Substring(0,myData.Length);
myData =
ae.GetBytes(text);
Console.WriteLine("Before
protection: {0}", ae.GetString(myData));
System.Security.Cryptography.ProtectedMemory.Protect(myData,
System.Security.Cryptography.MemoryProtectionScope.SameProcess);
Console.WriteLine("After
protection: {0}", ae.GetString(myData));
System.Security.Cryptography.ProtectedMemory.Unprotect(myData,
System.Security.Cryptography.MemoryProtectionScope.SameProcess);
Console.WriteLine("After
un-protection: {0}", ae.GetString(myData));
}
|