燃烧在内存System.String内存、System、String

2023-09-06 11:20:22 作者:薄涼少年

我想从内存中删除一个普通的字符串的任何痕迹,这样做,我从普通的字符串的基准创造 SecureString的的实例。像这样:

I am trying to remove any traces of a normal string from memory, to do so I am creating an instance of SecureString from a reference of the normal string. Like so:

public static unsafe void Burn(this string input)
{
    fixed (char* c = input)
    {
        var secure = new SecureString(c, input.Length);
        secure.Dispose();
    }
}

现在的问题是,即使在调用Dispose方法输入的内容是不可更改。从我的理解的 SecureString的实例应该在引用输入地址,因此干净的,如果从内存的Dispose()通话。我在想什么?

The problem is that even after calling the dispose method the contents of input are non-changed. From my understanding the SecureString instance should reference the input address and therefore clean if from memory upon Dispose() call. What am I missing?

推荐答案

看起来的 并不意味着要使用你的code这两个参数的构造函数。该文档还不清楚,但其使用的语句初始化SecureString类从System.Char对象的一个​​子新实例,告诉我那很可能复制数据,而不是加密以取代现有的字符串。这将使意义,因为对 SecureString的文件专门提到了一个字符串不能在确定的方式予以销毁。

It appears the two parameter constructor is not meant to be used by your code. The documentation isn't clear but its use of the phrase Initializes a new instance of the SecureString class from a subarray of System.Char objects tells me it's probably copying the data, not encrypting the existing string in place. This would make sense since the documentation for SecureString specifically mentions a String cannot be destroyed in a deterministic way.

要验证这一理论的一个好方法是比较输入的地址和安全来,如果看到他们在初始化之后仍指向同一位置在存储器中。

A good way to test this theory would be to compare the addresses of input and secure to see if they still point to the same location in memory after the initialization.