我编写了一个小类,用于使用 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; }
}