Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++/CLI

Keeping Secrets with Data Protection API (DPAPI) in .NET

2.67/5 (3 votes)
5 Oct 20051 min read 1   370  
A full blown sample of keeping data secret in memory or on a file.

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)
{
    // secret info to protect
    String ^s = L"this is a sample and a long one it is";

    // get the secret instance
    ::Security::ISecret ^a =
       (::Security::ISecret^)(gcnew ::Security::Secret());

    // keep your secret in memory
    a->ProtectMemory(s) ;
    a->UnprotectMemory();
    System::Console::WriteLine(a->ToString());


    // some user given / known data (entroy) to salt secret and
    // target file to store secret into
    String ^entropy=L"test", ^fpath=L"c:/temp/test.dat" ;

    // keep your secret in a file
    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
{
   ...

   // memory protection

   ProtectMemoryCrossProcess = 1,
   ProtectMemorySameLogon    = 2,
   ProtectMemorySameProcess  = 3,

   // data protection

   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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here