Rating:

## Solution

So to be able to quickly see the relationship between the plaintext and the ciphertext, we simulate the encryption and we get the following output

```
0 {'m0', 'm1', 'k0'}
1 {'k1', 'm0', 'k0'}
2 {'k2', 'k1', 'm1'}
3 {'k3', 'm1', 'k0', 'k2', 'm0'}
4 {'k3', 'k4', 'k0', 'k1', 'm0'}
5 {'k5', 'm1', 'k4', 'k2', 'k1'}
6 {'k5', 'm1', 'k3', 'k0', 'k6', 'k2', 'm0'}
7 {'k3', 'k4', 'k6', 'k0', 'k1', 'm0', 'k7'}
8 {'k5', 'm1', 'k4', 'k8', 'k2', 'k1', 'k7'}
9 {'m1', 'k6', 'k8', 'k0', 'k2', 'm0', 'k3', 'k5', 'k9'}
```

So in this case, our cipher text will just be

```
c0 = m1 ^ (k5 ^ k4 ^ k8 ^ k2 ^ k1 ^ k7)
c1 = m0 ^ m1 ^ (k6 ^ k8 ^ k0 ^ k2 ^ k3 ^ k5 ^ k9)
```
Let us define `final_key0` and `final_key1`
```
final_key0 = (k5 ^ k4 ^ k8 ^ k2 ^ k1 ^ k7)
final_key1 = (k6 ^ k8 ^ k0 ^ k2 ^ k3 ^ k5 ^ k9)
```

We can define the relationship of the plaintext, ciphertext and finalkeys completely.
```
c0 = m1 ^ final_key0
c1 = m0 ^ m1 ^ final_key1
```

So that means we can easily get the final_keys from the plaintext and Ciphertext
```
final_key0 = c0 ^ m1
final_key1 = c1 ^ m1 ^ m0
```

And we can use this final_keys to get the flag from the secret key

```
secret_0 = flag_1 ^ final_key0
secret_1 = flag_0 ^ flag_1 ^ final_key1

flag_1 = secret_0 ^ final_key0
flag_0 = secret_key ^ final_key1 ^ flag_1
```

Although this is only true if you have `H = 10`. Depending on what H, the the relationship between the plaintext, ciphertext and final_keys changes slightly. There are actually 3 forms which you can try all 3 to get the flag.

```
secret_0 = flag_1 ^ final_key0
secret_1 = flag_0 ^ flag_1 ^ final_key^1

secret_0 = flag_0 ^ final_key0
secret_1 = flag_1 ^ final_key^1

secret_0 = flag_0 ^ flag_1 ^ final_key0
secret_1 = flag_0 ^ final_key^1
```

And eventually you'll get the flag `# TMCTF{Feistel-Cipher-Flag-TMCTF2018}`

__For implementation details please see the link__

Original writeup (https://github.com/pberba/ctf-solutions/tree/master/20180915_trendmicro/forensics_crypto_1_400).