在某些情况下,无法在没有错误的情况下获取AES到crypt + decrypt

时间:2013-09-14 00:42:19

标签: c# encryption aes

我编写了一个用AES(System.Security.Cryptography.RijndaelManaged)加密/解密byte []数据的小类。

问题是:如果我尝试加密然后解密256个长度的字节数组,它可以正常工作。如果我使用任何其他长度(可能是任何数据)的数据,它会引发诸如“填充不正确且无法删除”或“不正确的数据长度”等错误。

我为RijndaelManaged实例尝试了Padding / Mode属性的许多配置。这是代码(使用默认配置Mode.CBC + Padding.PCKS7)。

int m_keySize;
byte[] m_key;
byte[] m_iv;

public AESEncryption(string key, int keySize = 128)
{
    m_keySize = keySize;

    byte[] entropy = Convert.FromBase64String(key);

    int keySizeBytes = (int)m_keySize / 8;
    if (entropy.Length == keySizeBytes)
        m_key = entropy;
    else
    {
        m_key = new byte[keySizeBytes];
        Buffer.BlockCopy(entropy, 0, m_key, 0, keySizeBytes);
    }

    // Generate IV
    RijndaelManaged temp = new RijndaelManaged { KeySize = m_keySize };
    temp.GenerateIV();
    m_iv = temp.IV;
}

// Simple Encrypt(byte[]) method
byte[] Encrypt(byte[] sourceData)
{
    try
    {
        MemoryStream resultStream = new MemoryStream();

        using (RijndaelManaged m_aes = new RijndaelManaged { KeySize = m_keySize })
        using (ICryptoTransform crypto = m_aes.CreateEncryptor(m_key, m_iv))
        using (CryptoStream cryptoStream = new CryptoStream(resultStream, crypto, CryptoStreamMode.Write))
            cryptoStream.Write(sourceData, 0, sourceData.Length);

        return resultStream.ToArray();
    }
    catch { return null; }
}

// Simple Decrypt(byte[]) method
byte[] Decrypt(byte[] sourceData)
{
    try
    {
        MemoryStream resultStream = new MemoryStream();

        using (RijndaelManaged m_aes = new RijndaelManaged { KeySize = m_keySize })
        using (ICryptoTransform crypto = m_aes.CreateDecryptor(m_key, m_iv))
        using (CryptoStream cryptoStream = new CryptoStream(resultStream, crypto, CryptoStreamMode.Write))
            cryptoStream.Write(sourceData, 0, sourceData.Length);

        return resultStream.ToArray();
    }
    catch { return null; }
}

1 个答案:

答案 0 :(得分:-1)

经过许多无用的解决方案,我找到了我的。相当愚蠢。 我将padding设置为None,并使用自己的填充方法,在加密前调用EncrypMethod中的Pad(ref sourceData)。

// TODO: I don't know what's wrong, it is only one working solution to make data decryptable. Enablind AES padding causes exceptions.
        void Pad(ref byte[] source)
        {
            int sourceLength = source.Length;
            while (Math.IEEERemainder(sourceLength, 256) != 0 || sourceLength < 256)
                sourceLength++;

            if (sourceLength == source.Length)
                return;

            int padAmount = (sourceLength - source.Length);

            MemoryStream stream = new MemoryStream(sourceLength);
            stream.Write(source, 0, source.Length);
            stream.Write(new byte[padAmount], 0, padAmount);

            source = stream.ToArray();
        }