0

我编写了一个小类,用于使用 AES (System.Security.Cryptography.RijndaelManaged) 加密/解密字节 [] 数据。

问题是:如果我尝试加密然后解密 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; }
}
4

1 回答 1

-1

在许多无用的解决方案之后,我找到了我的。相当愚蠢。我将填充设置为无,并使用自己的填充方法,在加密之前在 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();
        }
于 2013-09-14T08:53:35.407 回答