// constructs the enctryption sieve public void Initialize(byte *key, int keybytes) { int i, j; uint data, datal, datar; aword temp = new aword(); // first fill arrays from data tables for (i = 0; i < 18; i++) { PArray[i] = bf_P[i]; } for (i = 0; i < 4; i++) { for (j = 0; j < 256; j++) { SBoxes[i, j] = bf_S[i, j]; } } j = 0; for (i = 0; i < NPASS + 2; ++i) { temp.dword = 0; temp.byte0 = key[j]; temp.byte1 = key[(j + 1) % keybytes]; temp.byte2 = key[(j + 2) % keybytes]; temp.byte3 = key[(j + 3) % keybytes]; data = temp.dword; PArray[i] ^= data; j = (j + 4) % keybytes; } datal = 0; datar = 0; for (i = 0; i < NPASS + 2; i += 2) { Blowfish_encipher(&datal, &datar); PArray[i] = datal; PArray[i + 1] = datar; } for (i = 0; i < 4; ++i) { for (j = 0; j < 256; j += 2) { Blowfish_encipher(&datal, &datar); SBoxes[i, j] = datal; SBoxes[i, j + 1] = datar; } } }
private unsafe void Blowfish_decipher(uint *xl, uint *xr) { aword Xl = new aword(); aword Xr = new aword(); Xl.dword = *xl; Xr.dword = *xr; Xl.dword ^= PArray[17]; /*ROUND(ref Xr, Xl, 16); * ROUND(ref Xl, Xr, 15); * ROUND(ref Xr, Xl, 14); * ROUND(ref Xl, Xr, 13); * ROUND(ref Xr, Xl, 12); * ROUND(ref Xl, Xr, 11); * ROUND(ref Xr, Xl, 10); * ROUND(ref Xl, Xr, 9); * ROUND(ref Xr, Xl, 8); * ROUND(ref Xl, Xr, 7); * ROUND(ref Xr, Xl, 6); * ROUND(ref Xl, Xr, 5); * ROUND(ref Xr, Xl, 4); * ROUND(ref Xl, Xr, 3); * ROUND(ref Xr, Xl, 2); * ROUND(ref Xl, Xr, 1);*/ Xr.dword ^= ROUND(Xl, 16); Xl.dword ^= ROUND(Xr, 15); Xr.dword ^= ROUND(Xl, 14); Xl.dword ^= ROUND(Xr, 13); Xr.dword ^= ROUND(Xl, 12); Xl.dword ^= ROUND(Xr, 11); Xr.dword ^= ROUND(Xl, 10); Xl.dword ^= ROUND(Xr, 9); Xr.dword ^= ROUND(Xl, 8); Xl.dword ^= ROUND(Xr, 7); Xr.dword ^= ROUND(Xl, 6); Xl.dword ^= ROUND(Xr, 5); Xr.dword ^= ROUND(Xl, 4); Xl.dword ^= ROUND(Xr, 3); Xr.dword ^= ROUND(Xl, 2); Xl.dword ^= ROUND(Xr, 1); Xr.dword ^= PArray[0]; *xl = Xr.dword; *xr = Xl.dword; }
//[MethodImpl(MethodImplOptions.AggressiveInlining)] private uint ROUND(aword x, int n) { //a.dword ^= bf_F(x) ^ PArray[n]; Count++; return((((SBoxes[0, x.byte0] + SBoxes[1, x.byte1]) ^ SBoxes[2, x.byte2]) + SBoxes[3, x.byte3]) ^ PArray[n]); }
private void ROUND(ref aword a, aword x, int n) { //a.dword ^= bf_F(x) ^ PArray[n]; a.dword ^= (((SBoxes[0, x.byte0] + SBoxes[1, x.byte1]) ^ SBoxes[2, x.byte2]) + SBoxes[3, x.byte3]) ^ PArray[n]; }
/*private uint S(aword x, int i) { * return SBoxes[i, x.bytes[i]]; * }*/ //[MethodImpl(MethodImplOptions.AggressiveInlining)] private uint bf_F(aword x) { return(((SBoxes[0, x.byte0] + SBoxes[1, x.byte1]) ^ SBoxes[2, x.byte2]) + SBoxes[3, x.byte3]); }