C# AESCryptServiceProvider.TransformFinalBlock错误:输入数据不是完整的块

C# AESCryptServiceProvider.TransformFinalBlock错误:输入数据不是完整的块,c#,aes,C#,Aes,我编写了一个简单的加密/解密应用程序来熟悉AESCryptServiceProvider,我收到了一个错误。错误是“输入数据不是完整的块”。以下是代码: static void Main(string[] args) { Console.WriteLine("Enter string to encrypt:"); string userText = Console.ReadLine(); byte[] key; by

我编写了一个简单的加密/解密应用程序来熟悉AESCryptServiceProvider,我收到了一个错误。错误是“输入数据不是完整的块”。以下是代码:

    static void Main(string[] args)
    {
        Console.WriteLine("Enter string to encrypt:");
        string userText = Console.ReadLine();
        byte[] key;
        byte[] IV;
        using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
        {
            key = aes.Key;
            IV = aes.IV;
        }

        byte[] encryptedText = EncryptString(userText, key, IV);

        Console.WriteLine(Convert.ToBase64String(encryptedText));

        string decryptedText = DecryptString(encryptedText, key, IV);

        Console.WriteLine(decryptedText);

        Console.ReadLine();
    }

    private static byte[] EncryptString(string encryptText, byte[] key, byte[] IV)
    {
        using (AesCryptoServiceProvider symAlg = new AesCryptoServiceProvider())
        {
            symAlg.Key = key;
            symAlg.IV = IV;

            ICryptoTransform ct = symAlg.CreateEncryptor(symAlg.Key, symAlg.IV);
            byte[] encryptTextBytes = UnicodeEncoding.ASCII.GetBytes(encryptText);
            byte[] encryptedText = ct.TransformFinalBlock(encryptTextBytes, 0, encryptTextBytes.Length);

            return encryptTextBytes;
        }
    }

    private static string DecryptString(byte[] decryptText, byte[] key, byte[] IV)
    {
        using (AesCryptoServiceProvider symAlg = new AesCryptoServiceProvider())
        {
            symAlg.Key = key;
            symAlg.IV = IV;
            ICryptoTransform ct = symAlg.CreateDecryptor(symAlg.Key, symAlg.IV);
            byte[] decryptedUserText = ct.TransformFinalBlock(decryptText, 0, decryptText.Length);

            return Convert.ToBase64String(decryptedUserText);
        }
    }
我可以在网上找到这个错误的结果,但它们都与写入内存流进行加密有关,而这并不是我真正要做的。有人能帮我指出我做错了什么吗?

哈,找到了
查看在加密函数中返回的内容:

        byte[] encryptTextBytes = UnicodeEncoding.ASCII.GetBytes(encryptText);
        byte[] encryptedText = ct.TransformFinalBlock(encryptTextBytes, 0, encryptTextBytes.Length);

        return encryptTextBytes;

提示:这不是加密的内容。

您忘记将输入填充到完整的块中了吗?加密通常只对特定大小的块起作用,因此最后一个块必须填充内容,使其达到所需的大小。好的,这是有意义的。这通常是加密或解密的一部分吗?还有,是否有一种烘焙的方式来做这件事,或者我需要手动做些什么?AESCryptoprovide有一些。但这是您真正需要查找的特定于您使用的算法和实现的内容,因为不好的填充可能会危害整个系统(不太可能,但为什么要冒险?)。我看到了该属性,但它默认设置为填充模式(PaddingMode.PKCS7)。即使我手动尝试枚举中的其他填充模式,它仍然不起作用。似乎如果设置了它,它应该“正常工作”,但我显然对此一无所知,所以我可能会误解。呃……像往常一样,更好的变量名会让我省心。谢谢