c# - 加密数据 (AES) 的大小错误

标签 c# encryption aes cryptostream

我需要对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;
}

最佳答案

CryptoStream :

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/

相关文章:

MySQL 无法使用 AES_ENCRYPT 函数返回项目

ios - iOS 和 android 上的 AES 加密,输出和缓冲区大小不同

C# Mongo DeleteMany - 不使用类

c# - 更高效的数据包序列化

c# - 如何为多个动态文本框启用 Google 音译 (ASP.Net)

java - "NegativeArraySizeException"- 自定义类加载器

c# - WCF Web 服务的响应大小限制

c - 如何使密码更有效

java - Java中的Columnar Transposition解密算法

aes - 在虚拟机上托管的旧版 DOS 程序上进行打印