2013-05-10 188 views
0

我正在學習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

回答

1

好吧,我可以找到解決辦法 事實上,在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