Rail Fence Cipher (50 pts)


Decrypt and find the flag.

Ciphertext = AaY--rpyfneJBeaaX0n-,ZZcs-uXeeSVJ-sh2tioaZ}slrg,-ciE-anfGt.-eCIyss-TzprttFliora{GcouhQIadctm0ltt-FYluuezTyorZ-


Rail fence cipher is a simple transposition cipher which works by writing the plaintext over fences diagonally, while reading it off the fences horizontally. To further complicate the cipher, diagonal transcription changes direction upon reaching either the top or bottom fence. That said, given the number of fences (), it is easy to decipher a text encrypted with the rail fence cipher.

In this challenge, we simply brute force until we reach a promising plaintext, which means a plaintext containing the Sharif CTF 2016 flag format: SharifCTF{flag}.

So, here's a simple Python script which does the job:

#!/usr/bin/env python3 

CIPHERTEXT = "AaY--rpyfneJBeaaX0n-,ZZcs-uXeeSVJ-sh2tioaZ}slrg,-ciE-anfGt.-eCIyss-TzprttFliora{GcouhQIadctm0ltt-FYluuezTyorZ-"


while True:
    FENCES += 1

    Mat = [[] for i in range(FENCES)]
    Msg = [''] * n

    j = 0
    d = +1
    for i in range(0, n):
        j += d
        if j == 0 or j == FENCES - 1:
            d = -d

    l = 0
    for j in range(0, FENCES):
        for i in range(0, len(Mat[j])):
            Msg[Mat[j][i]] = CIPHERTEXT[l]
            l += 1

    m = ''.join(Msg)

    if m.find('SharifCTF{') != -1:

print("Number of fences:", FENCES)
print("Plaintext:", m)

The output is:

Number of fences: 21
Plaintext: A-fence-is-a-structure-that-encloses-an-area,-SharifCTF{QmFzZTY0IGlzIGEgZ2VuZXJpYyB0ZXJt},-typically-outdoors.

indicating that 21 fences where used, and the flag is QmFzZTY0IGlzIGEgZ2VuZXJpYyB0ZXJt.

Source Code