在C#中,为什么在内存中固定密钥更安全?

微软用于C#中加密/解密的示例代码有一条无法解释的行,它将密钥固定在内存中.我理解钉扎的概念 – 它用于表示GC不应该将该内存的内容移动到其他位置.当然,很好.

固定密钥有什么好处?我很确定有一个一个非常聪明的开发人员,曾经一度提到过,这是我们软件安全的重要一步.来自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被设计为被删除并且不留下任何副本.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...