为什么 SecureString 没有重载的构造函数?

Why does SecureString not have an overloaded constructor?

考虑以下几点:

_securePassword = New SecureString()
For Each character As Char In password
    _securePassword.AppendChar(character)
Next

令人惊讶的是,the documentation 似乎暗示这是用实际信息填充 SecureString 的 "best practice" 方法:

When creating a string from a character-at-a-time ...

我的问题

为什么不包括 New SecureString(password)

对于作为消费者的我来说,这似乎是纯粹的样板代码。

因为那时您要保护的字符串已经作为正常 String 存在于内存中,否定了将其作为一个整体仅保存在 SecureString 中的任何好处。

docs告诉你原因:

A SecureString object should never be constructed from a String, because the sensitive data is already subject to the memory persistence consequences of the immutable String class. The best way to construct a SecureString object is from a character-at-a-time unmanaged source, such as the Console.ReadKey method.

所以基本上,您永远不应该将字符串保存在内存中,因为那是不安全的。您无法保证该字符串已从易受攻击的内存中删除。