.NET 5和.NET Core在Windows上运行时,SecureString是否加密?

3

微软在其SecureString文档[1]中写道:

在Windows操作系统上,SecureString实例的内部字符数组内容是加密的。

另一方面,在微软的github仓库[2]中写道:

除了.NET Framework之外,数组的内容未加密

因此,我想知道哪种说法是正确的。SecureString是否基于操作系统Windows(.NET Framework和.NET Core)进行加密,还是仅在.NET Framework中进行加密? SecureString如何在.NET 5中处理加密?

[1] https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring?view=netcore-3.0

[2] https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md


1
很不幸,有时候无法避免使用密码进行身份验证。因此,我认为没有比SecureString更优雅的替代方案了。 - tux1337
1
想一想:如果有人能够访问你的系统内存,那么他们也能够访问加密密码、解密密钥以及你发送给其他系统的凭证组合,还有其他所有内容。我怀疑只有极少数情况下,SecureString可能会显著提高安全性。 - Franz Gleichmann
是的,尽管在特定的使用情况下,它比将密码存储为字符串更好。所以非常希望能得到对问题的答案。 - tux1337
你可以查看源代码 https://github.com/microsoft/referencesource/blob/master/mscorlib/system/security/securestring.cs - Klaus Gütter
2个回答

0

SecureString在.NET 5+和在Windows上运行的.NET Core中都是加密的。

来自.NET 5文档:

在Windows操作系统上,SecureString实例内部字符数组的内容被加密。

然而,最好完整阅读该页面。

对于.NET Core 3.0和2.0, .NET Core文档中也有相同的句子。


微软建议将机密信息存储在进程之外并使用不透明句柄来访问它们,而不是使用SecureString。换言之,使用SecureString的主要重点是固定和尽可能短暂地以任何形式存储秘密,而不是加密。当然,短暂的“活”存储期由开发人员负责,而不是SecureString本身。

SecureString 的加密可以提供有用的深度防御,特别是当秘密信息以较快的速度分批到达(例如在键盘输入密码期间),并且可以快速使用 SecureString(例如重新保护和存储到其他地方)并在收到秘密信息的最后一位后立即处理。相比之下,在循环中将现有的 String 复制到 SecureString 中总是毫无意义的:您应该很快就要处理 SecureString,而秘密信息已经分散到未固定的托管内存中,因此即使在处理 SecureString 后,其明文副本也可能永久存在于进程中。


0

SecureString的源代码有一个EncryptionSupported方法(参见下文),它与CheckSupportedOnCurrentPlatform方法结合使用以检查是否支持加密,否则将引发异常。

对我来说似乎SecureString在Windows上受支持,除非它在.NET Core或.NET Framework上运行。

https://github.com/microsoft/referencesource/blob/master/mscorlib/system/security/securestring.cs

    [System.Security.SecurityCritical]  // auto-generated
        unsafe static bool EncryptionSupported() {
            // check if the enrypt/decrypt function is supported on current OS
            bool supported = true;                        
            try {
                Win32Native.SystemFunction041(
                    SafeBSTRHandle.Allocate(null , (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE),
                    Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE, 
                    Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS);
            }
            catch (EntryPointNotFoundException) {
                supported = false;
            }            
            return supported;
        }


     private void CheckSupportedOnCurrentPlatform() {
            if( !supportedOnCurrentPlatform) {
                throw new NotSupportedException(Environment.GetResourceString("Arg_PlatformSecureString"));
            }                            
            Contract.EndContractBlock();
        }

1
这个回答似乎是说在.NET Framework上,SecureString不会进行加密。我对.NET 5在Windows上的情况不了解,但我相当确定在.NET Framework上,SecureString是会进行加密的。 - Jirka Hanika

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接