本文介绍了AesCryptoServiceProvider.TransformFinalBlock错误:输入数据不是完整的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的加密/解密应用程序,以使自己熟悉AesCryptoServiceProvider,但收到错误。错误为输入数据不是完整的块。下面是代码:

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?

推荐答案

哈,找到它了!

看看在您的加密函数返回的值上:

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.

这篇关于AesCryptoServiceProvider.TransformFinalBlock错误:输入数据不是完整的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:16