然后进行32轮迭代,首论迭代从高位m_nRoundsLen-1开始以后依次递减1,直到为0。在第i论迭代中,先将input数组右乘矩阵m_nAntiLinearTransMatrixBox(该矩阵的说明详见参考文献[1]),代码如下:
temp = input[6];
input[6] = input[30];
input[30] = temp;
...
input[2] = (byte)((input[2] - input[0]) >= 0 ? (input[2] - input[0]) : (input[2] - input[0] + 256));
其实质仍然是一维数组input[]与一个二维数组m_nAntiLinearTransMatrixBox的乘积,那么为什么不用以下更精炼的代码呢?
Byte[] temp = new byte[input.length];
For (j=0;j<16;j++)
For (k=0;k<16;k++)
{
Temp[2*j] +=(byte)(input[2*k] * m_nAntiLinearTransMatrixBox[k,j]);
}
For (j=0;j<16;j++)
{
Input[2*j] = (byte)temp[2*j];
}
其中:
Static public byte[,] m_nAntiLinearTransMatrixBox = newbyte[16,16]
{
{2,-2,1,-2,1,-1,4,-8,2,-4,1,-1,1,-2,1,-1},
{-4,4,-2,4,-2,2,-8,16,-2,4,-1,1,-1,2,-1,1},
{1,-2,1,-1,2,-4,1,-1,1,-1,1,-2,2,-2,4,-8},
{-2,4,-2,2,-2,4,-1,1,-1,1,-1,2,-4,4,-8,16},
{1,-1,2,-4,1,-1,1,-2,1,-2,1,-1,4,-8,2,-2},
{-1,1,-2,4,-1,1,-1,2,-2,4,-2,2,-8,16,-4,4},
{2,-4,1,-1,1,-2,1,-1,2,-2,4,-8,1,-1,1,-2},
{-2,4,-1,1,-1,2,-1,1,-4,4,-8,16,-2,2,-2,4},
{1,-1,1,-2,1,-1,2,-4,4,-8,2,-2,1,-2,1,-1},
{-1,1,-1,2,-1,1,-2,4,-8,16,-4,4,-2,4,-2,2},
{1,-2,1,-1,4,-8,2,-2,1,-1,1,-2,1,-1,2,-4},
{-1,2,-1,1,-8,16,-4,4,-2,2,-2,4,-1,1,-2,4},
{4,-8,2,-2,1,-2,1,-1,1,-2,1,-1,2,-4,1,-1},
{-8,16,-4,4,-2,4,-2,2,-1,2,-1,1,-2,4,-1,1},
{1,-1,4,-8,2,-2,1,-2,1,-1,2,-4,1,-1,1,-2},
{-2,2,-8,16,-4,4,-2,4,-1,1,-2,4,-1,1,-1,2}
}
道理同加密算法,因为这是模256的减法运算,所以只能采取在运算的每一步对表达式结果使用三目运算符 ?:进行判断,保证结果为正值后与0xFF作与(&)操作,从而保证其值介于0-255之间,因而不能采用通常意义上的二维数组乘法来进行处理。
同加密算法类似的,在第i轮迭代中,采用32*i+j的运算来定位n_LocExpandBox的下标,用表达式的运算结果与0xFF作与(&)操作。代码如下:
input[0] = (byte)((m_nLogBox[input[0] - n_LocKeyExpandBox[32 * i + 16] + 256] ^ n_LocKeyExpandBox[32 * i]) & 0xFF);
...
input[30] = (byte)((m_nLogBox[input[30] - n_LocKeyExpandBox[32 * i + 31] + 256] ^ n_LocKeyExpandBox[32 * i + 15]) & 0xFF);
三、几点说明
1.本程序在Windows server 2003 Standard Edition Service Pack 2,Visual Studio
2008 version 9.0.21022.8 RTM,.NET 3.5,Intel P4 3.06Ghz下 调试通过。
2.对程序中出现的所有模256“+”运算,考虑到只取低16位,所以均采用与(&)0xFF来达到此运算要求,而对于模256“+”运算的逆运算,即模256“-”运算,采用三目运算符?来进行判断,若“-”运算结果大于等于零,则结果为其自身,否则将差加上256来满足要求。
3.加密算法中,input[0] = (byte)((input[0] ^ n_LocKeyExpandBox[16 * m_nChipherLen]));不能对结果采用与(&)0xFF操作。
参考文献
[1] 胡予濮,张玉清,肖国镇编著 《对称密码学》 [M](北京)机械工业出版社2002 年8.
[2] http://www.princeton.edu/~rblee/safer+/.
|