ICryptoTransform.TransformBlock:发生了什么事?

问题描述:

我正在学习ICryptoTransform。ICryptoTransform.TransformBlock:发生了什么事?

而且我使用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(); 

我觉得输入应等于backput

但我的计划产出:

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和我的p有什么问题rogram? 或者我们可以直接使用ICryptoTransform.TransformBlock吗?

谢谢。 (最后请原谅我的英语不好......)

+0

嗯,我知道的CryptoStream是一个更好的选择,但我只是想知道什么是错的...(或者我们可以”请不要直接使用它?) – 2013-05-10 09:07:36

+0

对您的问题不负责,但'System.Random'不应该用于创建密钥甚至IV。 – CodesInChaos 2013-05-10 09:31:13

+2

您的问题可能与未检查“TransformBlock”的返回值而不使用“TransformFinalBlock”有关。 – CodesInChaos 2013-05-10 09:33:36

好吧,我可以找到解决办法 事实上,在ICryptoTransform.TransformBlock一个整数返回值,这意味着作为CodesInChaos所述的转化succedded的字节数。 而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

+0

但是'TransformFinalBlock'仍然必须被调用。 – SerG 2014-08-22 15:07:50