安全擦除内存中 Aes 加密密钥的所有副本

问题描述 投票:0回答:0

我正在尝试使用 AES 进行解密,并明确清除密钥使用的内存。

为了解密我需要传递解密密钥的东西。解密完成后,我想将密钥的内存归零。通过调用 CryptographicOperations.ZeroMemory 方法将密钥的内存清零非常容易,如下所示:

//just example key. The real key has been decrypted by an assymetric private key on specialized hardware. 
byte[] key = System.Security.Cryptography.RandomNumberGenerator.GetBytes(32);

using (Aes aes = Aes.Create())
{
    aes.Key = key;

    //use the aes object for decryption here.
}

CryptographicOperations.ZeroMemory(key);

但是当我在 .net 运行时查看 Key setter 属性的 Aes 实现 时,我看到有一个使用 CloneByteArray 制作的密钥副本:

public virtual byte[] Key
{
    get
    {
        if (KeyValue == null)
            GenerateKey();
        return KeyValue.CloneByteArray()!;
    }

    set
    {
        ArgumentNullException.ThrowIfNull(value);

        long bitLength = value.Length * 8L;
        if (bitLength > int.MaxValue || !ValidKeySize((int)bitLength))
            throw new CryptographicException(SR.Cryptography_InvalidKeySize);

        // must convert bytes to bits
        this.KeySize = (int)bitLength;
        KeyValue = value.CloneByteArray();
    }
}

这里是 CloneByteArray 扩展方法的实现:

public static byte[]? CloneByteArray(this byte[]? src)
{
    if (src == null)
    {
        return null;
    }

    return (byte[])(src.Clone());
}

有没有办法显式清除所有处理Aes秘钥的内存?包括 .net 运行时创建的所有副本?或者阻止 .net 运行时复制密钥并只处理我自己分配的密钥?

c# cryptography aes
© www.soinside.com 2019 - 2024. All rights reserved.