Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
962 views
in Technique[技术] by (71.8m points)

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

Here's the encryption method:

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 iv = new byte[16];
        for (int i = 0; i < iv.Length; i++)
            iv[i] = 0;
        aes.IV = iv;

        var encryptor = aes.CreateEncryptor(key, aes.IV);
        using(var target = new MemoryStream())
        using (var cs = new CryptoStream(target, encryptor, CryptoStreamMode.Write))
        {
            using (var source = new StreamWriter(cs))
                source.Write(plaintext);
            return target.ToArray();
        }
    }
}

And how I'm calling it:

var key = new byte[16] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
var plaintext = new byte[16] { 128, 0, 112, 0, 96, 0, 80, 0, 64, 0, 48, 0, 32, 0, 16, 0 };

But it keeps throwing an exception at source.Write(plaintext) that says it's not a complete block? I'm using a 16 byte/ 128 bit array with the block size set to 128. I don't understand what's wrong?

Also, just to head off any suggestions that ECB is bad etc, this is not for production, I'm just playing around.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...