ProtectedMemory.Unprotect 输出垃圾

min*_*ill 3 c# dpapi access-token

我有这个代码来存储和恢复授权令牌(字母数字):

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 ();
}
Run Code Online (Sandbox Code Playgroud)

它大部分工作正常,尽管有时我会得到垃圾(很多FD字节,和一些可读的字节)。我怀疑只有当我重新启动时才会发生这种情况,但我在重现它时遇到了一些困难。

这是预期的行为吗?也就是说,是否MemoryProtectionScope.SameLogon意味着重启后数据将始终无法读取?难道我做错了什么?

FromHexString方法ToHexString完全符合您的期望。

Lua*_*aan 6

是的,ProtectedMemory重新启动后总会失败(或者对于不同的MemoryProtectionScope情况,重新启动进程等)。它只是为了保护内存,而不是为了存储数据。

你想改用ProtectedData

ProtectedData.Protect(buffer, null, DataProtectionScope.CurrentUser);
Run Code Online (Sandbox Code Playgroud)

它们都是通过 DPAPI(随 Windows 2000 引入)的托管包装器。.NET 安全博客上有很多包含更多详细信息的帖子 - http://blogs.msdn.com/b/shawnfa/archive/2004/05/05/126825.aspx