c# - 在 C# 中,为什么将 key 固定在内存中更安全?

标签 c# security encryption

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/

相关文章:

c# - 在一个线程中有一组获胜表单而在另一个线程中有另一组是否有任何问题?

c# - 为什么这个方法需要递归?

c# - Xamarin.iOS Objective-C 绑定(bind)错误

ruby - ruby gem 内的校验和有什么意义

ios - Xamarin.iOS/Akavache - 使用自定义 EncryptionProvider 的加密缓存

java - 将 AES 加密从 Java 移植到 Objective-C

c# - 如何在 PHP 中解密 C# 中使用 3DES 加密的字符串?

c# - 将 <text> 转换为字符串?

c# - 套接字是否应该受到保护

security - 安全的只读sqlite3数据库