2013-02-14 93 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