ICryptoTransform.TransformBlock:发生了什么事?

时间:2013-05-10 09:00:44

标签: c# .net cryptography aes

我正在学习ICryptoTransform。

我加密了一些数据并使用ICryptoTransform.TransformBlock将它们解密回来。没有异常被抛出,但我发现我的数据正好关于一个bolck。

请看下面的代码:

//Init
var aes = new AesCryptoServiceProvider();
var key = new byte[16];
var IV = new byte[16];
var rand = new Random();
rand.NextBytes(key);
rand.NextBytes(IV);
var dev = aes.CreateEncryptor(key, IV);
var invdev = aes.CreateDecryptor(key, IV);
const int bufsize = 16 * 2;
var input = new byte[bufsize];
var output = new byte[bufsize];
var backbuf = new byte[bufsize];
rand.NextBytes(input);

// Start Caculate
for (int i = 0; i < bufsize; i += 16)
    dev.TransformBlock(input, i, 16, output, i);
backbuf[0] = 10; // it seems that invdev didn't touch backbuf[0 ~ 15]
for (int i = 0; i < bufsize; i += 16)
    invdev.TransformBlock(output, i, 16, backbuf, i);

// Output
for (int i = 0; i < bufsize; ++i)
{ Console.Write(input[i]); Console.Write(' '); }
Console.WriteLine();
for (int i = 0; i < bufsize; ++i)
{ Console.Write(output[i]); Console.Write(' '); }
Console.WriteLine();
for (int i = 0; i < bufsize; ++i)
{ Console.Write(backbuf[i]); Console.Write(' '); }
Console.WriteLine();
Console.ReadKey();

我认为输入应该等于反向输入

但我的节目输出:

83 202 85 77 101 146 91 55 90 194 242 26 118 40 46 218 196 202 75 234 228 232 146 156 169 250 72 130 78 185 52 14

219 44 184 142 192 20 222 199 39 232 160 115 254 18 250 70 43 81 149 152 140 4 249 193 248 57 18 59 149 30 41 23

10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 83 202 85 77 101 146 91 55 90 194 242 26 118 40 46 218

这很有趣且令人困惑...... ICryptoTransform.TransformBlock和我的程序出了什么问题? 或者我们可以直接使用ICryptoTransform.TransformBlock吗?

感谢。 (最后请原谅我可怜的英语......)

1 个答案:

答案 0 :(得分:1)

好吧,我可能会找到解决方案 事实上,ICryptoTransform.TransformBlock中有一个整数返回值,这意味着转换后的字节数成为CodesInChaos所说的。 并且ICryptoTransform.TransformBlock的正确用法是:

int transed = 0;
for (int i = 0; i < bufsize; i += transed )
    transed = invdev.TransformBlock(output, i, 16, backbuf, i);

有趣的是,第一个TransformBlock方法返回0 ......这就是我的程序错误的原因。

似乎Aes可能需要在变换前进行准备,以便第一个TransformBlock返回0。

相关问题