出于安全原因,我正在尝试清除 C# 字符串的内存内容。我知道这个SecureString
类,但不幸的是我不能在我的应用程序中SecureString
使用String
。需要清除的字符串是在运行时动态创建的(例如,我不想清除字符串文字)。
我发现的大多数搜索结果基本上表明清除 a 的内容String
是不可能的(因为字符串是不可变的)并且SecureString
应该使用。
因此,我确实在下面提出了自己的解决方案(使用不安全的代码)。测试表明解决方案有效,但我仍然不确定解决方案是否有问题?有更好的吗?
static unsafe bool clearString(string s, bool clearInternedString=false)
{
if (clearInternedString || string.IsInterned(s) == null)
{
fixed (char* c = s)
{
for (int i = 0; i < s.Length; i++)
c[i] = '\0';
}
return true;
}
return false;
}
编辑:由于 GC 在clearString
被调用之前移动字符串的评论:下面的代码片段怎么样?
string s = new string('\0', len);
fixed (char* c = s)
{
// copy data from secure location to s
c[0] = ...;
c[1] = ...;
...
// do stuff with the string
// clear the string
for (int i = 0; i < s.Length; i++)
c[i] = '\0';
}