我需要对byte[]数组进行加密。我使用了 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;
}
最佳答案
You should always explicitly close your CryptoStream object after you are done using it by calling the Close method. Doing so flushes the stream and causes all remain blocks of data to be processed by the CryptoStream object. However, if an exception occurs before you call the Close method, the CryptoStream object might not be closed. To ensure that the Close method always gets called, place your call to the Close method within the finally block of a try/catch statement.
(我的重点)
所以,请调用 Close
在您尝试对结果做任何事情之前。
基本上,padding用于处理一系列加密 block 的最后一个 block 。由于 CryptoStream
不知道您打算调用 Write()
多少次,因此它不会应用填充或写入任何最终不完整的 block ,直到您调用 关闭
。
(或者,正如 Monkieboy 指出的那样,FlushFinalBlock
也可用于表示您已完成)
关于c# - 加密数据 (AES) 的大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15291657/