2016-01-31 258 views
0

所以我需要從我的字節數組中切掉前16個字節。我跟另一篇文章我在Stack Overflow上看到使用下面的代碼:錯誤將數組拆分爲兩個

//split message into iv and encrypted bytes 
byte[] iv = new byte[16]; 
byte[] workingHash = new byte[rage.Length - 16]; 

//put first 16 bytes into iv 
for (int i = 0; i < 16; i++) 
{ 
    iv[i] = rage[i]; 
} 

Buffer.BlockCopy(rage, 16, workingHash, 0, rage.Length); 

我們試圖在這裏是從byte[] rage切斷前16個字節,並把其餘的爲byte[] workingHash

錯誤出現在Buffer.BlockCopy(rage, 16, workingHash, 0, rage.Length);

偏移量和長度超出數組的界限或count大於從索引到源集合結束的元素數。

任何幫助將不勝感激。

+0

'workingHash'是rage.Length - 16,所以你不能複製'rage.Length'字節。這看起來像缺少一個windows phone標記 – Plutonix

+1

你調試了你自己的代碼嗎?對於處理AES加密的人來說似乎是一個微不足道的問題。 –

+0

當然,我調試它...反正...修正。 –

回答

-1

修正:

   //split message into iv and encrypted bytes 
       byte[] iv = new byte[16]; 
       byte[] workingHash = new byte[rage.Length - 16]; 

       //put first 16 bytes into iv 
       for (int i = 0; i < 16; i++) 
       { 
        iv[i] = rage[i]; 
       } 

       for (int i = 0; i < rage.Length - 16; i++) 
       { 
        workingHash[i] = rage[i + 16]; 
       } 
+2

錯誤修復。最好是理解錯誤並保持BlockCopy調用,這是更好的代碼。這個問題在某個地方只是一個「-16」。不要重寫希望錯誤消失! – usr

1

問題是簡單的:Buffer.BlockCopy的最後一個參數需要被複制,這(服用的起始索引考慮)不得超過陣列的邊界正確的字節數(docs )。

因此,代碼應該是這樣的,避免任何for循環:

Buffer.BlockCopy(rage, 0, iv, 0, 16); 
Buffer.BlockCopy(rage, 16, workingHash, 0, rage.Length - 16); 

通知了「- 16」在第二行中,固定的原代碼。爲了保持一致性,第一行代替for週期。

1

讓我們假設ragebyte陣列長度20:

var rage = new byte[20] 
{ 
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 
}; 

byte[] iv = new byte[16];後,iv將包含:

byte[] workingHash = new byte[rage.Length - 16];
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } 

後,workingHash將包含:

{ 0, 0, 0, 0 } 

foriv後是:

{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } 

你需要:

Buffer.BlockCopy(rage, 16, workingHash, 0, rage.Length - 16); 

複印rage.Length - 16(4)從rage的第16個元素(其爲17),以workingHash從第0個元素開始的元素。

結果:

{ 17, 18, 19, 20 } 

順便說有一個非常可讀的方式,可能是不一樣快複製數組,但值得一提:

var firstSixteenElements = rage.Take(16).ToArray(); 
var remainingElements = rage.Skip(16).ToArray();