C# AES 加密错误:输入的数据不是一个完整的块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19614178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AES encryption error: The input data is not a complete block?
提问by ConditionRacer
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?
但是它一直在 source.Write(plaintext) 上抛出一个异常,说它不是一个完整的块?我使用的是 16 字节/128 位数组,块大小设置为 128。我不明白有什么问题?
Also, just to head off any suggestions that ECB is bad etc, this is not for production, I'm just playing around.
此外,只是为了阻止任何关于欧洲央行不好等的建议,这不是用于生产,我只是在玩。
采纳答案by SLaks
StreamWriter
writes UTF8 text characters to a stream.
You're writing plaintext.ToString()
as text for the ciphertext.
StreamWriter
将 UTF8 文本字符写入流。
您正在编写plaintext.ToString()
密文的文本。
This returns "System.Byte[]"
, which does not translate into 16 bytes of UTF8.
这将返回"System.Byte[]"
,它不会转换为 16 个字节的 UTF8。
回答by ConditionRacer
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();
}
}
}
回答by ZagNut
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.
我相信问题出在填充模式上。除非您要加密的文本肯定可以被 BlockSize(以位为单位,或 BlockSize / 8 以字节为单位)整除,否则您应该指定一个除 None 之外的 PaddingMode。
see the post herefor example code