我正在尝试实现Feistel Cipher,我有以下代码:
public static byte[] Encode(byte[] bytes) {
byte[] s = (byte[])bytes.Clone();
int half = s.Length / 2;
if (s.Length % 2 != 0)
throw new Exception("Unbalanced code");
byte[] left = new byte[half];
byte[] right = new byte[half];
Array.Copy(s, left, half);
Array.Copy(s, half, right, 0, half);
for (var k = 0; k < ROUNDS; k++) {
left = XOR(left,f(right));
var temp = left; left = right; right = temp;
}
byte[] toReturn = new byte[s.Length];
Array.Copy(left, 0, toReturn, half, half);
Array.Copy(right, 0, toReturn, 0, half);
return toReturn;
}
在此示例中,ROUNDS
为21,f是重新排列字节数组中字节的函数。
不幸的是,虽然字节应该等于Encode(编码(字节)),但事实并非如此。我不知道我做错了什么。
有什么建议吗?
编辑:f()
的代码public static byte[] f(byte[] s) {
byte[] toReturn = (byte[])s.Clone();
byte temp = s[0];
for (var k = 1; k < s.Length; k++) {
s[k-1] = s[k];
s[k - 1] = (byte)(s[k - 1] ^ 45);
}
s[s.Length - 1] = temp;
s[s.Length - 1] = (byte)(s[s.Length - 1] ^ 45);
return toReturn;
}
答案 0 :(得分:0)
CodesInChaos是正确的,问题是变量被变异。