如何在 WPF 中安全地显示随机生成的密码

How to securely display a randomly generated password in WPF

"securely",我的意思是 GC 不会在内存中移动它,复制保持在最低限度,并且一旦不再需要它就会从内存中删除。

我有生成随机密码的代码,但我需要显示它,我不想使用 string 来显示它。密码当前在 SecureString 中生成,我可以将其放入 fixed/pinned 缓冲区中使用。我可以将其呈现给用户的最安全方式是什么?

我不知道有什么方法可以在不将 SecureString 转换为普通字符串的情况下显示它。无论如何,Microsoft 自己甚至不再推荐 secure SecureStringThis is linked to from the official msdn documentation page:

DE0001: SecureString shouldn't be used

Motivation

  • The purpose of SecureString is to avoid having secrets stored in the process memory as plain text.
  • However, even on Windows, SecureString doesn't exist as an OS concept.
    • It just makes the window getting the plain text shorter; it doesn't fully prevent it as .NET still has to convert the string to a plain text representation.
    • The benefit is that the plain text representation doesn't hang around as an instance of System.String -- the lifetime of the native buffer is shorter.
  • The contents of the array is unencrypted except on .NET Framework.
    • In .NET Framework, the contents of the internal char array is encrypted. .NET doesn't support encryption in all environments, either due to missing APIs or key management issues.

Recommendation

Don't use SecureString for new code. When porting code to .NET Core, consider that the contents of the array are not encrypted in memory.

The general approach of dealing with credentials is to avoid them and instead rely on other means to authenticate, such as certificates or Windows authentication.

SecureString 并不是对敏感信息真正有效的保护,它只是稍微限制了攻击 window 并混淆了事情。

我个人的看法是,如果您无论如何都要向用户展示它,您真的应该担心它在应用程序内部的可访问性。而且,一般来说,应用程序的内存安全是 OS 和硬件物理安全的责任。如果您需要担心未经授权访问应用程序内存,那么您已经遇到了一个更大的安全问题。