AES Encryption Error: The Input Data Is Not A Complete Block?


Answer :

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

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?