C#AES - 填充无效,无法删除

时间:2014-04-08 18:02:48

标签: c# cryptography aes

我几天来一直在努力解决这个问题。我已经阅读了关于这个填充问题的所有帖子 - 这通常是由不正确的密钥引起的(可能是这里的情况 - 但我没有看到它。

以下代码:

internal class AESEncryptionManager
{
    private byte[] keyBytes { get; set; }

    private byte[] ivBytes { get; set; }

    private static readonly byte[] SALT = new byte[]
        {0x26, 0xdc, 0xff, 0x12, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x02, 0xaf, 0x4d, 0x08, 0x22, 0x3c};

    private Rfc2898DeriveBytes keyDerivationFunction { get; set; }
    private AesManaged aesManaged;

    public AESEncryptionManager(string key)
    {   
        aesManaged = new AesManaged();
        aesManaged.Padding = PaddingMode.PKCS7;
        keyDerivationFunction = new Rfc2898DeriveBytes(key, SALT);

        aesManaged.KeySize = 256;
        aesManaged.BlockSize = 128;

        byte[] newKey = keyDerivationFunction.GetBytes(aesManaged.KeySize >> 3);
        byte[] newIv = keyDerivationFunction.GetBytes(aesManaged.BlockSize >> 3);

        keyBytes = newKey;
        ivBytes = newIv;

        aesManaged.Key = keyBytes;
        aesManaged.IV = ivBytes;

    }

    public byte[] EncryptToBytes(byte[] message)
    {
        ICryptoTransform encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes);

        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                csEncrypt.Write(message, 0, message.Length);
                csEncrypt.Close();
                return msEncrypt.ToArray();
            }
        }
    }

    public byte[] DecryptToBytes(byte[] message)
    {
        byte[] newKey = keyDerivationFunction.GetBytes(aesManaged.KeySize >> 3);
        byte[] newIv = keyDerivationFunction.GetBytes(aesManaged.BlockSize >> 3);

        ICryptoTransform decryptor = aesManaged.CreateDecryptor(newKey, newIv);

        using (MemoryStream msDecrypt = new MemoryStream())
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
            {
                csDecrypt.Write(message, 0, message.Length);
                csDecrypt.Close();
                return msDecrypt.ToArray();
            }
        }
    }

我已经尝试了通常的事情,例如刷新流等。任何MSDN或Stack Overflow上尚未提供的帮助都会有所帮助。

1 个答案:

答案 0 :(得分:1)

问题出在DecryptToBytes()

byte[] newKey = keyDerivationFunction.GetBytes(aesManaged.KeySize >> 3);
byte[] newIv = keyDerivationFunction.GetBytes(aesManaged.BlockSize >> 3);

ICryptoTransform decryptor = aesManaged.CreateDecryptor(newKey, newIv);

您正在创建具有与用于加密的密钥和初始化向量不同的解密器;您从用于导出加密的密钥和初始化向量的相同密钥导出函数请求新字节。因为加密和解密密钥不匹配解密会产生损坏的数据,特别是损坏的填充。用以下三行替换三行,它将起作用。

ICryptoTransform decryptor = aesManaged.CreateDecryptor();

请注意,我没有仔细查看代码,“它会工作”只意味着这个错误将被解决,并不意味着实现的其他部分也是正常的。