private void SetKey(byte[] key)
{
/*
* - comments are from _Applied Crypto_, Schneier, p338
* please be careful comparing the two, AC numbers the
* arrays from 1, the enclosed code from 0.
*
* (1)
* Initialise the S-boxes and the P-array, with a fixed string
* This string contains the hexadecimal digits of pi (3.141...)
*/
Array.Copy(KS0, 0, S0, 0, SBOX_SK);
Array.Copy(KS1, 0, S1, 0, SBOX_SK);
Array.Copy(KS2, 0, S2, 0, SBOX_SK);
Array.Copy(KS3, 0, S3, 0, SBOX_SK);
Array.Copy(KP, 0, P, 0, P_SZ);
/*
* (2)
* Now, XOR P[0] with the first 32 bits of the key, XOR P[1] with the
* second 32-bits of the key, and so on for all bits of the key
* (up to P[17]). Repeatedly cycle through the key bits until the
* entire P-array has been XOR-ed with the key bits
*/
int keyLength = key.Length;
int keyIndex = 0;
for (int i = 0; i < P_SZ; i++)
{
// Get the 32 bits of the key, in 4 * 8 bit chunks
uint data = 0x0000000;
for (int j = 0; j < 4; j++)
{
// create a 32 bit block
data = (data << 8) | (uint)key[keyIndex++];
// wrap when we get to the end of the key
if (keyIndex >= keyLength)
{
keyIndex = 0;
}
}
// XOR the newly created 32 bit chunk onto the P-array
P[i] ^= data;
}
/*
* (3)
* Encrypt the all-zero string with the Blowfish algorithm, using
* the subkeys described in (1) and (2)
*
* (4)
* Replace P1 and P2 with the output of step (3)
*
* (5)
* Encrypt the output of step(3) using the Blowfish algorithm,
* with the modified subkeys.
*
* (6)
* Replace P3 and P4 with the output of step (5)
*
* (7)
* Continue the process, replacing all elements of the P-array
* and then all four S-boxes in order, with the output of the
* continuously changing Blowfish algorithm
*/
ProcessTable(0, 0, P);
ProcessTable(P[P_SZ - 2], P[P_SZ - 1], S0);
ProcessTable(S0[SBOX_SK - 2], S0[SBOX_SK - 1], S1);
ProcessTable(S1[SBOX_SK - 2], S1[SBOX_SK - 1], S2);
ProcessTable(S2[SBOX_SK - 2], S2[SBOX_SK - 1], S3);
}