Vinegar 2

Posted on Mon 05 August 2024 in ctf

This is a writeup of the crypto challenge Vinegar 2 in the n00bz CTF 2024.

60d646e2bf4e4ba281bb5c70561033b9.png

The attached file enc.txt contained the following encrypted text:

*fa4Q(}$ryHGswGPYhOC{C{1)&_vOpHpc2r0({

And chall.py contained the following python code that was used to encrypt the message:

alphanumerical = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*(){}_?'
matrix = []
for i in alphanumerical:
    matrix.append([i])

idx=0
for i in alphanumerical:
    matrix[idx][0] = (alphanumerical[idx:len(alphanumerical)]+alphanumerical[0:idx])
    idx += 1

flag=open('../src/flag.txt').read().strip()
key='5up3r_s3cr3t_k3y_f0r_1337h4x0rs_r1gh7?'
assert len(key)==len(flag)
flag_arr = []
key_arr = []
enc_arr=[]
for y in flag:
    for i in range(len(alphanumerical)):
        if matrix[i][0][0]==y:
            flag_arr.append(i)

for y in key:
    for i in range(len(alphanumerical)):
        if matrix[i][0][0]==y:
            key_arr.append(i)

for i in range(len(flag)):
    enc_arr.append(matrix[flag_arr[i]][0][key_arr[i]])
encrypted=''.join(enc_arr)
f = open('enc.txt','w')
f.write(encrypted)

The code implements Vigenère cipher but includes numbers and special characters.

The following script can be used to decrypt the message:

# Given data
alphanumerical = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*(){}_?'
key = '5up3r_s3cr3t_k3y_f0r_1337h4x0rs_r1gh7?' # Same key used in encryption
encrypted = '*fa4Q(}$ryHGswGPYhOC{C{1)&_vOpHpc2r0({'

# Step 1: Recreate the matrix
matrix = []
for i in alphanumerical:
    matrix.append([i])

idx = 0
for i in alphanumerical:
    matrix[idx][0] = (alphanumerical[idx:len(alphanumerical)] + alphanumerical[0:idx])
    idx += 1

# Step 2: Recompute key indices (key_arr)
key_arr = []
for y in key:
    for i in range(len(alphanumerical)):
        if matrix[i][0][0] == y:
            key_arr.append(i)

# Step 3: Map encrypted characters to original flag
decrypted = []
for i in range(len(encrypted)):
    enc_char = encrypted[i]
    key_idx = key_arr[i]
    # Find the original character in the matrix row `key_idx`
    for row in matrix:
        if row[0][key_idx] == enc_char:
            decrypted.append(row[0][0])
            break

# Join the decrypted characters to form the original flag
original_flag = ''.join(decrypted)
print("Decrypted message:", original_flag)

Executing this script results in the following flag: n00bz{4lph4num3r1c4l_1s_n0t_4_pr0bl3m}