65.9K
CodeProject 正在变化。 阅读更多。
Home

在 .NET 中使用数据保护 API (DPAPI) 保密

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.67/5 (3投票s)

2005年10月5日

1分钟阅读

viewsIcon

32759

downloadIcon

370

一个完整的示例,用于在内存或文件中保密数据。

引言

在托管代码中使用 DPAPI 进行数据保护需要使用 C++ 非托管代码或编写一些包装代码,正如我们许多人所做的那样。数据保护在 VS2005 中可用,通过使用一些易于使用的静态方法实现:“ProtectedMemory::Protect”、“ProtectedMemory::Unprotect”、“ProtectedData::Protect”和“ProtectedData::Unprotect”,这些方法位于“System::Security::Cryptography”命名空间中。我花了一些时间定义了一个名为“Secret”的类,该类隐藏了许多实现细节,目的是使使用这些方法尽可能简单。例如

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;
}

您很快就会发现,使用“Secret”类保密可能更复杂,如果您想影响您的密钥的“范围”。因此,我也抽象了 DPAPI 枚举器,并提供了一个单独的枚举器类,如下所示

public enum class ProtectionScope
{
   ...

   // memory protection

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

   // data protection

   ProtectDataCurrentUser  = 10,
   ProtectDataLocalMachine = 11,

   ...
}  ;

要更改范围,只需执行以下操作

   a->Scope = ProtectionScope::ProtectMemoryCrossProcess ;

我鼓励读者查阅 DPAPI MSDN 文章,并将其用于保护应用程序中的数据。搜索 DPAPI 和“ProtectedMemory”以获取这些文章。

我也希望对“Secret”类感兴趣的任何人使用它,如果进行了改进,请随时告诉我。另外,如果有任何建议(好的和坏的),也请发送给我。

© . All rights reserved.