miniBill
miniBill

Reputation: 1733

ProtectedMemory.Unprotect outputs garbage

I've got this code to store and recover an authorization token (which is alphanumeric):

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

And it mostly works fine, although some times I get garbage out (many FD bytes, and some readable ones). I suspect this happens only when I reboot, but I've had some difficulties reproducing it.

Is this the intended behaviour? That is, does MemoryProtectionScope.SameLogon mean that the data will always be unreadable upon reboot? Am I doing something wrong?

The FromHexString and ToHexString methods do exactly what you would expect from them.

Upvotes: 3

Views: 811

Answers (1)

Luaan
Luaan

Reputation: 63772

Yes, ProtectedMemory will always fail after you reboot (or for the different MemoryProtectionScopes, restart the process etc.). It's only meant to work to protect memory, not data for storage.

You want to use ProtectedData instead:

ProtectedData.Protect(buffer, null, DataProtectionScope.CurrentUser);

Both of those are managed wrappers over the DPAPI (introduced with Windows 2000). There's a bunch of posts with more details on the .NET security blog - http://blogs.msdn.com/b/shawnfa/archive/2004/05/05/126825.aspx

Upvotes: 6

Related Questions