Introduction
Data Protection using DPAPI on managed code needs to be done using C++ unmanaged code or by writing some wrapper code, as many of us have done. Data Protection is available in VS2005 by using some simple-to-use static methods: "ProtectedMemory::Protect", "ProtectedMemory::Unprotect", "ProtectedData::Protect", and "ProtectedData::Unprotect" located in the "System::Security::Cryptography" namespace. I have taken some time to define a class that I called "Secret" that hides many implementation details with the intention of making working with those methods as simple as it can be. For example:
int main(array<System::String ^> ^args)
{
String ^s = L"this is a sample and a long one it is";
::Security::ISecret ^a =
(::Security::ISecret^)(gcnew ::Security::Secret());
a->ProtectMemory(s) ;
a->UnprotectMemory();
System::Console::WriteLine(a->ToString());
String ^entropy=L"test", ^fpath=L"c:/temp/test.dat" ;
a->ProtectDataToFile(s,entropy,fpath) ;
a->UnprotectDataFromFile(entropy,fpath) ;
System::Console::WriteLine(a->ToString());
return 0;
}
You will soon find that keeping secrets with the "Secret" class can be a bit more complex if you like to influence the "Scope" of your secret. For that reason I also abstracted out the DPAPI enumerators and provided a single enumerator class as follows:
public enum class ProtectionScope
{
...
ProtectMemoryCrossProcess = 1,
ProtectMemorySameLogon = 2,
ProtectMemorySameProcess = 3,
ProtectDataCurrentUser = 10,
ProtectDataLocalMachine = 11,
...
} ;
To change the scope just do the following:
a->Scope = ProtectionScope::ProtectMemoryCrossProcess ;
I encourage the reader to lookup the DPAPI MSDN articles and use it to keep data secure in their applications. Search for DPAPI and "ProtectedMemory" to get to those articles.
I'd also like that anyone interested in the "Secret" class use it, and if improvements are done, keep me posted of those. Also if there are any recommendations (the good and the bad) send me those as well.