AES encryption error: The input data is not a complete block?

StreamWriter writes UTF8 text characters to a stream.
You're writing plaintext.ToString() as text for the ciphertext.

This returns "System.Byte[]", which does not translate into 16 bytes of UTF8.


I believe the problem to be padding mode. Unless your text to be encrypted is for sure divisible by BlockSize (in bits, or BlockSize / 8 in bytes), you should specify a PaddingMode other than None.

see the post here for example code


I changed the function to this:

public static byte[] Encrypt(byte[] plaintext, byte[] key)
{
    using (var aes = Aes.Create())
    {
        aes.BlockSize = 128;
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.None;

        var encryptor = aes.CreateEncryptor(key, new byte[16]);
        using(var target = new MemoryStream())
        using (var cs = new CryptoStream(target, encryptor, CryptoStreamMode.Write))
        {
            cs.Write(plaintext, 0, plaintext.Length);
            return target.ToArray();
        }
    }
}

From what I have experienced and fixed this issue, I missed to encrypt the field that it is complaining about, I was only decrypting it. It was saving a plain clear text and trying to decrypt it. So just make sure that the field that is complaining about is encrypted first. Thanks

Tags:

C#

Encryption