public bool Decode(byte[] data, int len, string key) { blf_ctx c; uint xl, xr; int i; if (len % 8 != 0) { return(false); } c = new blf_ctx(); c.S = new uint[4, 256]; c.P = new uint[18]; InitBlowfish(c, key, key.Length); for (i = 0; i < len; i += 8) { // memcpy(&xl, data + i, sizeof(UINT32)); // memcpy(&xr, data + i + 4, sizeof(UINT32)); xl = (uint)ConvertHelper.BytesToInt32(data, i, true); xr = (uint)ConvertHelper.BytesToInt32(data, i + 4, true); Blowfish_decipher(c, ref xl, ref xr); //memcpy(data + i, &xl, sizeof(UINT32)); //memcpy(data + i + 4, &xr, sizeof(UINT32)); byte[] byteXl = ConvertHelper.Int32ToBytes((int)xl, true); byte[] byteXr = ConvertHelper.Int32ToBytes((int)xr, true); Array.Copy(byteXl, 0, data, i, 4); Array.Copy(byteXr, 0, data, i + 4, 4); } return(true); }
private void Blowfish_decipher(blf_ctx c, ref uint xl, ref uint xr) { uint Xl; uint Xr; uint temp; int i; Xl = xl; Xr = xr; for (i = ROUNDCOUNT + 1; i > 1; --i) { Xl = Xl ^ c.P[i]; Xr = F1(c, Xl) ^ Xr; temp = Xl; Xl = Xr; Xr = temp; } temp = Xl; Xl = Xr; Xr = temp; Xr = Xr ^ c.P[1]; Xl = Xl ^ c.P[0]; xl = Xl; xr = Xr; }
private void InitBlowfish(blf_ctx c, string key, int key_len) { //short error; //short numread; uint data; uint data1; uint datar; /* Initialize s-boxes without file read. */ int i; ushort j = 0; int k; for (i = 0; i < 256; i++) { c.S[0, i] = ks0[i]; c.S[1, i] = ks1[i]; c.S[2, i] = ks2[i]; c.S[3, i] = ks3[i]; } for (i = 0; i < 18; i++) { c.P[i] = 0; } for (i = 0; i < ROUNDCOUNT + 2; ++i) { data = 0x00000000; for (k = 0; k < 4; ++k) { data = (data << 8) | key[j]; j++; if (j >= key_len) { j = 0; } } // for k c.P[i] = c.P[i] ^ data; } //for i data1 = 0x00000000; datar = 0x00000000; for (i = 0; i < ROUNDCOUNT + 2; i += 2) { Blowfish_encipher(c, ref data1, ref datar); c.P[i] = data1; c.P[i + 1] = datar; } for (i = 0; i < 4; ++i) { for (j = 0; j < 256; j += 2) { Blowfish_encipher(c, ref data1, ref datar); c.S[i, j] = data1; c.S[i, j + 1] = datar; } //for j } //for i }
private void Blowfish_encipher(blf_ctx c, ref uint xl, ref uint xr) { uint Xl; uint Xr; uint temp; int i; Xl = xl; Xr = xr; for (i = 0; i < ROUNDCOUNT; ++i) { Xl = Xl ^ c.P[i]; Xr = F1(c, Xl) ^ Xr; temp = Xl; Xl = Xr; Xr = temp; } temp = Xl; Xl = Xr; Xr = temp; Xr = Xr ^ c.P[ROUNDCOUNT]; Xl = Xl ^ c.P[ROUNDCOUNT + 1]; xl = Xl; xr = Xr; }
private static uint F1(blf_ctx bc, uint x) { ushort a; ushort b; ushort c; ushort d; uint y; d = (ushort)((ushort)x & 0x00FF); x >>= 8; c = (ushort)((ushort)x & 0x00FF); x >>= 8; b = (ushort)((ushort)x & 0x00FF); x >>= 8; a = (ushort)((ushort)x & 0x00FF); y = bc.S[0, a] + bc.S[1, b]; y = y ^ bc.S[2, c]; y = y + bc.S[3, d]; return(y); }