我需要执行字节[]的加密数组。我使用了 Microsoft 上提供的示例。不幸的是,加密数据被截断为 16 的倍数。如果在数据示例中我将添加 8 倍字节 0,则数据将被正确加密。填充已设置,但我没有看到任何可以更改的内容。如何解决这个问题,数据不被截断。
public byte[] EncryptAES(byte[] plainBytes)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] FKey = encoding.GetBytes("A002AD9AD73C402190C3E733D82CEA00");
byte[] FIV = encoding.GetBytes("zyxwvutsrqponmlk");
// Check arguments.
if (plainBytes == null || plainBytes.Length <= 0)
throw new ArgumentNullException("plainText");
if (FKey == null || FKey.Length <= 0)
throw new ArgumentNullException("Key");
if (FIV == null || FIV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = FKey;
rijAlg.IV = FIV;
rijAlg.Padding = PaddingMode.Zeros;
rijAlg.Mode = CipherMode.CBC;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
// plainBytes.Length = 2216
csEncrypt.Write(plainBytes, 0, plainBytes.Length);
// encrypted.Length = 2208
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}