Microsoft 在 C# 中用于加密/解密的示例代码有一个无法解释的行,他们将 key 固定在内存中。我非常理解固定的概念——它用于指示 GC 不应将该内存的内容移动到其他位置。当然可以。
固定 key 有什么好处?我相当确定有一个——我曾经合作过的一位非常聪明的开发人员提到,这是我们软件安全的重要一步。 MS的article的相关代码.
static void Main()
{
// Must be 64 bits, 8 bytes.
// Distribute this key to the user who will decrypt this file.
string sSecretKey;
// Get the key for the file to encrypt.
sSecretKey = GenerateKey();
// For additional security pin the key.
GCHandle gch = GCHandle.Alloc( sSecretKey, GCHandleType.Pinned );
// Encrypt the file.
EncryptFile( @"C:\MyData.txt", @"C:\Encrypted.txt", sSecretKey );
// Decrypt the file.
DecryptFile( @"C:\Encrypted.txt", @"C:\Decrypted.txt", sSecretKey );
// Remove the key from memory.
ZeroMemory( gch.AddrOfPinnedObject(), sSecretKey.Length * 2 );
gch.Free();
}
最佳答案
这是因为覆盖内存只会覆盖数据所在的位置现在。
如果垃圾收集器将其四处移动,则可能会在其先前位置保留数据副本。
你为什么不使用 SecureString
为此上课?就地覆盖 System.String
会违反其不变量,并可能导致意外行为。然而,SecureString
被设计为可删除且不留下任何副本。
关于c# - 在 C# 中,为什么将 key 固定在内存中更安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012534/