How should IBuffer objects generated through Windo

2019-09-21 15:31发布

问题:

Following on from my previous question: Do the IBuffer objects produced by the methods in Windows.Security.Cryptography.CryptographicBuffer have security features?

IBuffer objects are returned and used by the cryptographic routines in WinRT. As my previous question was answered, any secure management of those buffers has to be maintained by the user--e.g. overwriting the memory, encrypting when it isn't actively needed, etc. However, methods to interact with the data underlying IBuffers are limited at the C# level.

So, how can C# developers properly manage sensitive data in these IBuffers?

回答1:

You can wipe out the buffer if you like after use, even with C#. Here is a handy helper:

public static class BufferExtensions
{
  public async static Task ClearContentsAsync(this IBuffer buff)
  {
    var writer = new DataWriter(buff.AsStream().AsOutputStream());
    for (var i = 0; i < buff.Capacity; i++)
      writer.WriteByte(42);
    await writer.StoreAsync();
  }
}

Use it like this:

  var buff = CryptographicBuffer.GenerateRandom(20);
  var before = buff.ToArray();
  await buff.ClearContentsAsync();
  var after = buff.ToArray();
  Debug.WriteLine("{0},{1},{2} - {3},{4},{5}", 
    before[0], before[1], before[2], after[0], after[1], after[2]);

Note that the values in before (copy taken before clearing) are random, but the values in after (copy taken after clearing) are all 42. You can of course use a different value of your choice :-).