我有以下代码来存储和恢复授权令牌(字母数字):
public static void Store (string token)
{
byte[] buffer = Encoding.UTF8.GetBytes (token.PadRight (32));
ProtectedMemory.Protect (buffer, MemoryProtectionScope.SameLogon);
Settings.Default.UserToken = buffer.ToHexString ();
Settings.Default.Save ();
}
public static string Retrieve ()
{
byte[] buffer = Settings.Default.UserToken.FromHexString ();
if (buffer.Length == 0)
return String.Empty;
ProtectedMemory.Unprotect (buffer, MemoryProtectionScope.SameLogon);
return Encoding.UTF8.GetString (buffer).Trim ();
}
尽管有时我会产生垃圾(很多
FD
字节,还有一些可读的字节),但它通常都能正常工作。我怀疑只有在重新启动后才会发生这种情况,但是在复制它时遇到了一些困难。这是预期的行为吗?也就是说,
MemoryProtectionScope.SameLogon
是否表示重新启动后始终无法读取数据?难道我做错了什么?FromHexString
和ToHexString
方法完全可以满足您的期望。 最佳答案
是的,ProtectedMemory
将始终在您重新启动后失败(或者对于不同的MemoryProtectionScope
,重新启动进程等)。它仅用于保护内存,而不用于存储数据。
您想使用ProtectedData
代替:
ProtectedData.Protect(buffer, null, DataProtectionScope.CurrentUser);
这两个都是DPAPI(Windows 2000引入)上的托管包装。 .NET安全博客-http://blogs.msdn.com/b/shawnfa/archive/2004/05/05/126825.aspx上有很多帖子,提供了更多详细信息。