AesCryptoServiceProvider.TransformFinalBlock error: The input data is not a complete block

血红的双手。 提交于 2019-12-11 13:33:57

问题


I wrote what was supposed to be a simple encrypt/decrypt application to familiarize myself with the AesCryptoServiceProvider and I am receiving an error. The error is "The input data is not a complete block." Here is the code:

    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);
        }
    }

I can find results for this error online but they are all related to writing to a memory stream for encryption, which is not really what I am doing. Can someone help point out what I am doing wrong here?


回答1:


Ha, found it!
Look at what you return in your encrypt function:

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

        return encryptTextBytes;

Tip: it is not the encrypted stuff.



来源:https://stackoverflow.com/questions/23092814/aescryptoserviceprovider-transformfinalblock-error-the-input-data-is-not-a-comp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!