微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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被设计为被删除并且不留下任何副本.

原文地址:https://www.jb51.cc/csharp/98951.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐