Meta4Sec 2025 - Crypto Challenges
Meta4Sec 2025 cryptography writeup covering classical-cipher analysis and RSA weakness exploitation.
Meta4Sec 2025 – Crypto Writeup
Writeup from the Meta4Sec CTF Cryptography challenge that I’ve worked on
Thank you for taking the time and effort to solve the cryptography challenge I created. I truly appreciate the thought, strategies, and dedication you put into working through it. I hope this challenge provided you with valuable experience and insight into the world of cryptography. 💻🔐
🔐 Crypto
🔹 Challenge: 0
- Description: -
- Attachments: chall_0.zip
- Solution Steps:
🧩 Challenge Overview
We are provided with a zip archive. After extracting it, we get the following files:
1
flag.txt output_test.txt readme.md test.txt
📄 readme.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
A mysterious message has been intercepted, and according to analysts, it appears to be encrypted with an unusual twist on a traditional cipher.
Luckily, we have a sample of both the plaintext and its corresponding ciphertext, which seems to be encrypted using the same method as the flag.
Your task is to:
1. Identify the encryption pattern by comparing the known plaintext and ciphertext.
2. Use this pattern to decrypt the flag in `flag.txt`.
===[ Files ]===
- test.txt # known plaintext
- output_test.txt # corresponding ciphertext
- flag.txt # encrypted flag
===[ Objective ]===
Retrieve the original flag from `flag.txt`.
Flag format: `Meta4Sec{...}`
Brute-forcing isn't required to solve this, but you’re welcome to try. A logical approach and familiarity with classic ciphers will be more effective.
Good luck!
🎯 Task Summary
Based on the information in readme.md, the main objective is to analyze the encryption used in test.txt and output_test.txt, and then apply the same logic to decrypt flag.txt.
🔍 Sample Analysis
From output_test.txt:
1
Sheajra Shaal suat bkeunt einskpri taeurt dmaal sheajra dna mhais saendaehr ahdaal einskpri mneankgagnu aalmgtoir
From test.txt:
1
Sejarah Salah satu bentuk enkripsi tertua dalam sejarah dan masih sederhana adalah enkripsi menggunakan algoritma
Let’s examine the encryption of the word Sejarah ~> Sheajra.
| Index | Original | Encrypted |
|---|---|---|
| 0 | S | S |
| 1 | e | h |
| 2 | j | e |
| 3 | a | a |
| 4 | r | j |
| 5 | a | r |
| 6 | h | a |
We observe the following transformation:
- index[0] stays the same ~>
S - index[1] becomes index[6]
- index[2] becomes index[1]
- index[3] becomes index[5]
- index[4] becomes index[2]
- index[5] becomes index[4]
- index[6] becomes index[3]
bentuk ~> bkeunt
| Index | Original | Encrypted |
|---|---|---|
| 0 | b | b |
| 1 | e | k |
| 2 | n | e |
| 3 | t | u |
| 4 | u | n |
| 5 | k | t |
- index[0] stays the same →
b - index[1] becomes index[5]
- index[2] becomes index[1]
- index[3] becomes index[5]
- index[4] becomes index[2]
- index[5] becomes index[4]
This suggests a fixed permutation pattern This insight gives us a solid base to reverse the process and decrypt the flag.
solver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
encode(s:str) -> str:
result = []
n = len(s)
for i in range(n // 2):
result.append(s[i])
result.append(s[n - 1 - i])
if n % 2 == 1:
result.append(s[n // 2])
return ''.join(result)
def decode(s:str) -> str:
n = len(s)
result = [''] * n
left = 0
right = n - 1
idx = 0
for i in range(n // 2):
result[left] = s[idx]
result[right] = s[idx + 1]
idx += 2
left += 1
right -= 1
if n % 2 == 1:
result[left] = s[idx]
return ''.join(result)
with open('flag.txt','r') as f:
enc = f.read().split()
decrypted = []
for j in enc:
decrypted.append(decode(j))
print(' '.join(decrypted))
- Flag:
Meta4Sec{sajjjaddddkunnnn_absoluteeee_cineemaaaaaa_202cb962ac}
🔹 Challenge: 1
- Description: -
- Attachments: chall_zip
- Solution Steps:
🔐 Overview
This challenge script implements RSA encryption using a custom large-prime generation method. The encryption process introduces several cryptographic weaknesses that make the ciphertext recoverable.
🧪 Prime Generation Logic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def generate_large_prime_product():
p = getPrime(512)
n = 1
phi = 1
primes = []
while True:
primes.append(p)
n *= p
phi *= (p - 1)
if n.bit_length() >= 8192:
break
p = nextprime(nextprime(p))
return n, primes, phi, p
- This function generates multiple 512-bit primes and multiplies them until the result (
n) is at least 8192 bits long. - The primes are generated using
nextprime(nextprime(p)), meaning each new prime is very close to the previous one. - Because these primes are closely spaced, the modulus
nbecomes vulnerable to root-based factorization techniques and then go back into previous prime until the result of gcd prime and N less than 512 bit length.
🧬 RSA Key Generation Logic
1
2
3
4
5
6
7
8
9
10
11
def get_valid_prime_update(n):
return nextprime(n)
def generate_rsa_keys(p, e=65537):
q = getPrime(16)
n = p * q
phi = (p - 1) * (q - 1)
d = inverse(e, phi)
private_key = RSA.construct((n, e, d, p, q))
public_key = private_key.publickey()
return private_key, public_key
- After the initial modulus is constructed, the program updates the prime using
nextprime(n)and treats this as the newp. - A new small prime
qis generated usinggetPrime(16), which results in a 16-bit value. - Because
qis so small, it can be brute-forced easily by trying all values in the range [1, 65536].
⚠️ Vulnerability Summary
- The first modulus
nis built from many closely spaced 512-bit primes. These can be factored using numerical root techniques since the primes are near each other. - The updated prime
pis justnextprime(n), which is predictable. - The second prime
qis only 16 bits, making it trivial to brute-force. - These combined weaknesses make it possible to reconstruct the private RSA key and recover the plaintext from
public.pemand the encrypted file.
🧩 Exploitation Strategy
- Factor the initial 8192-bit modulus using numerical methods that exploit closely spaced primes.
- Compute
p = nextprime(n)as used in the second phase. - Brute-force all possible 16-bit
qvalues (≤ 65536) to find the correct one. - Rebuild the full private key using
pandq. - Decrypt the encrypted chunks and recover the original ciphertext.
📜 Solver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# === IMPORTS ===
import base64
import time
from math import gcd
from sympy import nextprime
from gmpy2 import iroot
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Util.number import (
getPrime, inverse, bytes_to_long, long_to_bytes, isPrime
)
# === HELPER FUNCTIONS ===
def prevprime(n):
"""Find previous prime before n."""
n -= 1
while n > 1:
if isPrime(n):
return n
n -= 1
return None # Shouldn't happen for n > 2
def generate_large_prime_product(p, n_candidate, e=65537):
"""Generate RSA modulus and private exponent from base prime `p`."""
n = 1
phi = 1
primes = []
while True:
primes.append(p)
n *= p
phi *= (p - 1)
if n.bit_length() >= 8192:
break
p = nextprime(nextprime(p))
if n in n_candidate:
d = inverse(e, phi)
return n, e, d
return None, None, None
def decrypt(p, q, encrypted, e=65537):
"""Decrypt ciphertext using reconstructed RSA private key."""
n = p * q
phi = (p - 1) * (q - 1)
d = inverse(e, phi)
private_key = RSA.construct((n, e, d, p, q))
public_key = private_key.publickey()
cipher_decrypt = PKCS1_OAEP.new(private_key)
key_size = public_key.size_in_bytes()
chunk_size = key_size # ciphertext chunk size
decrypted_data = b""
for i in range(0, len(encrypted), chunk_size):
chunk = encrypted[i:i + chunk_size]
decrypted_data += cipher_decrypt.decrypt(chunk)
return decrypted_data
def find_factor_1(x):
"""Brute-force factor using small values."""
for i in range(32767, 65537):
if gcd(x, i) < 3000:
continue
p = i
q = x // i
return p, q
# === MAIN PROGRAM ===
if __name__ == "__main__":
# Load public key
with open("public.pem", "rb") as f:
public_key = RSA.import_key(f.read())
# Load encrypted file
with open("encrypted", "rb") as f:
ct = f.read()
n = public_key.n
e = public_key.e
# Factor n (rough guess)
p, q = find_factor_1(n)
# Decrypt with small p and q
ct_2 = bytes_to_long(decrypt(p, q, ct))
# Build candidate list near q
n_candidate = [q - i for i in range(100000)]
# Try root extraction to find 512-bit base
to_pr = []
for j in range(1, 50):
n_pr = iroot(q, j)[0]
if n_pr.bit_length() == 512:
to_pr.append(n_pr)
prim = to_pr[0]
sav = []
# Start prime search
start_time = time.time()
while True:
if time.time() - start_time > 10:
break
if isPrime(prim):
found = False
for N in n_candidate:
if gcd(prim, N) != 1:
if prim not in sav:
sav.append(prim)
print(f"[+] Found: {prim}")
found = True
break
prim = prevprime(prevprime(prim)) if found else prevprime(prim)
else:
prim = prevprime(prim)
print("Saved primes:", sav)
print("Last checked prime:", prim)
# Generate RSA params using last saved prime
f_pr = sav[-1]
n, e, d = generate_large_prime_product(f_pr, n_candidate)
# Decrypt the actual flag
if n and d:
flag = long_to_bytes(pow(ct_2, d, n))
print(flag.decode())
else:
print("Failed to generate valid RSA parameters.")
✅ Conclusion
This encryption mechanism is flawed due to:
- Use of many closely spaced primes to generate a large modulus.
- Use of a predictable updated prime via
nextprime(n). - Use of a weak 16-bit prime for RSA key generation.
These flaws break RSA’s security assumptions and allow full decryption of the encrypted flag.
- Flag:
Meta4Sec{l0r3m_1p5um_d0l0r_517_4m37_de6e5}
“Capture The Flag is not just a game. It’s a journey to mastering cybersecurity.”
#HappyHacking 🔐
