分组密码SAFER+的C#实现
2009-02-27 08:18:34 来源:WEB开发网3. 加密算法
算法首先将string型的明文m_sInClearText置入byte型的字节数组input中,注意到string
型使用unicode字符集,所以16位的m_m_sInClearText将转换成32个元素的input,而明文则在input数组的偶数位下标中,如input[0],input[2],……,input[30]中,(当然也可以使用密钥扩展算法中的方法,即全部使用ASCII码,这样,该数组的范围将为input[0]-input[15])。
然后进行32轮迭代,在第i轮迭代中,采用32*i+j的运算来定位密钥扩展数组n_LocKeyExpandBox的下标,用表达式的运算结果来与0xFF作与(<, SPAN lang=EN-US>&)操作,从而达到运算结果模256的要求,代码如下:
input[0] = (byte)((m_nExpBox[input[0] ^ n_LocKeyExpandBox[32 * i]] + n_LocKeyExpandBox[32 * i + 16]) & 0xFF);
input[2] = (byte)((m_nLogBox[input[2] + n_LocKeyExpandBox[32 * i + 1]] ^ n_LocKeyExpandBox[32 * i + 17]) & 0xFF);
input[4] = (byte)((m_nLogBox[input[4] + n_LocKeyExpandBox[32 * i + 2]] ^ n_LocKeyExpandBox[32 * i + 18]) & 0xFF);
input[6] = (byte)((m_nExpBox[input[6] ^ n_LocKeyExpandBox[32 * i + 3]] + n_LocKeyExpandBox[32 * i + 19]) & 0xFF);
input[8] = (byte)((m_nExpBox[input[8] ^ n_LocKeyExpandBox[32 * i + 4]] + n_LocKeyExpandBox[32 * i + 20]) & 0xFF);
input[10] = (byte)((m_nLogBox[input[10] + n_LocKeyExpandBox[32 * i + 5]] ^ n_LocKeyExpandBox[32 * i + 21]) & 0xFF);
input[12] = (byte)((m_nLogBox[input[12] + n_LocKeyExpandBox[32 * i + 6]] ^ n_LocKeyExpandBox[32 * i + 22]) & 0xFF);
input[14] = (byte)((m_nExpBox[input[14] ^ n_LocKeyExpandBox[32 * i + 7]] + n_LocKeyExpandBox[32 * i + 23]) & 0xFF);
input[16] = (byte)((m_nExpBox[input[16] ^ n_LocKeyExpandBox[32 * i + 8]] + n_LocKeyExpandBox[32 * i + 24]) & 0xFF);
input[18] = (byte)((m_nLogBox[input[18] + n_LocKeyExpandBox[32 * i + 9]] ^ n_LocKeyExpandBox[32 * i + 25]) & 0xFF);
input[20] = (byte)((m_nLogBox[input[20] + n_LocKeyExpandBox[32 * i + 10]] ^ n_LocKeyExpandBox[32 * i + 26]) & 0xFF);
input[22] = (byte)((m_nExpBox[input[22] ^ n_LocKeyExpandBox[32 * i + 11]] + n_LocKeyExpandBox[32 * i + 27]) & 0xFF);
input[24] = (byte)((m_nExpBox[input[24] ^ n_LocKeyExpandBox[32 * i + 12]] + n_LocKeyExpandBox[32 * i + 28]) & 0xFF);
input[26] = (byte)((m_nLogBox[input[26] + n_LocKeyExpandBox[32 * i + 13]] ^ n_LocKeyExpandBox[32 * i + 29]) & 0xFF);
input[28] = (byte)((m_nLogBox[input[28] + n_LocKeyExpandBox[32 * i + 14]] ^ n_LocKeyExpandBox[32 * i + 30]) & 0xFF);
input[30] = (byte)((m_nExpBox[input[30] ^ n_LocKeyExpandBox[32 * i + 15]] + n_LocKeyExpandBox[32 * i + 31]) & 0xFF);
更多精彩
赞助商链接