2013-02-14 92 views
1

有人可以請外行解釋這個C#代碼的工作原理嗎?C#私有函數,IncrementArray

for (int pos = 0; pos < EncryptedData.Length; pos += AesKey.Length); 
{ 
    Array.Copy(incPKGFileKey, 0, PKGFileKeyConsec, pos, PKGFileKey.Length); 

    IncrementArray(ref incPKGFileKey, PKGFileKey.Length - 1); 
} 

private Boolean IncrementArray(ref byte[] sourceArray, int position) 
{ 
    if (sourceArray[position] == 0xFF) 
    { 
     if (position != 0) 
     { 
      if (IncrementArray(ref sourceArray, position - 1)) 
      { 
       sourceArray[position] = 0x00; 
       return true; 
      } 
      else return false; 
     } 
     else return false; 
    } 
    else 
    { 
     sourceArray[position] += 1; 
     return true; 
    } 
} 

我試圖將應用程序移植到Ruby,但我無法理解IncrementArray函數的工作原理。

+1

通俗地說,你不明白什麼? – Oded 2013-02-14 19:25:01

回答

1

IncrementArray遞增字節數組的所有條目,任何溢出被添加到前一個索引,除非它已經是索引0。 整個事情看起來像某種加密或解密代碼。您可能希望查找使用哪種算法的其他提示,因爲此類代碼通常不會自我解釋。

+0

謝謝你的回答,我會試一試。我會鼓勵你,但我還沒有足夠的代表。 – user2053979 2013-02-14 19:30:23

0

在我看來就像一個大端另外的算法:

比方說,你還有很長(64位,8個字節)數量:

var bigNumber = 0x123456FFFFFFFF; 

但由於某些原因,我們已經有了它的到來給我們作爲一個字節數組中big-endian格式:

// Get the little endian byte array representation of the number: 
// [0xff 0xff 0xff 0xff 0xff 0x56 0x34 0x12] 
byte[] source = BitConverter.GetBytes(bigNumber); 

// BigEndian-ify it by reversing the byte array 
source = source.Reverse().ToArray(); 

所以,現在你想添加一個到這個‘數字’,在它的當前形式,同時保持任何carrys /溢出就像您在正常的算術中:

// increment the least significant byte by one, respecting carry 
// (as it's bigendian, the least significant byte will be the last one) 
IncrementArray(ref source, source.Length-1); 

// we'll re-little-endian-ify it so we can convert it back 
source = source.Reverse().ToArray(); 

// now we convert the array back into a long 
var bigNumberIncremented = BitConverter.ToInt64(source, 0); 

// Outputs: "Before +1:123456FFFFFFFF" 
Console.WriteLine("Before +1:" + bigNumber);  

// Outputs: "After +1:12345700000000" 
Console.WriteLine("After +1:" + bigNumberIncremented); 
+0

謝謝你的解釋。那麼一個添加到數組中的每個元素,然後一個添加到最不重要的字節?或者它只是將一個加到最低有效字節? – user2053979 2013-02-14 20:27:21

+0

謝謝JerKimball,這已經解決了我的問題。 :) – user2053979 2013-02-17 22:01:46