repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2018/crypto/gmx/gm.py | ctfs/angstromCTF/2018/crypto/gmx/gm.py | from Crypto.Util.number import *
from gmpy2 import legendre
def generate():
p = getStrongPrime(1024)
q = getStrongPrime(1024)
n = p*q
x = getRandomRange(0, n)
while legendre(x, p) != -1 or legendre(x, q) != -1:
x = getRandomRange(0, n)
return (n, x), (p, q)
def encrypt(m, pk):
n, x = pk
for b in format(int(m.encode('hex'), 16), 'b').zfill(len(m) * 8):
y = getRandomRange(0, n)
yield pow(y, 2) * pow(x, int(b)) % n
def decrypt(c, sk):
p, q = sk
m = 0
for z in c:
m <<= 1
if legendre(z % p, p) != 1 or legendre(z % q, q) != 1:
m += 1
h = '%x' % m
l = len(h)
return h.zfill(l + l % 2).decode('hex') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2018/crypto/gmx/gen.py | ctfs/angstromCTF/2018/crypto/gmx/gen.py | from Crypto import Random
import aes
import gm
flag = open('flag').read()
key = Random.new().read(16)
pk, sk = gm.generate()
encflag = aes.encrypt(key, flag)
enckey = gm.encrypt(key, pk)
with open('pk', 'w') as f:
f.write('\n'.join([str(x) for x in pk]))
with open('sk', 'w') as f:
f.write('\n'.join([str(x) for x in sk]))
with open('key.enc', 'w') as f:
f.write('\n'.join([str(x) for x in enckey]))
with open('flag.enc', 'w') as f:
f.write(encflag) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2018/crypto/gmx/server.py | ctfs/angstromCTF/2018/crypto/gmx/server.py | import base64
import signal
import SocketServer
import aes
import gm
PORT = 3000
message = open('message').read()
with open('sk') as f:
p = int(f.readline())
q = int(f.readline())
sk = (p, q)
class incoming(SocketServer.BaseRequestHandler):
def handle(self):
req = self.request
def receive():
buf = ''
while not buf.endswith('\n'):
buf += req.recv(1)
return buf[:-1]
signal.alarm(60)
req.sendall('Welcome to the Goldwasser-Micali key exchange!\n')
req.sendall('Please send us an encrypted 128 bit key for us to use.\n')
req.sendall('Each encrypted bit should be sent line by line in integer format.\n')
enckey = []
for i in range(128):
enckey.append(int(receive()))
key = gm.decrypt(enckey, sk)
encmessage = aes.encrypt(key, message)
req.sendall(base64.b64encode(encmessage)+'\n')
req.close()
class ReusableTCPServer(SocketServer.ForkingMixIn, SocketServer.TCPServer):
pass
SocketServer.TCPServer.allow_reuse_address = True
server = ReusableTCPServer(('0.0.0.0', PORT), incoming)
print 'Server listening on port %d' % PORT
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2018/crypto/gmx/aes.py | ctfs/angstromCTF/2018/crypto/gmx/aes.py | from Crypto import Random
from Crypto.Cipher import AES
def encrypt(k, m):
iv = Random.new().read(16)
cipher = AES.new(k, AES.MODE_CFB, iv)
return iv + cipher.encrypt(m)
def decrypt(k, c):
cipher = AES.new(k, AES.MODE_CFB, c[:16])
return cipher.decrypt(c[16:]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/misc/pycjail_returns/chall.py | ctfs/angstromCTF/2024/misc/pycjail_returns/chall.py | #!/usr/local/bin/python
import opcode
cod = bytes.fromhex(input("cod? "))
name = input("name? ")
if len(cod) > 20 or len(cod) % 2 != 0 or len(name) > 16:
print("my memory is really bad >:(")
exit(1)
# can't hack me if I just ban every opcode
banned = set(opcode.opmap.values())
for i in range(0, len(cod), 2):
[op, arg] = cod[i:i + 2]
if op in banned:
print("your code is sus >:(")
exit(1)
if arg > 10:
print("I can't count that high >:(")
exit(1)
def f():
pass
f.__code__ = f.__code__.replace(co_names=(name,), co_code=cod)
f()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/pwn/presidential/source.py | ctfs/angstromCTF/2024/pwn/presidential/source.py | #!/usr/local/bin/python
import ctypes
import mmap
import sys
flag = "redacted"
print("White House declared Python to be memory safe :tm:")
buf = mmap.mmap(-1, mmap.PAGESIZE, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
ftype = ctypes.CFUNCTYPE(ctypes.c_void_p)
fpointer = ctypes.c_void_p.from_buffer(buf)
f = ftype(ctypes.addressof(fpointer))
u_can_do_it = bytes.fromhex(input("So enter whatever you want 👍 (in hex): "))
buf.write(u_can_do_it)
f()
del fpointer
buf.close()
print("byebye")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/crypto/PHIlosophy/chall.py | ctfs/angstromCTF/2024/crypto/PHIlosophy/chall.py | from Crypto.Util.number import getPrime
from secret import flag
p = getPrime(512)
q = getPrime(512)
m = int.from_bytes(flag.encode(), "big")
n = p * q
e = 65537
c = pow(m, e, n)
phi = (p + 1) * (q + 1)
print(f"n: {n}")
print(f"e: {e}")
print(f"c: {c}")
print(f"\"phi\": {phi}")
"""
n: 86088719452932625928188797700212036385645851492281481088289877829109110203124545852827976798704364393182426900932380436551569867036871171400190786913084554536903236375579771401257801115918586590639686117179685431627540567894983403579070366895343181435791515535593260495162656111028487919107927692512155290673
e: 65537
c: 64457111821105649174362298452450091137161142479679349324820456191542295609033025036769398863050668733308827861582321665479620448998471034645792165920115009947792955402994892700435507896792829140545387740663865218579313148804819896796193817727423074201660305082597780007494535370991899386707740199516316196758
"phi": 86088719452932625928188797700212036385645851492281481088289877829109110203124545852827976798704364393182426900932380436551569867036871171400190786913084573410416063246853198167436938724585247461433706053188624379514833802770205501907568228388536548010385588837258085711058519777393945044905741975952241886308
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/crypto/tss1/tss1.py | ctfs/angstromCTF/2024/crypto/tss1/tss1.py | from hashlib import sha256
import fastecdsa.curve
import fastecdsa.keys
import fastecdsa.point
TARGET = b'flag'
curve = fastecdsa.curve.secp256k1
def input_point():
x = int(input('x: '))
y = int(input('y: '))
return fastecdsa.point.Point(x, y, curve=curve)
def input_sig():
c = int(input('c: '))
s = int(input('s: '))
return (c, s)
def hash_transcript(pk, R, msg):
h = sha256()
h.update(f'({pk.x},{pk.y})'.encode())
h.update(f'({R.x},{R.y})'.encode())
h.update(msg)
return int.from_bytes(h.digest(), 'big') % curve.q
def verify(pk, msg, sig):
c, s = sig
R = s * curve.G + c * pk
return c == hash_transcript(pk, R, msg)
if __name__ == '__main__':
import sys
if len(sys.argv) == 2 and sys.argv[1] == 'setup':
sk1, pk1 = fastecdsa.keys.gen_keypair(curve)
with open('key.txt', 'w') as f:
f.write(f'{sk1}\n{pk1.x}\n{pk1.y}\n')
exit()
with open('key.txt') as f:
sk1, x, y = map(int, f.readlines())
pk1 = fastecdsa.point.Point(x, y, curve=curve)
print(f'my public key: {(pk1.x, pk1.y)}')
print('gimme your public key')
pk2 = input_point()
apk = pk1 + pk2
print(f'aggregate public key: {(apk.x, apk.y)}')
print('what message do you want to sign?')
msg = bytes.fromhex(input('message: '))
if msg == TARGET:
print('anything but that')
exit()
k1, R1 = fastecdsa.keys.gen_keypair(curve)
print(f'my nonce: {(R1.x, R1.y)}')
print(f'gimme your nonce')
R2 = input_point()
R = R1 + R2
print(f'aggregate nonce: {(R.x, R.y)}')
c = hash_transcript(apk, R, msg)
s = (k1 - c * sk1) % curve.q
print(f'my share of the signature: {s}')
print(f'gimme me the aggregate signature for "{TARGET}"')
sig = input_sig()
if verify(apk, TARGET, sig):
with open('flag.txt') as f:
flag = f.read().strip()
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/crypto/tss2/tss2.py | ctfs/angstromCTF/2024/crypto/tss2/tss2.py | #!/usr/local/bin/python
from hashlib import sha256
import fastecdsa.curve
import fastecdsa.keys
import fastecdsa.point
TARGET = b'flag'
curve = fastecdsa.curve.secp256k1
def input_point():
x = int(input('x: '))
y = int(input('y: '))
return fastecdsa.point.Point(x, y, curve=curve)
def input_sig():
c = int(input('c: '))
s = int(input('s: '))
return (c, s)
def hash_transcript(pk, R, msg):
h = sha256()
h.update(f'({pk.x},{pk.y})'.encode())
h.update(f'({R.x},{R.y})'.encode())
h.update(msg)
return int.from_bytes(h.digest(), 'big') % curve.q
def verify(pk, msg, sig):
c, s = sig
R = s * curve.G + c * pk
return c == hash_transcript(pk, R, msg)
if __name__ == '__main__':
import sys
if len(sys.argv) == 2 and sys.argv[1] == 'setup':
sk1, pk1 = fastecdsa.keys.gen_keypair(curve)
with open('key.txt', 'w') as f:
f.write(f'{sk1}\n{pk1.x}\n{pk1.y}\n')
exit()
with open('key.txt') as f:
sk1, x, y = map(int, f.readlines())
pk1 = fastecdsa.point.Point(x, y, curve=curve)
print(f'my public key: {(pk1.x, pk1.y)}')
print('gimme your public key')
pk2 = input_point()
print('prove it!')
sig = input_sig()
if not verify(pk2, b'foo', sig):
print('boo')
exit()
apk = pk1 + pk2
print(f'aggregate public key: {(apk.x, apk.y)}')
print('what message do you want to sign?')
msg = bytes.fromhex(input('message: '))
if msg == TARGET:
print('anything but that')
exit()
k1, R1 = fastecdsa.keys.gen_keypair(curve)
print(f'my nonce: {(R1.x, R1.y)}')
print(f'gimme your nonce')
R2 = input_point()
R = R1 + R2
print(f'aggregate nonce: {(R.x, R.y)}')
c = hash_transcript(apk, R, msg)
s = (k1 - c * sk1) % curve.q
print(f'my share of the signature: {s}')
print(f'gimme me the aggregate signature for "{TARGET}"')
sig = input_sig()
if verify(apk, TARGET, sig):
with open('flag.txt') as f:
flag = f.read().strip()
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/crypto/random_rabin/random_rabin.py | ctfs/angstromCTF/2024/crypto/random_rabin/random_rabin.py | from random import SystemRandom
from Crypto.Util.number import getPrime
from libnum import xgcd
random = SystemRandom()
def primegen():
while True:
p = getPrime(512)
if p % 4 == 3:
return p
def keygen():
p = primegen()
q = primegen()
n = p * q
return n, (n, p, q)
def encrypt(pk, m):
n = pk
return pow(m, 2, n)
def decrypt(sk, c):
n, p, q = sk
yp, yq, _ = xgcd(p, q)
mp = pow(c, (p + 1)//4, p)
mq = pow(c, (q + 1)//4, q)
s = yp * p * mq % n
t = yq * q * mp % n
rs = [(s + t) % n, (-s - t) % n, (s - t) % n, (-s + t) % n]
r = random.choice(rs)
return r
def game():
pk, sk = keygen()
print(f'pubkey: {pk}')
secret = random.randbytes(16)
m = int.from_bytes(secret, 'big')
print(f'plaintext: {decrypt(sk, encrypt(pk, m))}')
guess = bytes.fromhex(input('gimme the secret: '))
return guess == secret
if __name__ == '__main__':
for _ in range(64):
success = game()
if not success:
exit()
with open('flag.txt') as f:
flag = f.read().strip()
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/crypto/layers/challenge.py | ctfs/angstromCTF/2024/crypto/layers/challenge.py | import hashlib
import itertools
import os
def xor(key, data):
return bytes([k ^ d for k, d in zip(itertools.cycle(key), data)])
def encrypt(phrase, message, iters=1000):
key = phrase.encode()
for _ in range(iters):
key = hashlib.md5(key).digest()
message = xor(key, message)
return message
print('Welcome to my encryption service!')
print('Surely encrypting multiple times will make it more secure.')
print('1. Encrypt message.')
print('2. Encrypt (hex) message.')
print('3. See encrypted flag!')
phrase = os.environ.get('FLAG', 'missing')
choice = input('Pick 1, 2, or 3 > ')
if choice == '1':
message = input('Your message > ').encode()
encrypted = encrypt(phrase, message)
print(encrypted.hex())
if choice == '2':
message = bytes.fromhex(input('Your message > '))
encrypted = encrypt(phrase, message)
print(encrypted.hex())
elif choice == '3':
print(encrypt(phrase, phrase.encode()).hex())
else:
print('Not sure what that means.')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/crypto/Simon_Says/simon_says.py | ctfs/angstromCTF/2024/crypto/Simon_Says/simon_says.py | class Simon:
n = 64
m = 4
z = 0b01100111000011010100100010111110110011100001101010010001011111
def __init__(self, k, T):
self.T = T
self.k = self.schedule(k)
def S(self, x, j):
j = j % self.n
return ((x << j) | (x >> (self.n - j))) & 0xffffffffffffffff
def schedule(self, k):
k = k[:]
for i in range(self.m, self.T):
tmp = self.S(k[i - 1], -3)
if self.m == 4:
tmp ^= k[i - 3]
tmp ^= self.S(tmp, -1)
zi = (self.z >> ((i - self.m) % 62)) & 1
k.append(k[i - self.m] ^ tmp ^ zi ^ 0xfffffffffffffffc)
return k
def encrypt(self, x, y):
for i in range(self.T):
tmp = x
x = y ^ (self.S(x, 1) & self.S(x, 8)) ^ self.S(x, 2) ^ self.k[i]
y = tmp
return x, y
def encrypt(simon, pt):
ct = bytes()
for i in range(0, len(pt), 16):
x = int.from_bytes(pt[i:i+8], 'big')
y = int.from_bytes(pt[i+8:i+16], 'big')
x, y = simon.encrypt(x, y)
ct += x.to_bytes(8, 'big')
ct += y.to_bytes(8, 'big')
return ct
if __name__ == '__main__':
from random import SystemRandom
random = SystemRandom()
with open('flag.txt') as f:
flag = f.read().strip().encode()
key = [random.getrandbits(64) for _ in range(4)]
simon68 = Simon(key, 68) # secure
simon69 = Simon(key, 69) # super secure
simon72 = Simon(key, 72) # ultra secure
pt = flag + bytes(-len(flag) % 16)
print(encrypt(simon68, pt).hex())
print(encrypt(simon69, pt).hex())
print(encrypt(simon72, pt).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/web/pastebin/main.py | ctfs/angstromCTF/2024/web/pastebin/main.py | import hashlib
import html
import os
import secrets
from server import Server
ADMIN_PASSWORD = hashlib.md5(
f'password-{secrets.token_hex}'.encode()
).hexdigest()
pastes = {}
def add_paste(paste_id, content, admin_only=False):
pastes[paste_id] = {
'content': content,
'admin_only': admin_only,
}
server = Server()
@server.get('/')
async def root(request):
del request
return (200, '''
<link rel="stylesheet" href="/style.css">
<div class="container">
<h1>Pastebin</h1>
<form action="/paste" method="post">
<textarea
name="content"
rows="10"
placeholder="Content..."
></textarea>
<input type="submit" value="Create Paste">
</form>
</div>
''')
@server.post('/paste')
async def paste(request):
data = await request.post()
content = data.get('content', '')
paste_id = id(content)
add_paste(paste_id, content)
return (200, f'''
<link rel="stylesheet" href="/style.css">
<div class="container">
<h1>Paste Created</h1>
<p><a href="/view?id={paste_id}">View Paste</a></p>
</div>
''')
@server.get('/view')
async def view_paste(request):
id = request.query.get('id')
paste = pastes.get(int(id))
if paste is None:
return (404, 'Paste not found')
if paste['admin_only']:
password = request.query.get('password', '')
if password != ADMIN_PASSWORD:
return (
403,
f'Incorrect parameter &password={ADMIN_PASSWORD[:6]}...',
)
return (200, f'''
<link rel="stylesheet" href="/style.css">
<div class="container">
<h1>Paste</h1>
<pre>{html.escape(paste['content'])}</pre>
</div>
''')
@server.get('/style.css', c_type='text/css')
async def style(request):
del request
return (200, '''
* {
font-family: system-ui, -apple-system, BlinkMacSystemFont,
'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
box-sizing: border-box;
}
html,
body {
margin: 0;
}
.container {
padding: 2rem;
width: 90%;
max-width: 900px;
margin: auto;
}
input:not([type='submit']) {
width: 100%;
padding: 8px;
margin: 8px 0;
}
textarea {
width: 100%;
padding: 8px;
margin: 8px 0;
resize: vertical;
font-family: monospace;
}
input[type='submit'] {
margin-bottom: 16px;
}
''')
add_paste(0, os.getenv('FLAG', 'missing flag'), admin_only=True)
server.run('0.0.0.0', 3000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2024/web/winds/app.py | ctfs/angstromCTF/2024/web/winds/app.py | import random
from flask import Flask, redirect, render_template_string, request
app = Flask(__name__)
@app.get('/')
def root():
return render_template_string('''
<link rel="stylesheet" href="/style.css">
<div class="content">
<h1>The windy hills</h1>
<form action="/shout" method="POST">
<input type="text" name="text" placeholder="Hello!">
<input type="submit" value="Shout your message...">
</form>
<div style="color: red;">{{ error }}</div>
</div>
''', error=request.args.get('error', ''))
@app.post('/shout')
def shout():
text = request.form.get('text', '')
if not text:
return redirect('/?error=No message provided...')
random.seed(0)
jumbled = list(text)
random.shuffle(jumbled)
jumbled = ''.join(jumbled)
return render_template_string('''
<link rel="stylesheet" href="/style.css">
<div class="content">
<h1>The windy hills</h1>
<form action="/shout" method="POST">
<input type="text" name="text" placeholder="Hello!">
<input type="submit" value="Shout your message...">
</form>
<div style="color: red;">{{ error }}</div>
<div>
Your voice echoes back: %s
</div>
</div>
''' % jumbled, error=request.args.get('error', ''))
@app.get('/style.css')
def style():
return '''
html, body { margin: 0 }
.content {
padding: 2rem;
width: 90%;
max-width: 900px;
margin: auto;
font-family: Helvetica, sans-serif;
display: flex;
flex-direction: column;
gap: 1rem;
}
'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Classy_Cipher/classy_cipher.py | ctfs/angstromCTF/2019/crypto/Classy_Cipher/classy_cipher.py | from secret import flag, shift
def encrypt(d, s):
e = ''
for c in d:
e += chr((ord(c)+s) % 0xff)
return e
assert encrypt(flag, shift) == ':<M?TLH8<A:KFBG@V' | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Lattice_ZKP/otp.py | ctfs/angstromCTF/2019/crypto/Lattice_ZKP/otp.py | import numpy as np
from Crypto.Hash import SHAKE256
from Crypto.Util.strxor import strxor
def encrypt(s, flag):
raw = bytes(np.mod(s, 256).tolist())
shake = SHAKE256.new()
shake.update(raw)
pad = shake.read(len(flag))
return strxor(flag, pad) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Lattice_ZKP/lwe.py | ctfs/angstromCTF/2019/crypto/Lattice_ZKP/lwe.py | import numpy as np
n = 640
q = 1 << 15
sigma = 2.75
public = lambda: np.random.randint(q, size=(n, n))
secret = lambda: np.random.randint(q, size=n)
error = lambda: np.rint(np.random.normal(0, sigma, n)).astype(int)
def add(x, y):
return np.mod(x+y, q)
def mul(A, x):
return np.mod(np.matmul(A, x), q)
def sample(A):
s = secret()
b = add(mul(A, s), error())
return s, b | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Lattice_ZKP/server.py | ctfs/angstromCTF/2019/crypto/Lattice_ZKP/server.py | import binascii
import numpy as np
import socketserver
from Crypto.Util.asn1 import DerSequence
import lwe
welcome = rb'''
__ __ __ _ __
/ /___ _/ /_/ /_(_)_______ ____ / /______
/ / __ `/ __/ __/ / ___/ _ \ /_ / / //_/ __ \
/ / /_/ / /_/ /_/ / /__/ __/ / /_/ ,< / /_/ /
/_/\__,_/\__/\__/_/\___/\___/ /___/_/|_/ .___/
/_/
Query until you are convinced that I know s, where
b = A*s + e
'''
choices = b'''\
[0] r
[1] r+s'''
with open('A.npy', 'rb') as f:
A = np.load(f)
with open('s.npy', 'rb') as f:
s = np.load(f)
pack = lambda x: binascii.hexlify(DerSequence(x.tolist()).encode())
def handle(self):
self.write(welcome)
r, b = lwe.sample(A)
self.write(b'A*r + e: %b' % pack(b))
self.write(choices)
choice = self.query(b'Choice: ')
if choice == b'0':
self.write(b'r: %b' % pack(r))
elif choice == b'1':
self.write(b'r+s: %b' % pack(lwe.add(r, s)))
else:
self.write(b'Invalid choice.')
class RequestHandler(socketserver.BaseRequestHandler):
handle = handle
def read(self, until=b'\n'):
out = b''
while not out.endswith(until):
out += self.request.recv(1)
return out[:-len(until)]
def query(self, string=b''):
self.write(string, newline=False)
return self.read()
def write(self, string, newline=True):
self.request.sendall(string)
if newline:
self.request.sendall(b'\n')
class Server(socketserver.ForkingTCPServer):
allow_reuse_address = True
def handle_error(self, request, client_address):
pass
port = 3000
server = Server(('0.0.0.0', port), RequestHandler)
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Secret_Sheep_Society/__init__.py | ctfs/angstromCTF/2019/crypto/Secret_Sheep_Society/__init__.py | from .app import app | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Secret_Sheep_Society/manager.py | ctfs/angstromCTF/2019/crypto/Secret_Sheep_Society/manager.py | import base64
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
class Manager:
BLOCK_SIZE = AES.block_size
def __init__(self, key):
self.key = key
def pack(self, session):
cipher = AES.new(self.key, AES.MODE_CBC)
iv = cipher.iv
dec = json.dumps(session).encode()
enc = cipher.encrypt(pad(dec, self.BLOCK_SIZE))
raw = iv + enc
return base64.b64encode(raw)
def unpack(self, token):
raw = base64.b64decode(token)
iv = raw[:self.BLOCK_SIZE]
enc = raw[self.BLOCK_SIZE:]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
dec = unpad(cipher.decrypt(enc), self.BLOCK_SIZE)
return json.loads(dec.decode()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Secret_Sheep_Society/app.py | ctfs/angstromCTF/2019/crypto/Secret_Sheep_Society/app.py | from flask import Flask
from flask import request
from flask import redirect, render_template
from .secret import flag, key
from .manager import Manager
app = Flask(__name__)
manager = Manager(key)
@app.route('/')
def index():
try:
token = request.cookies.get('token')
session = manager.unpack(token)
return render_template('index.html', session=session, flag=flag)
except:
pass
return render_template('index.html')
@app.route('/enter', methods=['POST'])
def enter():
handle = request.form.get('handle')
session = {
'admin': False,
'handle': handle
}
token = manager.pack(session)
response = redirect('/')
response.set_cookie('token', token)
return response
@app.route('/exit', methods=['POST'])
def exit():
response = redirect('/')
response.set_cookie('token', expires=0)
return response
if __name__ == "__main__":
app.run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Random_ZKP/otp.py | ctfs/angstromCTF/2019/crypto/Random_ZKP/otp.py | import numpy as np
from Crypto.Hash import SHAKE256
from Crypto.Util.strxor import strxor
def encrypt(s, flag):
raw = bytes(np.mod(s, 256).tolist())
shake = SHAKE256.new()
shake.update(raw)
pad = shake.read(len(flag))
return strxor(flag, pad) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Random_ZKP/lwe.py | ctfs/angstromCTF/2019/crypto/Random_ZKP/lwe.py | import numpy as np
import os
from Crypto.Util.number import getRandomInteger
n = 640
b = 15
q = 1 << b
sigma = 2.75
public = lambda: np.array([[getRandomInteger(b) for _ in range(n)] for _ in range(n)])
secret = lambda: np.array([getRandomInteger(b) for _ in range(n)])
def error():
np.random.seed(getRandomInteger(32))
return np.rint(np.random.normal(0, sigma, n)).astype(int)
def add(x, y):
return np.mod(x+y, q)
def mul(A, x):
return np.mod(np.matmul(A, x), q)
def sample(A):
s = secret()
b = add(mul(A, s), error())
return s, b | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Random_ZKP/server.py | ctfs/angstromCTF/2019/crypto/Random_ZKP/server.py | import binascii
import numpy as np
import signal
import socketserver
from Crypto.Util.asn1 import DerSequence
import lwe
welcome = rb'''
__ __
_________ _____ ____/ /___ ____ ___ ____ / /______
/ ___/ __ `/ __ \/ __ / __ \/ __ `__ \ /_ / / //_/ __ \
/ / / /_/ / / / / /_/ / /_/ / / / / / / / /_/ ,< / /_/ /
/_/ \__,_/_/ /_/\__,_/\____/_/ /_/ /_/ /___/_/|_/ .___/
/_/
Query until you are convinced that I know s, where
b = A*s + e
'''
choices = b'''\
[0] r
[1] r+s'''
with open('A.npy', 'rb') as f:
A = np.load(f)
with open('s.npy', 'rb') as f:
s = np.load(f)
pack = lambda x: binascii.hexlify(DerSequence(x.tolist()).encode())
def handle(self):
signal.alarm(60)
self.write(welcome)
r, b = lwe.sample(A)
self.write(b'A*r + e: %b' % pack(b))
self.write(choices)
choice = self.query(b'Choice: ')
if choice == b'0':
self.write(b'r: %b' % pack(r))
elif choice == b'1':
self.write(b'r+s: %b' % pack(lwe.add(r, s)))
else:
self.write(b'Invalid choice.')
self.close()
class RequestHandler(socketserver.BaseRequestHandler):
handle = handle
def read(self, until=b'\n'):
out = b''
while not out.endswith(until):
out += self.request.recv(1)
return out[:-len(until)]
def query(self, string=b''):
self.write(string, newline=False)
return self.read()
def write(self, string, newline=True):
self.request.sendall(string)
if newline:
self.request.sendall(b'\n')
def close(self):
self.request.close()
class Server(socketserver.ForkingTCPServer):
allow_reuse_address = True
def handle_error(self, request, client_address):
self.request.close()
port = 3000
server = Server(('0.0.0.0', port), RequestHandler)
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Half_and_Half/half_and_half.py | ctfs/angstromCTF/2019/crypto/Half_and_Half/half_and_half.py | from secret import flag
def xor(x, y):
o = ''
for i in range(len(x)):
o += chr(ord(x[i])^ord(y[i]))
return o
assert len(flag) % 2 == 0
half = len(flag)//2
milk = flag[:half]
cream = flag[half:]
assert xor(milk, cream) == '\x15\x02\x07\x12\x1e\x100\x01\t\n\x01"' | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Powerball/server.py | ctfs/angstromCTF/2019/crypto/Powerball/server.py | import socketserver
from Crypto.Util.number import getRandomRange
from secret import flag
welcome = b'''\
************ ANGSTROMCTF POWERBALL ************
Correctly guess all 6 ball values ranging from 0
to 4095 to win the jackpot! As a special deal,
we'll also let you secretly view a ball's value!
'''
with open('public.txt') as f:
n = int(f.readline()[3:])
e = int(f.readline()[3:])
with open('private.txt') as f:
d = int(f.readline()[3:])
def handle(self):
self.write(welcome)
balls = [getRandomRange(0, 4096) for _ in range(6)]
x = [getRandomRange(0, n) for _ in range(6)]
self.write('x: {}\n'.format(x).encode())
v = int(self.query(b'v: '))
m = []
for i in range(6):
k = pow(v-x[i], d, n)
m.append((balls[i]+k) % n)
self.write('m: {}\n'.format(m).encode())
guess = []
for i in range(6):
guess.append(int(self.query('Ball {}: '.format(i+1).encode())))
if balls == guess:
self.write(b'JACKPOT!!!')
self.write(flag)
else:
self.write(b'Sorry, those were the wrong numbers.')
class RequestHandler(socketserver.BaseRequestHandler):
handle = handle
def read(self, until=b'\n'):
out = b''
while not out.endswith(until):
out += self.request.recv(1)
return out[:-len(until)]
def query(self, string=b''):
self.write(string, newline=False)
return self.read()
def write(self, string, newline=True):
self.request.sendall(string)
if newline:
self.request.sendall(b'\n')
class Server(socketserver.ForkingTCPServer):
allow_reuse_address = True
def handle_error(self, request, client_address):
pass
port = 3000
server = Server(('0.0.0.0', port), RequestHandler)
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Paint/paint.py | ctfs/angstromCTF/2019/crypto/Paint/paint.py | import binascii
import random
from secret import flag
image = int(binascii.hexlify(flag), 16)
palette = 1 << 2048
base = random.randint(0, palette) | 1
secret = random.randint(0, palette)
my_mix = pow(base, secret, palette)
print('palette: {}'.format(palette))
print('base: {}'.format(base))
print('my mix: {}'.format(my_mix))
your_mix = int(input('your mix: '))
shared_mix = pow(your_mix, secret, palette)
painting = image ^ shared_mix
print('painting: {}'.format(painting)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Eightball/benaloh.py | ctfs/angstromCTF/2019/crypto/Eightball/benaloh.py | from gmpy2 import div, gcd, invert, powmod
from Crypto.Util.number import getPrime, getRandomRange
def unpack(fn):
with open(fn, 'r') as f:
return tuple([int(x) for x in f.readlines()])
def pack(fn, k):
with open(fn, 'w') as f:
f.write('\n'.join([str(x) for x in k]))
def generate():
r = 257
while True:
p = getPrime(1024)
if (p-1) % r == 0 and gcd(r, div(p-1, r)) == 1:
break
while True:
q = getPrime(1024)
if gcd(r, q-1) == 1:
break
n = p*q
phi = (p-1)*(q-1)
while True:
y = getRandomRange(0, n)
x = powmod(y, phi*invert(r, n) % n, n)
if x != 1:
break
return (n, y), (n, phi, x)
def encrypt(m, pk):
r = 257
n, y = pk
u = getRandomRange(0, n)
return powmod(y, m, n)*powmod(u, r, n) % n
def decrypt(c, sk):
r = 257
n, phi, x = sk
a = powmod(c, phi*invert(r, n) % n, n)
for i in range(256):
if powmod(x, i, n) == a:
return i
return 0 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/Eightball/server.py | ctfs/angstromCTF/2019/crypto/Eightball/server.py | import binascii
import socketserver
from Crypto.Random.random import choice
from Crypto.Util.asn1 import DerSequence
import benaloh
answers = [
b'It is certain',
b'It is decidedly so',
b'Without a doubt',
b'Yes definitely',
b'You may rely on it',
b'As I see it, yes',
b'Most likely',
b'Outlook good',
b'Yes',
b'Signs point to yes',
b'Reply hazy try again',
b'Ask again later',
b'Better not tell you now',
b'Cannot predict now',
b'Concentrate and ask again',
b'Don\'t count on it',
b'My reply is no',
b'My sources say no',
b'Outlook not so good',
b'Very doubtful'
]
sk = benaloh.unpack('sk')
def handle(self):
while True:
der = DerSequence()
der.decode(binascii.unhexlify(self.query(b'Question: ')))
question = bytes([benaloh.decrypt(c, sk) for c in der])
response = choice(answers)
self.write(response)
class RequestHandler(socketserver.BaseRequestHandler):
handle = handle
def read(self, until=b'\n'):
out = b''
while not out.endswith(until):
out += self.request.recv(1)
return out[:-len(until)]
def query(self, string=b''):
self.write(string, newline=False)
return self.read()
def write(self, string, newline=True):
self.request.sendall(string)
if newline:
self.request.sendall(b'\n')
class Server(socketserver.ForkingTCPServer):
allow_reuse_address = True
def handle_error(self, request, client_address):
pass
port = 3000
server = Server(('0.0.0.0', port), RequestHandler)
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/MAC_Forgery/cbc_mac.py | ctfs/angstromCTF/2019/crypto/MAC_Forgery/cbc_mac.py | from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad
from Crypto.Util.number import long_to_bytes
from Crypto.Util.strxor import strxor
split = lambda s, n: [s[i:i+n] for i in range(0, len(s), n)]
class CBC_MAC:
BLOCK_SIZE = 16
def __init__(self, key):
self.key = key
def next(self, t, m):
return AES.new(self.key, AES.MODE_ECB).encrypt(strxor(t, m))
def mac(self, m, iv):
m = pad(m, self.BLOCK_SIZE)
m = split(m, self.BLOCK_SIZE)
m.insert(0, long_to_bytes(len(m), self.BLOCK_SIZE))
t = iv
for i in range(len(m)):
t = self.next(t, m[i])
return t
def generate(self, m):
iv = get_random_bytes(self.BLOCK_SIZE)
return iv, self.mac(m, iv)
def verify(self, m, iv, t):
return self.mac(m, iv) == t
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/MAC_Forgery/server.py | ctfs/angstromCTF/2019/crypto/MAC_Forgery/server.py | import binascii
import socketserver
from cbc_mac import CBC_MAC
from secret import flag, key
welcome = b'''\
If you provide a message (besides this one) with
a valid message authentication code, I will give
you the flag.'''
cbc_mac = CBC_MAC(key)
def handle(self):
iv, t = cbc_mac.generate(welcome)
self.write(welcome)
self.write(b'MAC: %b' % binascii.hexlify(iv+t))
m = binascii.unhexlify(self.query(b'Message: '))
mac = binascii.unhexlify(self.query(b'MAC: '))
assert len(mac) == 32
iv = mac[:16]
t = mac[16:]
if m != welcome and cbc_mac.verify(m, iv, t):
self.write(flag)
class RequestHandler(socketserver.BaseRequestHandler):
handle = handle
def read(self, until=b'\n'):
out = b''
while not out.endswith(until):
out += self.request.recv(1)
return out[:-len(until)]
def query(self, string=b''):
self.write(string, newline=False)
return self.read()
def write(self, string, newline=True):
self.request.sendall(string)
if newline:
self.request.sendall(b'\n')
class Server(socketserver.ForkingTCPServer):
allow_reuse_address = True
def handle_error(self, request, client_address):
pass
port = 3000
server = Server(('0.0.0.0', port), RequestHandler)
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/crypto/WALL-E/wall-e.py | ctfs/angstromCTF/2019/crypto/WALL-E/wall-e.py | from Crypto.Util.number import getPrime, bytes_to_long, inverse
from secret import flag
assert(len(flag) < 87) # leave space for padding since padding is secure
p = getPrime(1024)
q = getPrime(1024)
n = p*q
e = 3
d = inverse(e,(p-1)*(q-1))
m = bytes_to_long(flag.center(255,"\x00")) # pad on both sides for extra security
c = pow(m,e,n)
print("n = {}".format(n))
print("e = {}".format(e))
print("c = {}".format(c)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/web/Madlibbin/__init__.py | ctfs/angstromCTF/2019/web/Madlibbin/__init__.py | from .app import app | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/web/Madlibbin/app.py | ctfs/angstromCTF/2019/web/Madlibbin/app.py | import binascii
import json
import os
import re
import redis
from flask import Flask
from flask import request
from flask import redirect, render_template
from flask import abort
app = Flask(__name__)
app.secret_key = os.environ.get('FLAG')
redis = redis.Redis(host='madlibbin_redis', port=6379, db=0)
generate = lambda: binascii.hexlify(os.urandom(16)).decode()
parse = lambda x: list(dict.fromkeys(re.findall(r'(?<=\{args\[)[\w\-\s]+(?=\]\})', x)))
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def create():
tag = generate()
template = request.form.get('template', '')
madlib = {
'template': template,
'blanks': parse(template)
}
redis.set(tag, json.dumps(madlib))
return redirect('/{}'.format(tag))
@app.route('/<tag>', methods=['GET'])
def view(tag):
if redis.exists(tag):
madlib = json.loads(redis.get(tag))
if set(request.args.keys()) == set(madlib['blanks']):
return render_template('result.html', stuff=madlib['template'].format(args=request.args))
else:
return render_template('fill.html', blanks=madlib['blanks'])
else:
abort(404)
if __name__ == '__main__':
app.run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2019/web/NaaS/app.py | ctfs/angstromCTF/2019/web/NaaS/app.py | from flask import Flask, request, redirect, make_response
app = Flask(__name__)
import requests
import json
import subprocess
import random
pastes = {}
html = """<!doctype html>
<html>
<head>
<title>Yet Another Pastebin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<head>
<body style="text-align: center;">
<h1 style="color: #96cdd1; margin-top: 1.5em;">Yet Another Pastebin</h1>
<h3>Create Paste</h3>
<form method="POST">
<textarea required name="paste" style="width: 50em; height: 20em;"></textarea><br>
<button type="submit">Create</button>
</form>
</body>
</html>"""
@app.route("/", methods=["GET", "POST"])
def get_pastes():
if request.method == "POST":
p = request.form.get("paste", "")
pid = "%8x" % random.getrandbits(4*8)
pastes[pid] = p
return redirect("/" + pid)
return html
@app.route("/<string:id>")
def get_paste(id):
if id in pastes:
html = """<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<title>View Paste</title>
</head>
<body>
<pre id="paste">{}</pre>
<small id="report">If you think this paste shouldn't be here, <a href="#">report it</a>.</small>
<script>
function send () {{
fetch("/report", {{
method: "POST",
headers: {{
"Content-Type": "application/json"
}},
body: JSON.stringify({{ url: location.href }})
}})
paste.innerHTML = "An admin will review this paste shortly."
report.innerHTML = ""
}}
report.onclick = send
</script>
</body>
</html>"""
nonceify = requests.post("https://naas.2019.chall.actf.co/nonceify", data=html).json()
r = make_response(nonceify["html"].format(pastes[id]))
r.headers["Content-Security-Policy"] = nonceify["csp"]
return r
else: return redirect("/")
@app.route("/report", methods=["POST"])
def report():
print(request.get_json())
subprocess.Popen(["node", "visit.js", request.get_json()["url"]])
return "OK" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/pwn/SailorsRevenge/solve.py | ctfs/angstromCTF/2023/pwn/SailorsRevenge/solve.py | # sample solve script to interface with the server
from pwn import *
# feel free to change this
account_metas = [
("program", "-r"), # readonly
("user", "sw"), # signer + writable
("vault", "-w"), # writable
("sailor union", "-w"),
("registration", "-w"),
("rich boi", "-r"),
("system program", "-r"),
]
instruction_data = b"placeholder"
p = remote("challs.actf.co", 31404)
with open("solve.so", "rb") as f:
solve = f.read()
p.sendlineafter(b"program len: \n", str(len(solve)).encode())
p.send(solve)
accounts = {}
for l in p.recvuntil(b"num accounts: \n", drop=True).strip().split(b"\n"):
[name, pubkey] = l.decode().split(": ")
accounts[name] = pubkey
p.sendline(str(len(account_metas)).encode())
for (name, perms) in account_metas:
p.sendline(f"{perms} {accounts[name]}".encode())
p.sendlineafter(b"ix len: \n", str(len(instruction_data)).encode())
p.send(instruction_data)
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/rev/Uncertainty/stego.py | ctfs/angstromCTF/2023/rev/Uncertainty/stego.py | msg = b'REDACTED'
msgb = '0' + bin(int(msg.hex(), 16))[2:]
f = open("uncertainty", "rb").read()
b = list(f)
i = 0
bitnum = 6
for a in range(len(b)):
b[a] = (b[a] & ~(1 << bitnum)) | ((1 if msgb[i] == '1' else 0) << bitnum)
i += 1
if len(msgb) == i: i = 0
open("uncertainty_modified", "wb").write(bytes(b))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/RoyalSocietyofArts2/rsa2.py | ctfs/angstromCTF/2023/crypto/RoyalSocietyofArts2/rsa2.py | from Crypto.Util.number import getStrongPrime, bytes_to_long, long_to_bytes
f = open("flag.txt").read()
m = bytes_to_long(f.encode())
p = getStrongPrime(512)
q = getStrongPrime(512)
n = p*q
e = 65537
c = pow(m,e,n)
print("n =",n)
print("e =",e)
print("c =",c)
d = pow(e, -1, (p-1)*(q-1))
c = int(input("Text to decrypt: "))
if c == m or b"actf{" in long_to_bytes(pow(c, d, n)):
print("No flag for you!")
exit(1)
print("m =", pow(c, d, n)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/millionaires/millionaires.py | ctfs/angstromCTF/2023/crypto/millionaires/millionaires.py | #!/usr/local/bin/python
import private_set_intersection.python as psi
import base64
import secrets
def fake_psi(a, b):
return [i for i in a if i in b]
def zero_encoding(x, n):
ret = []
s = bin(x)[2:].zfill(n)
for i in range(n):
if s[i] == "0":
ret.append(s[:i] + "1")
return ret
def one_encoding(x, n):
ret = []
s = bin(x)[2:].zfill(n)
for i in range(n):
if s[i] == "1":
ret.append(s[:i+1])
return ret
def performIntersection(serverInputs):
s = psi.server.CreateWithNewKey(True)
numClientElements = int(input("Size of client set: "))
setup = s.CreateSetupMessage(0.001, numClientElements, serverInputs, psi.DataStructure.RAW)
print("Setup: ", base64.b64encode(setup.SerializeToString()).decode())
req = psi.Request()
req.ParseFromString(base64.b64decode(input("Request: ")))
resp = psi.Response()
resp.ParseFromString(s.ProcessRequest(req).SerializeToString())
print(base64.b64encode(resp.SerializeToString()).decode())
def ensure_honesty(secret, history):
print("Okay, game time's over. Hand over your inputs and let's see if you cheated me.")
for i in history:
x = int(input(": "))
if sorted(fake_psi(one_encoding(secret, NBITS), zero_encoding(x, NBITS)), key=lambda _: len(_)) != sorted(i, key=lambda _: len(_)):
print("Cheater! I'll have my people break your knees.")
exit(2)
NBITS = 256
correct = 0
for i in range(10):
print(f"Currently talking to millionaire {i+1}/10")
tries = 0
secret = secrets.randbits(NBITS)
serverInputs = one_encoding(secret, NBITS)
performIntersection(serverInputs)
tries += 1
history = []
x = input("Computed intersection: ").split(" ")
history.append(x if x != [''] else [])
while tries < 215:
performIntersection(serverInputs)
x = input("Computed intersection: ").split(" ")
history.append(x if x != [''] else [])
tries += 1
x = input("Check (y/N)? ")
if x == "y":
break
if tries < 215 and int(input("My secret: ")) == secret:
print(f"You guessed it!")
ensure_honesty(secret, history)
correct += 1
else:
print("death")
exit()
if correct == 10:
print(open("flag.txt").read()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/snap-circuits/snap-circuits.py | ctfs/angstromCTF/2023/crypto/snap-circuits/snap-circuits.py | #!/usr/local/bin/python
from collections import namedtuple
from Crypto.Hash import SHAKE128
from Crypto.Random import get_random_bytes, random
from Crypto.Util.strxor import strxor
def get_truth_table(op):
match op:
case 'and':
return [
[0, 0, 0],
[0, 1, 0],
[1, 0, 0],
[1, 1, 1],
]
case 'xor':
return [
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 0],
]
BUF_LEN = 16
def rand_bit():
return random.getrandbits(1)
def rand_buf():
return get_random_bytes(BUF_LEN)
class Wire:
Label = namedtuple('Label', 'key ptr')
def __init__(self, zero, one):
self.zero = zero
self.one = one
@classmethod
def new(cls):
bit = rand_bit()
zero = Wire.Label(rand_buf(), bit)
one = Wire.Label(rand_buf(), bit ^ 1)
return cls(zero, one)
def get_label(self, value):
match value:
case 0:
return self.zero
case 1:
return self.one
case _:
raise ValueError('cannot translate value to label')
def get_value(self, label):
match label:
case self.zero:
return 0
case self.one:
return 1
case _:
raise ValueError('cannot translate label to value')
class Cipher:
def __init__(self, *labels):
key = b''.join([l.key for l in labels])
self.shake = SHAKE128.new(key)
def xor_buf(self, buf):
return strxor(buf, self.shake.read(BUF_LEN))
def xor_bit(self, bit):
return bit ^ self.shake.read(1)[0] & 1
def encrypt(self, label):
return self.xor_buf(label.key), self.xor_bit(label.ptr)
def decrypt(self, row):
return Wire.Label(self.xor_buf(row[0]), self.xor_bit(row[1]))
def garble_gate(op, wa, wb):
wc = Wire.new()
table = [[None, None], [None, None]]
for va, vb, vc in get_truth_table(op):
la = wa.get_label(va)
lb = wb.get_label(vb)
lc = wc.get_label(vc)
table[la.ptr][lb.ptr] = Cipher(la, lb).encrypt(lc)
return wc, table
def evaluate_gate(table, la, lb):
row = table[la.ptr][lb.ptr]
return Cipher(la, lb).decrypt(row)
def garble(circuit):
wires = []
in_wires = []
out_wires = []
tables = []
for line in circuit:
match line:
case ('id',):
wire = Wire.new()
wires.append(wire)
in_wires.append(wire)
case ('id', a):
wires.append(None)
out_wires.append(wires[a])
case (op, a, b):
wire, table = garble_gate(op, wires[a], wires[b])
wires.append(wire)
tables.append(table)
return in_wires, out_wires, tables
def evaluate(circuit, in_labels, out_wires, tables):
in_labels = iter(in_labels)
out_wires = iter(out_wires)
tables = iter(tables)
labels = []
out_bits = []
for line in circuit:
match line:
case ('id',):
labels.append(next(in_labels))
case ('id', a):
labels.append(None)
out_bits.append(next(out_wires).get_value(labels[a]))
case (_, a, b):
labels.append(evaluate_gate(next(tables), labels[a], labels[b]))
return out_bits
if __name__ == '__main__':
from binteger import Bin
with open('flag.txt', 'rb') as f:
flag_bits = Bin(f.read().strip())
print(f'Welcome to Snap Circuits: Garbled Edition! You have {len(flag_bits)} inputs to work with. Only AND and XOR gates are allowed, and no outputs.')
circuit = [('id',) for _ in flag_bits]
while True:
gate = input('gate: ')
tokens = gate.split(' ')
try:
assert len(tokens) == 3
assert tokens[0] in ('and', 'xor')
assert tokens[1].isdecimal()
assert tokens[2].isdecimal()
op = tokens[0]
a = int(tokens[1])
b = int(tokens[2])
assert 0 <= a < len(circuit)
assert 0 <= b < len(circuit)
assert len(circuit) < 1000
circuit.append((op, a, b))
except:
print('moving on...')
break
in_wires, _, tables = garble(circuit)
for i, b in enumerate(flag_bits):
label = in_wires[i].get_label(b)
print(f'wire {i}: {label.key.hex()} {label.ptr}')
print('table data:')
for table in tables:
for i in range(2):
for j in range(2):
row = table[i][j]
print(f'{row[0].hex()} {row[1]}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/RoyalSocietyofArts/rsa.py | ctfs/angstromCTF/2023/crypto/RoyalSocietyofArts/rsa.py | from Crypto.Util.number import getStrongPrime, bytes_to_long
f = open("flag.txt").read()
m = bytes_to_long(f.encode())
p = getStrongPrime(512)
q = getStrongPrime(512)
n = p*q
e = 65537
c = pow(m,e,n)
print("n =",n)
print("e =",e)
print("c =",c)
print("(p-2)*(q-1) =", (p-2)*(q-1))
print("(p-1)*(q-2) =", (p-1)*(q-2)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/LazyLagrange/lazylagrange.py | ctfs/angstromCTF/2023/crypto/LazyLagrange/lazylagrange.py | #!/usr/local/bin/python
import random
with open('flag.txt', 'r') as f:
FLAG = f.read()
assert all(c.isascii() and c.isprintable() for c in FLAG), 'Malformed flag'
N = len(FLAG)
assert N <= 18, 'I\'m too lazy to store a flag that long.'
p = None
a = None
M = (1 << 127) - 1
def query1(s):
if len(s) > 100:
return 'I\'m too lazy to read a query that long.'
x = s.split()
if len(x) > 10:
return 'I\'m too lazy to process that many inputs.'
if any(not x_i.isdecimal() for x_i in x):
return 'I\'m too lazy to decipher strange inputs.'
x = (int(x_i) for x_i in x)
global p, a
p = random.sample(range(N), k=N)
a = [ord(FLAG[p[i]]) for i in range(N)]
res = ''
for x_i in x:
res += f'{sum(a[j] * x_i ** j for j in range(N)) % M}\n'
return res
query1('0')
def query2(s):
if len(s) > 100:
return 'I\'m too lazy to read a query that long.'
x = s.split()
if any(not x_i.isdecimal() for x_i in x):
return 'I\'m too lazy to decipher strange inputs.'
x = [int(x_i) for x_i in x]
while len(x) < N:
x.append(0)
z = 1
for i in range(N):
z *= not x[i] - a[i]
return ' '.join(str(p_i * z) for p_i in p)
while True:
try:
choice = int(input(": "))
assert 1 <= choice <= 2
match choice:
case 1:
print(query1(input("\t> ")))
case 2:
print(query2(input("\t> ")))
except Exception as e:
print("Bad input, exiting", e)
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/tau-as-a-service/taas.py | ctfs/angstromCTF/2023/crypto/tau-as-a-service/taas.py | #!/usr/local/bin/python
from blspy import PrivateKey as Scalar
# order of curve
n = 0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001
with open('flag.txt', 'rb') as f:
tau = int.from_bytes(f.read().strip(), 'big')
assert tau < n
while True:
d = int(input('gimme the power: '))
assert 0 < d < n
B = Scalar.from_bytes(pow(tau, d, n).to_bytes(32, 'big')).get_g1()
print(B)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/ranch/ranch.py | ctfs/angstromCTF/2023/crypto/ranch/ranch.py | import string
f = open("flag.txt").read()
encrypted = ""
shift = int(open("secret_shift.txt").read().strip())
for i in f:
if i in string.ascii_lowercase:
encrypted += chr(((ord(i) - 97 + shift) % 26)+97)
else:
encrypted += i
print(encrypted) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/crypto/impossible/impossible.py | ctfs/angstromCTF/2023/crypto/impossible/impossible.py | #!/usr/local/bin/python
def fake_psi(a, b):
return [i for i in a if i in b]
def zero_encoding(x, n):
ret = []
for i in range(n):
if (x & 1) == 0:
ret.append(x | 1)
x >>= 1
return ret
def one_encoding(x, n):
ret = []
for i in range(n):
if x & 1:
ret.append(x)
x >>= 1
return ret
print("Supply positive x and y such that x < y and x > y.")
x = int(input("x: "))
y = int(input("y: "))
if len(fake_psi(one_encoding(x, 64), zero_encoding(y, 64))) == 0 and x > y and x > 0 and y > 0:
print(open("flag.txt").read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/web/CelesteTunnelingAssociation/server.py | ctfs/angstromCTF/2023/web/CelesteTunnelingAssociation/server.py | # run via `uvicorn app:app --port 6000`
import os
SECRET_SITE = b"flag.local"
FLAG = os.environ['FLAG']
async def app(scope, receive, send):
assert scope['type'] == 'http'
headers = scope['headers']
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
# IDK malformed requests or something
num_hosts = 0
for name, value in headers:
if name == b"host":
num_hosts += 1
if num_hosts == 1:
for name, value in headers:
if name == b"host" and value == SECRET_SITE:
await send({
'type': 'http.response.body',
'body': FLAG.encode(),
})
return
await send({
'type': 'http.response.body',
'body': b'Welcome to the _tunnel_. Watch your step!!',
})
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2023/web/brokenlogin/app.py | ctfs/angstromCTF/2023/web/brokenlogin/app.py | from flask import Flask, make_response, request, escape, render_template_string
app = Flask(__name__)
fails = 0
indexPage = """
<html>
<head>
<title>Broken Login</title>
</head>
<body>
<p style="color: red; fontSize: '28px';">%s</p>
<p>Number of failed logins: {{ fails }}</p>
<form action="/" method="POST">
<label for="username">Username: </label>
<input id="username" type="text" name="username" /><br /><br />
<label for="password">Password: </label>
<input id="password" type="password" name="password" /><br /><br />
<input type="submit" />
</form>
</body>
</html>
"""
@app.get("/")
def index():
global fails
custom_message = ""
if "message" in request.args:
if len(request.args["message"]) >= 25:
return render_template_string(indexPage, fails=fails)
custom_message = escape(request.args["message"])
return render_template_string(indexPage % custom_message, fails=fails)
@app.post("/")
def login():
global fails
fails += 1
return make_response("wrong username or password", 401)
if __name__ == "__main__":
app.run("0.0.0.0") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2022/crypto/RandomlySampledAlgorithm/rsa.py | ctfs/angstromCTF/2022/crypto/RandomlySampledAlgorithm/rsa.py | from Crypto.Util.number import getStrongPrime
f = [REDACTED]
m = int.from_bytes(f,'big')
p = getStrongPrime(512)
q = getStrongPrime(512)
n = p*q
e = 65537
c = pow(m,e,n)
print("n =",n)
print("e =",e)
print("c =",c)
print("phi =",(p-1)*(q-1))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2022/crypto/Strike-SlipFault/fault.py | ctfs/angstromCTF/2022/crypto/Strike-SlipFault/fault.py | #!/usr/local/bin/python3
from Crypto.Util.number import getStrongPrime, long_to_bytes, bytes_to_long, inverse
from secrets import randbelow, token_bytes
print("Welcome to my super secret service! (under construction)")
BITS = 4096
p = getStrongPrime(BITS//2)
q = getStrongPrime(BITS//2)
n = p*q
phi = (p-1)*(q-1)
e = 65537
flag = [REDACTED]
m = bytes_to_long(flag+token_bytes(BITS//8 - len(flag) - 1))
c = pow(m,e,n)
print("Making sure nothing was tampered with...")
print("n =", n)
print("e =", e)
print("c =", c)
d = inverse(e, phi)
bits = list(range(d.bit_length()))
for i in range(3):
d ^= 1 << bits.pop(randbelow(len(bits))) # these cosmic rays man...
ans = long_to_bytes(pow(c,d,n))
if ans.startswith(flag):
print("Check passed!")
print(f"Check failed, {ans} does not start with the flag.") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2022/crypto/VinegarFactory/main.py | ctfs/angstromCTF/2022/crypto/VinegarFactory/main.py | #!/usr/local/bin/python3
import string
import os
import random
with open("flag.txt", "r") as f:
flag = f.read().strip()
alpha = string.ascii_lowercase
def encrypt(msg, key):
ret = ""
i = 0
for c in msg:
if c in alpha:
ret += alpha[(alpha.index(key[i]) + alpha.index(c)) % len(alpha)]
i = (i + 1) % len(key)
else:
ret += c
return ret
inner = alpha + "_"
noise = inner + "{}"
print("Welcome to the vinegar factory! Solve some crypto, it'll be fun I swear!")
i = 0
while True:
if i % 50 == 49:
fleg = flag
else:
fleg = "actf{" + "".join(random.choices(inner, k=random.randint(10, 50))) + "}"
start = "".join(random.choices(noise, k=random.randint(0, 2000)))
end = "".join(random.choices(noise, k=random.randint(0, 2000)))
key = "".join(random.choices(alpha, k=4))
print(f"Challenge {i}: {start}{encrypt(fleg + 'fleg', key)}{end}")
x = input("> ")
if x != fleg:
print("Nope! Better luck next time!")
break
i += 1
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2022/crypto/RSA-AES/rsaaes.py | ctfs/angstromCTF/2022/crypto/RSA-AES/rsaaes.py | from Crypto.Util.number import bytes_to_long, long_to_bytes
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from secret import flag, d
assert len(flag) < 256
n = 0xbb7bbd6bb62e0cbbc776f9ceb974eca6f3d30295d31caf456d9bec9b98822de3cb941d3a40a0fba531212f338e7677eb2e3ac05ff28629f248d0bc9f98950ce7e5e637c9764bb7f0b53c2532f3ce47ecbe1205172f8644f28f039cae6f127ccf1137ac88d77605782abe4560ae3473d9fb93886625a6caa7f3a5180836f460c98bbc60df911637fa3f52556fa12a376e3f5f87b5956b705e4e42a30ca38c79e7cd94c9b53a7b4344f2e9de06057da350f3cd9bd84f9af28e137e5190cbe90f046f74ce22f4cd747a1cc9812a1e057b97de39f664ab045700c40c9ce16cf1742d992c99e3537663ede6673f53fbb2f3c28679fb747ab9db9753e692ed353e3551
e = 0x10001
assert pow(2,e*d,n)==2
enc = pow(bytes_to_long(flag),e,n)
print(enc)
k = get_random_bytes(32)
iv = get_random_bytes(16)
cipher = AES.new(k, AES.MODE_CBC, iv)
while 1:
try:
i = int(input("Enter message to sign: "))
assert(0 < i < n)
print("signed message (encrypted with military-grade aes-256-cbc encryption):")
print(cipher.encrypt(pad(long_to_bytes(pow(i,d,n)),16)))
except:
print("bad input, exiting")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2020/crypto/one_time_bad/server.py | ctfs/angstromCTF/2020/crypto/one_time_bad/server.py | import random, time
import string
import base64
import os
def otp(a, b):
r = ""
for i, j in zip(a, b):
r += chr(ord(i) ^ ord(j))
return r
def genSample():
p = ''.join([string.ascii_letters[random.randint(0, len(string.ascii_letters)-1)] for _ in range(random.randint(1, 30))])
k = ''.join([string.ascii_letters[random.randint(0, len(string.ascii_letters)-1)] for _ in range(len(p))])
x = otp(p, k)
return x, p, k
random.seed(int(time.time()))
print("Welcome to my one time pad service!\nIt's so unbreakable that *if* you do manage to decrypt my text, I'll give you a flag!")
print("You will be given the ciphertext and key for samples, and the ciphertext for when you try to decrypt. All will be given in base 64, but when you enter your answer, give it in ASCII.")
print("Enter:")
print("\t1) Request sample")
print("\t2) Try your luck at decrypting something!")
while True:
choice = int(input("> "))
if choice == 1:
x, p, k = genSample()
print(base64.b64encode(x.encode()).decode(), "with key", base64.b64encode(k.encode()).decode())
elif choice == 2:
x, p, k = genSample()
print(base64.b64encode(x.encode()).decode())
a = input("Your answer: ").strip()
if a == p:
print(os.environ.get("FLAG"))
break
else:
print("Wrong! The correct answer was", p, "with key", k)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2020/crypto/Dream_Stream/chall.py | ctfs/angstromCTF/2020/crypto/Dream_Stream/chall.py | from __future__ import print_function
import random,os,sys,binascii
from Crypto.Util.number import isPrime
from decimal import *
try:
input = raw_input
except:
pass
getcontext().prec = 3000
def keystream(key):
random.seed(int(os.environ["seed"]))
p = random.randint(3,30)
while not isPrime(p):
p = random.randint(3,30)
e = random.randint(50,600)
while 1:
d = random.randint(10,100)
ret = Decimal('0.'+str(key ** e).split('.')[-1])
for i in range(d):
ret*=2
yield int((ret//1)%2)
e+=p
try:
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
# added some more weak key protections
if b*b < 4*a*c or [a,b,c].count(0) or Decimal(b*b-4*a*c).sqrt().to_integral_value()**2==b*b-4*a*c or abs(a)>400 or abs(b)>500 or abs(c)>500:
raise Exception()
key = (Decimal(b*b-4*a*c).sqrt() - Decimal(b))/Decimal(a*2)
if 4*key*key<5 or abs(key-key.to_integral_value())<0.05:
raise Exception()
except:
print("bad key")
else:
flag = binascii.hexlify(os.environ["flag"].encode())
flag = bin(int(flag,16))[2:].zfill(len(flag)*4)
ret = ""
k = keystream(key)
for i in flag:
ret += str(next(k)^int(i))
print(ret) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2020/crypto/Wacko_Images/image-encryption.py | ctfs/angstromCTF/2020/crypto/Wacko_Images/image-encryption.py | from numpy import *
from PIL import Image
flag = Image.open(r"flag.png")
img = array(flag)
key = [41, 37, 23]
a, b, c = img.shape
for x in range (0, a):
for y in range (0, b):
pixel = img[x, y]
for i in range(0,3):
pixel[i] = pixel[i] * key[i] % 251
img[x][y] = pixel
enc = Image.fromarray(img)
enc.save('enc.png')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2020/crypto/RSA-OTP/chall.py | ctfs/angstromCTF/2020/crypto/RSA-OTP/chall.py | from Crypto.Util.number import bytes_to_long
from Crypto.Random.random import getrandbits # cryptographically secure random get pranked
from Crypto.PublicKey import RSA
from secret import d, flag
# 1024-bit rsa is unbreakable good luck
n = 136018504103450744973226909842302068548152091075992057924542109508619184755376768234431340139221594830546350990111376831021784447802637892581966979028826938086172778174904402131356050027973054268478615792292786398076726225353285978936466029682788745325588134172850614459269636474769858467022326624710771957129
e = 0x10001
key = RSA.construct((n,e,d))
f = bytes_to_long(bytes(flag,'utf-8'))
print("Encrypted flag:")
print(key.encrypt(f,0)[0])
def otp(m):
# perfect secrecy ahahahaha
out = ""
for i in bin(m)[2:]:
out+=str(int(i)^getrandbits(1))
return out
while 1:
try:
i = int(input("Enter message to sign: "))
assert(0 < i < n)
print("signed message (encrypted with unbreakable otp):")
print(otp(key.decrypt(i)))
except:
print("bad input, exiting")
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2020/crypto/Confused_Streaming/chall.py | ctfs/angstromCTF/2020/crypto/Confused_Streaming/chall.py | from __future__ import print_function
import random,os,sys,binascii
from decimal import *
try:
input = raw_input
except:
pass
getcontext().prec = 1000
def keystream(key):
random.seed(int(os.environ["seed"]))
e = random.randint(100,1000)
while 1:
d = random.randint(1,100)
ret = Decimal('0.'+str(key ** e).split('.')[-1])
for i in range(d):
ret*=2
yield int((ret//1)%2)
e+=1
try:
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
# remove those pesky imaginary numbers, rationals, zeroes, integers, big numbers, etc
if b*b < 4*a*c or a==0 or b==0 or c==0 or Decimal(b*b-4*a*c).sqrt().to_integral_value()**2==b*b-4*a*c or abs(a)>1000 or abs(b)>1000 or abs(c)>1000:
raise Exception()
key = (Decimal(b*b-4*a*c).sqrt() - Decimal(b))/Decimal(a*2)
except:
print("bad key")
else:
flag = binascii.hexlify(os.environ["flag"].encode())
flag = bin(int(flag,16))[2:].zfill(len(flag)*4)
ret = ""
k = keystream(key)
for i in flag:
ret += str(next(k)^int(i))
print(ret) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2020/web/LeetTube/leettube.py | ctfs/angstromCTF/2020/web/LeetTube/leettube.py | #!/usr/bin/env python
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.parse
import os
videos = []
for file in os.listdir('videos'):
os.chmod('videos/'+file, 0o600)
videos.append({'title': file.split('.')[0], 'path': 'videos/'+file, 'content': open('videos/'+file, 'rb').read()})
published = []
for video in videos:
if video['title'].startswith('UNPUBLISHED'): os.chmod(video['path'], 0) # make sure you can't just guess the filename
else: published.append(video)
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
self.path = urllib.parse.unquote(self.path)
if self.path.startswith('/videos/'):
file = os.path.abspath('.'+self.path)
try: video = open(file, 'rb', 0)
except OSError:
self.send_response(404)
self.end_headers()
return
reqrange = self.headers.get('Range', 'bytes 0-')
ranges = list(int(i) for i in reqrange[6:].split('-') if i)
if len(ranges) == 1: ranges.append(ranges[0]+65536)
try:
video.seek(ranges[0])
content = video.read(ranges[1]-ranges[0]+1)
except:
self.send_response(404)
self.end_headers()
return
self.send_response(206)
self.send_header('Accept-Ranges', 'bytes')
self.send_header('Content-Type', 'video/mp4')
self.send_header('Content-Range', 'bytes '+str(ranges[0])+'-'+str(ranges[0]+len(content)-1)+'/'+str(os.path.getsize(file)))
self.end_headers()
self.wfile.write(content)
elif self.path == '/':
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(("""
<style>
body {
background-color: black;
color: #00e33d;
font-family: monospace;
max-width: 30em;
font-size: 1.5em;
margin: 2em auto;
}
</style>
<h1>LeetTube</h1>
<p>There are <strong>"""+str(len(published))+"</strong> published video"+('s' if len(published) > 1 else '')+" and <strong>"+str(len(videos)-len(published))+"</strong> unpublished video"+('s' if len(videos)-len(published) > 1 else '')+".</p>"+''.join("<h2>"+video["title"]+"</h2><video controls src=\""+video["path"]+"\"></video>" for video in published)).encode('utf-8'))
else:
self.send_response(404)
self.end_headers()
except:
self.send_response(500)
self.end_headers()
httpd = HTTPServer(('', 8000), RequestHandler)
httpd.serve_forever()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/angstromCTF/2020/web/Secret_Agents/app.py | ctfs/angstromCTF/2020/web/Secret_Agents/app.py | from flask import Flask, render_template, request
#from flask_limiter import Limiter
#from flask_limiter.util import get_remote_address
from .secret import host, user, passwd, dbname
import mysql.connector
dbconfig = {
"host":host,
"user":user,
"passwd":passwd,
"database":dbname
}
app = Flask(__name__)
"""
limiter = Limiter(
app,
key_func=get_remote_address,
default_limits=["1 per second"],
)"""
#@limiter.exempt
@app.route("/")
def index():
return render_template("index.html")
@app.route("/login")
def login():
u = request.headers.get("User-Agent")
conn = mysql.connector.connect(
**dbconfig
)
cursor = conn.cursor()
#cursor.execute("SET GLOBAL connect_timeout=1")
#cursor.execute("SET GLOVAL wait_timeout=1")
#cursor.execute("SET GLOBAL interactive_timeout=1")
for r in cursor.execute("SELECT * FROM Agents WHERE UA='%s'"%(u), multi=True):
if r.with_rows:
res = r.fetchall()
break
cursor.close()
conn.close()
if len(res) == 0:
return render_template("login.html", msg="stop! you're not allowed in here >:)")
if len(res) > 1:
return render_template("login.html", msg="hey! close, but no bananananananananana!!!! (there are many secret agents of course)")
return render_template("login.html", msg="Welcome, %s"%(res[0][0]))
if __name__ == '__main__':
app.run('0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/misc/Your_papers_please/server.py | ctfs/TBTL/2024/misc/Your_papers_please/server.py | #!/usr/bin/python3
import base64
import datetime
import json
import os
import signal
import humanize
import jwt
# openssl ecparam -name secp521r1 -genkey -noout -out private.key
# openssl ec -in private.key -pubout -out public.pem
PUBLIC_KEY = u'''-----BEGIN PUBLIC KEY-----
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBGOtycGkAMpTEDsjFykEywLecIdCX
1QIShxmJB0qJj9K2yFNwJj/eRR6yzIZcHJPZWzQU6Mad62y1MsJ8uOgdZ2sBmkS0
HJtT4FZq/EQbtkHeahsDnSLbFpPfoN/t8hmKrVmDzDRGe3PNl7OQVuzoY2TVSxVK
IKmpZ9Pw9/5HOzSmOxs=-----END PUBLIC KEY-----
'''
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
myprint("Time out!")
exit(0)
def decode(token):
signing_input, crypto_segment = token.rsplit(".", 1)
header_segment, payload_segment = signing_input.split(".", 1)
header_data = base64.urlsafe_b64decode(header_segment)
header = json.loads(header_data)
alg = header["alg"]
return jwt.decode(token, algorithms=[alg], key=PUBLIC_KEY)
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
myprint("Your papers, please.")
token = input()
try:
mdl = decode(token)
assert mdl["docType"] == "iso.org.18013.5.1.mDL"
family_name = mdl["family_name"]
given_name = mdl["given_name"]
expiry_date = datetime.datetime.strptime(mdl["expiry_date"], "%Y-%m-%dT%H:%M:%S.%f")
except Exception as e:
myprint("Your papers are not in order!")
exit(0)
myprint("Hello {} {}!".format(given_name, family_name))
delta = expiry_date - datetime.datetime.now()
if delta <= datetime.timedelta(0):
myprint("Your papers expired {} ago!".format(humanize.naturaldelta(delta)))
exit(0)
flag = open("flag.txt", "r").read().strip()
myprint("Your papers are in order, here is your flag: {}".format(flag))
exit(0)
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/pwn/Squeezing_Tightly_On_Arm/squeezing_tightly_on_arm.py | ctfs/TBTL/2024/pwn/Squeezing_Tightly_On_Arm/squeezing_tightly_on_arm.py | import sys
version = sys.version_info
del sys
FLAG = 'TBTL{...}'
del FLAG
def check(command):
if len(command) > 120:
return False
allowed = {
"'": 0,
'.': 1,
'(': 1,
')': 1,
'/': 1,
'+': 1,
}
for char, count in allowed.items():
if command.count(char) > count:
return False
return True
def safe_eval(command, loc={}):
if not check(command):
return
return eval(command, {'__builtins__': {}}, loc)
for _ in range(10):
command = input(">>> ")
if command == 'version':
print(str(version))
else:
safe_eval(command)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/pwn/Pwn_From_the_Past/server.py | ctfs/TBTL/2024/pwn/Pwn_From_the_Past/server.py | #!/usr/bin/python3
import base64
import os
import shutil
import signal
import subprocess
import tempfile
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
myprint("Time out!")
exit(0)
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(10)
myprint("Enter contents for INPUT.TXT (base64): ")
contents = input()
try:
data = base64.b64decode(contents)
except Exception as e:
myprint("Error decoding contents ({}).\n".format(e))
exit(0)
tmp_dir = tempfile.mkdtemp(dir="./run")
shutil.copy("flag.txt", os.path.join(tmp_dir, "FLAG.TXT"))
shutil.copy("RUN.BAT", os.path.join(tmp_dir, "RUN.BAT"))
shutil.copy("CHALL.EXE", os.path.join(tmp_dir, "CHALL.EXE"))
input_filename = os.path.join(tmp_dir, "INPUT.TXT")
input_file = open(input_filename, "wb")
input_file.write(data)
input_file.close()
cmd = ["/usr/bin/dosbox", "-c", f"MOUNT C {tmp_dir}", "-c", "C:\RUN.BAT"]
env = {"SDL_VIDEODRIVER": "dummy"} # Supress dosbox GUI
myprint(f"Running {' '.join(cmd)}")
subprocess.check_output(cmd, env=env)
try:
output_filename = os.path.join(tmp_dir, "OUTPUT.TXT")
output_data = open(output_filename, "rb").read()
myprint("Your OUTPUT.TXT: {}".format(base64.b64encode(output_data).decode()))
except FileNotFoundError:
myprint("Program did not produce OUTPUT.TXT")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/pwn/A_Day_at_the_Races/server.py | ctfs/TBTL/2024/pwn/A_Day_at_the_Races/server.py | #!/usr/bin/python3
import base64
import hashlib
import io
import signal
import string
import subprocess
import sys
import time
REVIEWED_SOURCES = [
"24bf297fff03c69f94e40da9ae9b39128c46b7fe", # fibonacci.c
"55c53ce7bc99001f12027b9ebad14de0538f6a30", # primes.c
]
def slow_print(s, baud_rate=0.1):
for letter in s:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(baud_rate)
def handler(_signum, _frame):
slow_print("Time out!")
exit(0)
def error(message):
slow_print(message)
exit(0)
def check_filename(filename):
for c in filename:
if not c in string.ascii_lowercase + ".":
error("Invalid filename\n")
def check_compile_and_run(source_path):
slow_print("Checking if the program is safe {} ...\n".format(source_path))
hash = hashlib.sha1(open(source_path, 'rb').read()).hexdigest()
if not hash in REVIEWED_SOURCES:
error("The program you uploaded has not been reviewed yet.")
exe_path = source_path + ".exe"
slow_print("Compiling {} ...\n".format(source_path))
subprocess.check_call(["/usr/bin/gcc", "-o", exe_path, source_path])
slow_print("Running {} ...\n".format(exe_path))
time_start = time.time()
subprocess.check_call(exe_path)
duration = time.time()-time_start
slow_print("Duration {} s\n".format(duration))
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
slow_print("Let's see what kind of time your C program clocks today!\n")
slow_print("Enter filename: ")
filename = input()
check_filename(filename)
filepath = "./run/" + filename
slow_print("Enter contents (base64): ")
contents = input()
try:
data = base64.decode(io.StringIO(contents), open(filepath, 'wb'))
except Exception as e:
error("Error decoding contents ({}).\n".format(e))
check_compile_and_run(filepath)
slow_print("Bye!\n")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/crypto/University_Paper/chall.py | ctfs/TBTL/2024/crypto/University_Paper/chall.py | from Crypto.Util.number import *
from redacted import FLAG
ESSAY_TEMPLATE = """
On the Estemeed Scientifc Role Model of Mine
============================================
Within the confines of this academic setting, the individual whom
I hold in highest regard not only boasts an engaging smile but also
possesses a remarkable sense of humor, complemented by an array of
vibrant notebooks.
Yet, it is their distinct quantifiable attribute that stands out
most prominently: their name, when converted into an integer value
and squared modulo %d,
astonishingly results in %d.
Furthermore, the greatest integer that does not surpass the cube root
of the aforementioned squared name equals %d.
This computational detail adds another layer of distinction.
It is likely that by this point, many of you have discerned the identity
of this distinguished role model.
"""
def invpow3(x):
lo, hi = 1, x
while lo < hi:
mid = (lo + hi) // 2 + 1
if (mid**3) <= x:
lo = mid
else:
hi = mid - 1
return lo
N = 13113180816763040887576781992067364636289723584543479342139964290889855987378109190372819034517913477911738026253141916115785049387269347257060732629562571
name_int = bytes_to_long(FLAG)
assert 1 < name_int < N
value_1 = (name_int**2) % N
value_2 = invpow3(name_int**2)
assert (value_2**3) <= (name_int**2)
assert ((value_2 + 2) ** 3) > (name_int**2)
print(ESSAY_TEMPLATE % (N, value_1, value_2))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/crypto/School_Essay/chall.py | ctfs/TBTL/2024/crypto/School_Essay/chall.py | from Crypto.Util.number import *
from redacted import FLAG
ESSAY_TEMPLATE = """
My Favorite Classmate
=====================
My favorite person in this class has a beautiful smile,
great sense of humour, and lots of colorful notebooks.
However, their most distinctive feature is the fact that
you can represent their name as an integer value, square
it modulo %d,
and you'll get %d.
Additionally, When you compute the greatest integer not exceeding
the cube root of their squared name, you get %d.
By now, all of you have probably guessed who I'm talking about.
"""
def invpow3(x):
lo, hi = 1, x
while lo < hi:
mid = (lo + hi) // 2 + 1
if (mid**3) <= x:
lo = mid
else:
hi = mid - 1
return lo
N = 59557942237937483757629838075432240015613811860811898821186897952866236010569299041278104165604573
name_int = bytes_to_long(FLAG)
assert 1 < name_int < N
value_1 = (name_int**2) % N
value_2 = invpow3(name_int**2)
print(ESSAY_TEMPLATE % (N, value_1, value_2))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/crypto/Cursed_Decryption/server.py | ctfs/TBTL/2024/crypto/Cursed_Decryption/server.py | #!/usr/bin/python3
from Crypto.Util.number import *
from Crypto.Random import random
from redacted import FLAG
import signal
BANNER = (
" \n"
' ( " ) Just a small dash of OTP\n'
" ( _ * And the FLAG is lost forever!\n"
" * ( / \\ ___\n"
' " " _/ /\n'
" ( * ) ___/ |\n"
" ) \" _ o)'-./__\n"
" * _ ) (_, . $$$\n"
" ( ) __ __ 7_ $$$$\n"
" ( : { _) '--- $\\\n"
" _____'___//__\\ ____, \\\n"
" ) ( \\_/ _____\\_\n"
" .' \\ \\------''.\n"
" |=' '=| | )\n"
" | | | . _/\n"
" \\ (. ) , / /__I_____\\\n"
" '._/_)_(\\__.' (__,(__,_]\n"
" @---()_.'---@\n"
)
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
myprint("Time out!")
exit(0)
class Cipher:
BITS = 256
def __init__(self):
self.p = getPrime(Cipher.BITS)
self.q = getPrime(Cipher.BITS)
self.n = self.p * self.q
self.e = 0x10001
phi = (self.p - 1) * (self.q - 1)
self.d = inverse(self.e, phi)
def encrypt(self, pt):
ct = pow(pt, self.e, self.n)
return bin(ct)[2:]
def decrypt_lol(self, ct):
pt = pow(ct, self.d, self.n)
pt_len = len(bin(pt)[2:])
dec = list(map(int, bin(pt)[2:]))
otp_key = list(map(int, bin(random.getrandbits(pt_len))[2:]))
for i in range(len(otp_key)):
dec[i] ^= otp_key[i]
return "".join(list(map(str, dec)))
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
myprint(BANNER)
cipher = Cipher()
myprint(f"N = {cipher.n}")
myprint(f"e = {cipher.e}")
myprint(f"enc(flag) = {cipher.encrypt(bytes_to_long(FLAG))}\n")
while True:
user_ct = int(input("Enter ciphertext: "), 2)
pt = cipher.decrypt_lol(user_ct)
myprint(f"Decrypted: {pt}")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/crypto/Wikipedia_Signatures/server.py | ctfs/TBTL/2024/crypto/Wikipedia_Signatures/server.py | #!/usr/bin/python3
from redacted import FLAG
from Crypto.Util.number import bytes_to_long
from Crypto.Math.Numbers import Integer
from Crypto.PublicKey import RSA
import signal
TARGET = b'I challenge you to sign this message!'
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
myprint("Time out!")
exit(0)
def rsa(m, n, x):
if not 0 <= m < n:
raise ValueError("Value too large")
return int(pow(Integer(m), x, n))
# Alice signs a message—"Hello Bob!"—by appending to the original
# message a version encrypted with her private key.
def wikipedia_sign(message, n, d):
return rsa(message, n, d)
# Bob receives both the message and signature. He uses Alice's public key
# to verify the authenticity of the message, i.e. that the encrypted copy,
# decrypted using the public key, exactly matches the original message.
def wikipedia_verify(message, signature, n, e):
return rsa(signature, n, e) == bytes_to_long(message)
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
rsa_key = RSA.generate(1024)
public_key = (rsa_key.n, rsa_key.e)
myprint(f"RSA public key: {public_key}")
myprint("Options:")
myprint(f"1 <sig> -- Submit signature for {TARGET} and win")
myprint("2 <msg> -- Sign any other message using wikipedia-RSA")
for _ in range(10):
line = input("> ")
action, data = map(int, line.split())
if action == 1:
if wikipedia_verify(TARGET, data, rsa_key.n, rsa_key.e):
myprint(f"{FLAG}")
exit(0)
else:
myprint(f"Nope. Keep trying!")
elif action == 2:
if data % rsa_key.n == bytes_to_long(TARGET):
myprint(f"Nope. Won't sign that!")
else:
sig = wikipedia_sign(data, rsa_key.n, rsa_key.d)
myprint(sig)
else:
break
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/crypto/Kung_Fu_Cipher/server.py | ctfs/TBTL/2024/crypto/Kung_Fu_Cipher/server.py | from Crypto.Util.number import *
from sage.all import *
from redacted import FLAG
import random
import signal
BANNER = (
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣦⣤⣖⣶⣒⠦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣿⣿⣾⣿⣿⣿⣿⣿⣶⣷⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⢜⡛⠈⠛⢙⣃⠙⢿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡏⢟⠀⠀⠹⠀⠀⠘⠃⣸⡿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⢀⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢳⡈⠷⠀⠀⠀⠁⠀⠹⣿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⢀⣿⣏⢹⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⠟⠛⠛⠛⢦⣍⣃⣀⡴⠂⠀⣽⠙⠲⢤⣀⠀⠀⠀⠀⠀⠀⠀This is a sparing program... ⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⢸⡘⣿⣾⣇⠀⠀⠀⠀⠀⠀⠀⢠⡾⠁⠀⠀⠀⠀⡀⠙⢇⠁⠀⠀⠀⡿⠀⠀⠀⠈⢻⡇⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠸⡅⠻⠯⣿⠀⠀⠀⠀⠀⠀⣠⠏⣀⠀⠀⠀⠀⠀⠳⡄⠈⠳⡄⠀⣰⠃⢰⠆⠀⠀⢸⡇⠀⠀⠀It has the same basic rules as any⠀⠀ \n"
"⠀⠀⠀⠀⠀⠉⠳⣆⠈⢻⣄⠀⠀⢀⡞⠁⠀⠘⢦⠀⠀⠀⠀⠀⠙⣆⠀⠙⢦⠏⢀⡞⠀⠀⠀⢸⠁⠀⠀⠀⠀⠀ other cryptographic program. ⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⢨⡷⣾⠈⠳⣤⠟⠀⠀⠀⠀⠈⢧⠀⠀⠀⠀⠀⠈⠃⢀⡞⠀⣸⠃⠀⠀⠀⣾⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠸⣟⠁⠀⠀⠈⠳⣄⡀⠀⠀⢀⡼⠆⠀⠀⠀⠀⠀⢀⡜⠀⣰⠇⠀⠀⠀⢀⡟⠀⠀⠀⠀⠀What you must learn is that some⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⣄⠀⠀⠀⠈⠉⢀⡴⠋⣆⠀⠀⠀⠀⠀⢀⡞⠀⣠⠏⠀⠀⠀⠀⢸⠃⠀⠀⠀⠀⠀⠀⠀of these rules can be bent,⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⣄⠀⣠⠖⠉⠀⠀⢹⡀⠀⠀⠀⢀⡞⠀⣠⠏⠀⠀⠀⠀⠀⣼⣓⣶⣶⣦⠀⠀⠀⠀⠀ others can be broken.⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠁⠀⠀⠀⠀⠀⢷⠀⠀⣠⠋⠀⡰⠏⠀⠀⠀⠀⠀⠀⣿⢹⡶⣾⡿⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢷⣾⣥⣄⡈⠁⠀⠀⠀⠀⠀⠀⠀⡏⠉⠉⠉⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⠛⠛⢿⣿⣿⣿⣿⣶⣶⣤⣤⣤⣼⠁⠀⠀⠀⠀⠀OPTIONS: ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡴⠃⠀⠀⠀⠀⠈⠉⠉⠛⢻⣿⣿⣿⠛⢦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡼⠁⣰⡆⠀⠀⠀⠀⠀⠀⠀⣾⣿⠀⢿⣧⠀⠙⢦⡀⠀⠀⠀⠀⠀⠀1) Encrypt the FLAG ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣡⠞⠁⢣⠀⠀⠀⠀⠀⠀⠀⣿⣿⡇⠸⣿⣇⠀⠈⢣⡀⠀⠀⠀⠀⠀2) Encrypt arbitrary plaintext⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠟⠁⠀⠀⢸⡄⠀⠀⠀⠀⠀⠀⣿⣿⡇⠀⢿⣿⡀⠀⣀⣷⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡏⠀⠀⠀⠀⠈⣇⠀⠀⠀⠀⠀⠀⣿⣿⣆⡀⠼⣿⣿⠉⠉⠈⢦⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡞⠀⠀⠀⠀⠀⠀⠛⢻⠟⠛⠛⠛⠋⠉⠙⠛⢦⠀⣿⣿⡆⠀⠀⠈⢷⠀⠀⠀⠀ What are you waiting for?⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡾⠀⠀⠀⠀⠀⠀⠀⢠⠏⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⡀⠈⠀⠀⠀⠀⠈⢳⡀⠀⠀You're a better hacker than this\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡼⠁⠀⠀⠀⠀⠀⠀⣰⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢦⡀⠀⠀⠀⠀⠈⢳⡄⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⠁⠀⠀⠀⠀⠀⠀⣰⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⠁⠀⠀⠀⠀⢀⡾⠁⠀ Don't think you are,⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣸⠃⠀⠀⠀⠀⠀⠀⣴⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡏⠀⠀⠀⠀⠀⣼⠃⠀⠀ KNOW YOU ARE! ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⠃⠀⠀⠀⠀⠀⠀⡼⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣸⡁⠀⠀⠀⠀⣸⣻⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⠃⠀⠀⠀⠀⠀⠀⡼⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠀⠀⠀⠀⠘⠉⡏⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⣰⠃⠀⠀⠀⠀⠀⠀⡼⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡇⠀⠀⠀⠀⠀⢈⡇⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⣰⠃⠀⠀⠀⠀⠀⠀⡾⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⠁⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⢀⡼⠃⠀⠀⠀⠀⠀⢀⡾⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⢀⣽⠦⣤⡀⠀⠀⢀⡞⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠋⠛⡶⠤⣤⣀⣸⡿⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⣀⣀⡴⠖⠉⠀⠀⠀⠉⠑⡶⠎⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡟⠀⠀⢧⡀⠀⠀⠁⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⢻⣯⣥⡀⠀⣤⠤⠤⠤⠴⠞⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀⢉⣳⣤⣄⡀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠙⠓⠚⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠛⠓⠒⠚⠛⠋⠁⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
)
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
myprint("Time out!")
exit(0)
class KungFuCipher:
BITS = 512
def __init__(self):
rng = random.SystemRandom()
self.p = KungFuCipher.get_prime(rng)
self.q = KungFuCipher.get_prime(rng)
self.n = self.p * self.q
self.e = getPrime(100)
def get_prime(rng):
DIGITS = 80
while True:
ret = 0
for _ in range(DIGITS):
ret *= 10
ret += rng.choice([5, 7, 9])
if isPrime(ret):
return ret
def encrypt(self, pt):
def mul(A, B, mod):
return (A * B).apply_map(lambda x: x % mod)
M = matrix(ZZ, 2, 2, pt).apply_map(lambda x: x % self.n)
C = identity_matrix(ZZ, M.nrows())
e = self.e
while e > 0:
if e & 1:
C = mul(C, M, self.n)
M = mul(M, M, self.n)
e //= 2
return C
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
myprint(BANNER)
cipher = KungFuCipher()
myprint(f"n = {hex(cipher.n)}\n")
assert len(FLAG) % 4 == 0
k = len(FLAG) // 4
pt = [bytes_to_long(FLAG[i * k : (i + 1) * k]) for i in range(4)]
flag_ct = cipher.encrypt(pt)
for _ in range(10):
action = input("> ")
if action == "1":
for i in range(2):
for j in range(2):
myprint(f"ct[{i}][{j}] = {hex(flag_ct[i][j])}")
elif action == "2":
user_pt = []
for i in range(2):
for j in range(2):
try:
x = int(input(f"pt[{i}][{j}] = "), 16)
except Exception as _:
myprint("kthxbai")
exit(0)
user_pt.append(x)
user_ct = cipher.encrypt(user_pt)
for i in range(2):
for j in range(2):
myprint(f"ct[{i}][{j}] = {hex(user_ct[i][j])}")
pass
else:
break
myprint("kthxbai")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/web/Mexico_City_Tour/app.py | ctfs/TBTL/2024/web/Mexico_City_Tour/app.py | from flask import Flask, render_template, url_for, redirect, request
from neo4j import GraphDatabase
app = Flask(__name__)
URI = "bolt://localhost:7687"
AUTH = ("", "")
def query(input_query):
with GraphDatabase.driver(URI, auth=AUTH) as driver:
driver.verify_connectivity()
session = driver.session()
tx = session.begin_transaction()
records = [t for t in tx.run(input_query)]
tx.rollback()
return records
@app.route("/")
def index():
distance = request.args.get('distance')
stations = query('MATCH (n:Station) RETURN n.id, n.name ORDER BY n.id DESC;')
return render_template('index.html', stations=stations, distance=distance)
@app.route("/search", methods=['POST'])
def search():
start = request.form["startStation"]
end = request.form['endStation']
distance_query = f'MATCH (n {{id: {start}}})-[p *bfs]-(m {{id: {end}}}) RETURN size(p) AS distance;'
distance = query(distance_query)
if len(distance) == 0:
distance = 'unknown'
else:
distance = int(distance[0]['distance'])
return redirect(url_for('.index', distance=distance))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/web/Rnd_For_Data_Science/generator_app.py | ctfs/TBTL/2024/web/Rnd_For_Data_Science/generator_app.py | from flask import Flask, request
import random as rnd
app = Flask(__name__)
flag = open('flag.txt', 'r').read().rstrip()
@app.route("/", methods=['POST'])
def index():
delimiter = request.form['delimiter']
if len(delimiter) > 1:
return 'ERROR'
num_columns = int(request.form['numColumns'])
if num_columns > 10:
return 'ERROR'
headers = ['id'] + [request.form["columnName" + str(i)] for i in range(num_columns)]
forb_list = ['and', 'or', 'not']
for header in headers:
if len(header) > 120:
return 'ERROR'
for c in '\'"!@':
if c in header:
return 'ERROR'
for forb_word in forb_list:
if forb_word in header:
return 'ERROR'
csv_file = delimiter.join(headers)
for i in range(10):
row = [str(i)] + [str(rnd.randint(0, 100)) for _ in range(num_columns)]
csv_file += '\n' + delimiter.join(row)
row = [str('NaN')] + ['FLAG'] + [flag] + [str(0) for _ in range(num_columns)]
csv_file += '\n' + delimiter.join(row[:len(headers)])
return csv_file
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2024/web/Rnd_For_Data_Science/app.py | ctfs/TBTL/2024/web/Rnd_For_Data_Science/app.py | from flask import Flask, request, send_file
from io import StringIO, BytesIO
import pandas as pd
import requests
app = Flask(__name__)
@app.route("/")
def index():
return app.send_static_file('index.html')
@app.route("/generate", methods=['POST'])
def generate():
data = request.form
delimiter_const = 'delimiter'
r = requests.post('http://127.0.0.1:5001', data=data)
if r.text == 'ERROR':
return 'ERROR'
csv = StringIO(r.text)
df = pd.read_csv(csv)
# Filter out secrets
first = list(df.columns.values)[1]
df = df.query(f'{first} != "FLAG"')
string_df = StringIO(df.to_csv(index=False, sep=data[delimiter_const]))
bytes_df = BytesIO()
bytes_df.write(string_df.getvalue().encode())
bytes_df.seek(0)
return send_file(bytes_df, download_name="data.csv")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2023/pwn/Math_is_hard/calc.py | ctfs/TBTL/2023/pwn/Math_is_hard/calc.py | #!/usr/bin/python3
from math import *
from string import *
USAGE = """PwnCalc -- a simple calculator
$ a=4
>>> a = 4
$ a = 4
>>> a = 4
$ b = 3
>>> b = 3
$ c = sqrt(a*a+b*b)
>>> c = 5.0
$ d = sin(pi/4)
>>> d = 0.7071067811865475
Have fun!
"""
def check_expression(s):
"""Allow only digits, decimal point, lowecase letters and math symbols."""
SYMBOLS = ".+*-/()"
for c in s:
if not c.islower() and not c.isdigit() and c not in SYMBOLS:
return False
return True
def loop():
"""Main calculator loop."""
vars = { c : 0 for c in ascii_lowercase }
while True:
line = input("$ ")
if not line:
print("Bye!")
return
items = line.split("=")
if len(items) != 2:
print("Invalid syntax!")
continue
varname, expression = items
varname = varname.strip()
expression = expression.strip()
if len(varname) != 1 or not varname.islower():
print("Invalid variable name!")
continue
if not check_expression(expression):
print("Invalid character in expression!")
continue
result = eval(expression, vars, {'sin': sin, 'cos': cos, 'sqrt': sqrt, 'exp': exp, 'log': log, 'pi': pi})
vars[varname] = result
print(">>> {} = {}".format(varname, result))
if __name__ == "__main__":
print(USAGE)
loop()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2023/crypto/Custom_Cipher/server.py | ctfs/TBTL/2023/crypto/Custom_Cipher/server.py | #!/usr/bin/python3
from Crypto.Cipher import AES
from Crypto.Util.number import bytes_to_long, long_to_bytes
import hashlib
import os
import signal
BANNER = (" \n"
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡴⠟⠛⠛⠛⠛⠛⢦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⠀⣠⡾⠋⠀⠀⠀⠀⠀⠀⠀⠀⠙⠷⣄⠀⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⢀⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⡆⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠀⡿ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣷⠀⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⢀⡿⠀⠀⢀⣀⣤⡴⠶⠶⢦⣤⣀⡀⠀⠀⢻⡆⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⠀⠀⠘⣧⡀⠛⢻⡏⠀⠀⠀⠀⠀⠀⠉⣿⠛⠂⣼⠇⠀⠀⠀⠀⠀⠀\n"
"⠀⠀⠀⠀⢀⣤⡴⠾⢷⡄⢸⡇⠀⠀⠀⠀⠀⠀⢀⡟⢀⡾⠷⢦⣤⡀⠀⠀⠀⠀\n"
"⠀⠀⠀⢀⡾⢁⣀⣀⣀⣻⣆⣻⣦⣤⣀⣀⣠⣴⣟⣡⣟⣁⣀⣀⣀⢻⡄⠀⠀⠀\n"
"⠀⠀⢀⡾⠁⣿⠉⠉⠀⠀⠉⠁⠉⠉⠉⠉⠉⠀⠀⠈⠁⠈⠉⠉⣿⠈⢿⡄⠀⠀\n"
"⠀⠀⣾⠃⠀⣿⠀⠀⠀⠀⠀⠀⣠⠶⠛⠛⠷⣤⠀⠀⠀⠀⠀⠀⣿⠀⠈⢷⡀⠀\n"
"⠀⣼⠃⠀⠀⣿⠀⠀⠀⠀⠀⢸⠏⢤⡀⢀⣤⠘⣧⠀⠀⠀⠀⠀⣿⠀⠀⠈⣷⠀\n"
"⢸⡇⠀⠀⠀⣿⠀⠀⠀⠀⠀⠘⢧⣄⠁⠈⣁⣴⠏⠀⠀⠀⠀⠀⣿⠀⠀⠀⠘⣧\n"
"⠈⠳⣦⣀⠀⣿⠀⠀⠀⠀⠀⠀⠀⠻⠶⠶⠟⠀⠀⠀⠀⠀⠀⠀⣿⠀⢀⣤⠞⠃\n"
"⠀⠀⠀⠙⠷⣿⣤⣤⣤⣤⣤⣠⣤⣤⣤⣤⣀⣤⣠⣤⣀⣤⣤⣄⣿⡶⠋⠁⠀⠀\n"
"⠀⠀⠀⠀⠀⢿⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣿⠀⠀⠀⠀⠀\n")
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
print("Time out!")
exit(0)
def hack_detected():
myprint("Hack detected... go away!")
exit(1)
def bxor(a, b):
return bytes([_a ^ _b for _a, _b in zip(a, b)])
def hash(num):
return hashlib.sha256(long_to_bytes(num)).digest()
class LCG:
def __init__(self, a, b, m):
self.a = a
self.b = b
self.m = m
self.state = bytes_to_long(os.urandom(32))
def next(self):
self.state = (self.a * self.state + self.b) % self.m
return self.state
class CustomCipher:
N_KEYS = 16
def __init__(self, keygen):
self.keygen = keygen
self.keys = [hash(keygen.next()) for _ in range(self.N_KEYS)]
if len(set(self.keys)) < self.N_KEYS // 2:
hack_detected()
def encrypt(self, pt):
L = [pt[:32]]
R = [pt[32:]]
for (i, ki) in enumerate(self.keys):
iv = bxor(self.keys[i][16:], self.keys[(
i + self.N_KEYS // 2) % self.N_KEYS][:16])
F = AES.new(ki, AES.MODE_CBC, iv=iv)
l, r = R[-1], bxor(L[-1], F.encrypt(R[-1]))
if i + 1 == self.N_KEYS // 2:
l, r = r, l
L.append(l)
R.append(r)
return L[-1] + R[-1]
def tamper(self, a, b, c):
for idx in [a, b, c]:
if not 1 <= idx <= self.N_KEYS:
hack_detected()
self.keys[a - 1] = bxor(self.keys[b - 1], self.keys[c - 1])
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
myprint(BANNER)
myprint(
"\"Don't roll out your own crypto!\" is just a piece of advice for the weak.")
myprint(" * We have a strong team of world renowned researchers!")
myprint(" * We are not weak!")
myprint(" * We are not afraid of hackers!")
myprint(" * We are so confident we've opened some backdoors!")
myprint("")
myprint("Enjoy wasting your time on this...")
myprint("")
m = 2 ** 256
a = int(input("Insert key generator b[a]ckdoor: ")) % m
b = int(input("Insert key generator [b]ackdoor: ")) % m
cipher = CustomCipher(LCG(a, b, m))
for i in range(1, 13):
myprint(
f"[{i}/12] Wanna tamper with the keys [(a, b, c) --> ka = kb ^ kc])?")
s = input("> ")
if s == "no":
continue
a, b, c = map(int, s.split())
cipher.tamper(a, b, c)
flag = open("flag.txt", "rb").read()
assert(len(flag) == 64)
flag_ct = cipher.encrypt(flag).hex()
myprint(f"Here is your encrypted flag: {flag_ct}")
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2023/crypto/Perfect_Secrecy/challenge.py | ctfs/TBTL/2023/crypto/Perfect_Secrecy/challenge.py | #!/usr/bin/python3
import random
def encrypt(m_bytes):
l = len(m_bytes)
pad = random.getrandbits(l * 8).to_bytes(l, 'big')
return bytes([a ^ b for (a, b) in zip(m_bytes, pad)]).hex()
def main():
flag = open("flag.txt", "rb").read()
assert(flag.startswith(b"Blockhouse{") and flag.endswith(b"}"))
[print(encrypt(flag)) for _ in range(300)]
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2023/crypto/Baby_Shuffle/server.py | ctfs/TBTL/2023/crypto/Baby_Shuffle/server.py | #!/usr/bin/python3
from Crypto.Util.number import *
import os
import signal
BABY_FLAG = (" .@@@@@.\n"
" / \\\n"
" / 6 6 \\\n"
" ( ^ ,)\n"
" \\ c /-._\n"
" `._____.' `--.__\n"
" \\ / `/``\"\"\"'-.\n"
" Y 7 / :\n"
" | / | .--. :\n"
" ***** ***** ***** ***** / /__ \\/ `.__.:.____.-.\n"
" * G * * F * * L * * A * / / / `\"\"\"`/ .-\"..____.-. \\\n"
" ***** ***** ***** ***** _.-' /_/ ( \-. \\\n"
" `=----' `----------'\"\"`-. \ `\"\n")
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
myprint("Time out!")
exit(0)
class RSA:
BITS = 512
def __init__(self):
self.p = getPrime(self.BITS)
self.q = getPrime(self.BITS)
self.n = self.p * self.q
self.e = 17
def pubkey(self):
return (self.n, self.e)
def encrypt(self, m):
return pow(m, self.e, self.n)
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
myprint(BABY_FLAG)
myprint("This challenge is unbreakable! Just listen to the setup:")
myprint(" 1) We give you the encrypted secret FLAG")
myprint(" 2) We give the FLAG to the youngest TBTL member")
myprint(" 3) They shuffle the FLAG")
myprint(" 4) We give you the encrypted shuffled FLAG")
myprint(
" 5) We laugh at you for wasting your time trying to figure out the FLAG :)")
myprint("")
myprint("Our newest member is still a baby... they are good at shuffling, right?")
myprint("")
myprint("")
cipher = RSA()
flag = open("flag.txt", "r").read().strip()
shuffled_flag = flag[-1] + flag[:-1]
assert(len(flag) == 61)
myprint(f"(N, e) = ({cipher.n}, {cipher.e})")
m1 = bytes_to_long(flag.encode("utf-8"))
m2 = bytes_to_long(shuffled_flag.encode("utf-8"))
c1 = cipher.encrypt(m1)
c2 = cipher.encrypt(m2)
myprint(f"c1 = {c1}")
myprint(f"c2 = {c2}")
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2023/crypto/Random_Keys/server.py | ctfs/TBTL/2023/crypto/Random_Keys/server.py | #!/usr/bin/python3
from Crypto.Util.number import *
import os
import signal
BANNER = (" \n"
" ###### \n"
" ####******#### \n"
" ##**************## \n"
" ##****##########****## \n"
" ##****## ##****## \n"
" ################################################****## ##****##\n"
" ##**************************************************## ##****##\n"
" ##****##****##****############################****## ##****##\n"
" #### #### #### ##****## ##****## \n"
" ##****##########****## \n"
" ##**************## \n"
" ####******#### \n"
" ###### \n")
def myprint(s):
print(s, flush=True)
def handler(_signum, _frame):
print("Time out!")
exit(0)
class LCG:
def __init__(self):
self.m = 128
self.state = bytes_to_long(os.urandom(1))
self.a = bytes_to_long(os.urandom(1))
self.b = bytes_to_long(os.urandom(1))
def next(self):
self.state = (self.a * self.state + self.b) % self.m
return self.state
class RSA:
BITS = 512
def __init__(self):
self.primes = [getPrime(self.BITS) for _ in range(128)]
self.gen = LCG()
def encrypt(self, msg):
p = self.primes[self.gen.next()]
q = self.primes[self.gen.next()]
N = p * q
e = 0x10001
return (N, e, hex(pow(msg, e, N)))
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
myprint(BANNER)
myprint("Try to defeat our new encryption service using a chosen plaintext attack with at most 10 queries:")
myprint(" 1) Encrypt arbitrary message")
myprint(" 2) Encrypt flag and exit")
myprint("")
print("Initializing service... ", end="", flush=True)
cipher = RSA()
myprint("DONE!")
myprint("")
for _ in range(10):
action = input("> ")
if action == '1':
message = bytes_to_long(bytes.fromhex(input("Message (hex): ")))
result = cipher.encrypt(message)
myprint(f"Result (N, e, ct): {result}")
elif action == '2':
flag = bytes_to_long(open("flag.txt", "rb").read())
result = cipher.encrypt(flag)
myprint(f"Result (N, e, ct): {result}")
exit(0)
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2023/web/No_admin_no_problem/app.py | ctfs/TBTL/2023/web/No_admin_no_problem/app.py | from flask import Flask, request, render_template
from fast_jwt import encode, decode
import uuid
import base64
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/apply', methods=['POST'])
def apply():
token = request.form.get('token')
public_key = open('publickey.crt', 'br').read()
reason = ''
try:
decoded = decode(token, public_key)
except Exception as e:
reason = str(e)
decoded = None
fail = decoded is None or 'username' not in decoded or 'admin' not in decoded
message = 'Test success:' + str(decoded) if not fail else 'Test failed! ' + reason
if not fail and decoded['admin'] is True:
return render_template('flag.html')
return render_template('user.html', message=message)
@app.route('/get_token', methods=['GET'])
def get_token():
private_key = open('keypair.pem', 'br').read()
public_key = open('publickey.crt', 'br').read()
public_key = base64.b64encode(public_key.replace(b'\n', b'')).decode('ascii')
username = str(uuid.uuid4())
payload = {'username': username, 'admin': False}
encoded = encode(payload, private_key, 'RS256', public_key)
return render_template('token.html', token=encoded)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2025/pwn/Michael_Scofield/sandbox.py | ctfs/TBTL/2025/pwn/Michael_Scofield/sandbox.py | def check_pattern(user_input):
"""
This function will check if numbers or strings are in user_input.
"""
return '"' in user_input or '\'' in user_input or any(str(n) in user_input for n in range(10))
while True:
user_input = input(">> ")
if len(user_input) == 0:
continue
if len(user_input) > 500:
print("Too long!")
continue
if not __import__("re").fullmatch(r'([^()]|\(\))*', user_input):
print("No function calls with arguments!")
continue
if check_pattern(user_input):
print("Numbers and strings are forbbiden")
continue
forbidden_keywords = ['eval', 'exec', 'import', 'open']
forbbiden = False
for word in forbidden_keywords:
if word in user_input:
forbbiden = True
if forbbiden:
print("Forbbiden keyword")
continue
try:
output = eval(user_input, {"__builtins__": None}, {})
print(output)
except:
print("Error")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2025/crypto/Guessy/server.py | ctfs/TBTL/2025/crypto/Guessy/server.py | #!/usr/bin/python3
import math
import signal
import sys
from Crypto.Util.number import getPrime, inverse, getRandomRange
N_BITS = 512
class A:
def __init__(self, bits = N_BITS):
self.p = getPrime(bits // 2)
self.q = getPrime(bits // 2)
self.n = self.p * self.q
self.phi = (self.p - 1) * (self.q - 1)
self.e = 0x10001
self.d = pow(self.e, -1, self.phi)
def encrypt(self, m):
return pow(m, self.e, self.n)
def decrypt(self, c):
return pow(c, self.d, self.n)
class B:
def __init__(self, bits = N_BITS):
self.p = getPrime(bits // 2)
self.q = getPrime(bits // 2)
self.n = self.p * self.q
self.n_sq = self.n * self.n
self.g = self.n + 1
self.lam = (self.p - 1) * (self.q - 1) // math.gcd(self.p - 1, self.q - 1)
x = pow(self.g, self.lam, self.n_sq)
L = (x - 1) // self.n
self.mu = inverse(L, self.n)
def encrypt(self, m):
r = getRandomRange(1, self.n)
while math.gcd(r, self.n) != 1:
r = getRandomRange(1, self.n)
c1 = pow(self.g, m, self.n_sq)
c2 = pow(r, self.n, self.n_sq)
return (c1 * c2) % self.n_sq
def decrypt(self, c):
x = pow(c, self.lam, self.n_sq)
L = (x - 1) // self.n
return (L * self.mu) % self.n
def err(msg):
print(msg)
exit(1)
def compute(e_secret, xs, a, b):
ret = 1
for x in xs:
ret *= a.encrypt(b.decrypt(e_secret * x))
ret %= a.n
return ret
def ans(secret, qs, a, b):
e_secret = b.encrypt(secret + 0xD3ADC0DE)
for i in range(7):
li = qs[i][:len(qs[i]) // 2]
ri = qs[i][len(qs[i]) // 2:]
print(f"{compute(e_secret, li, a, b)} {compute(e_secret, ri, a, b)}")
def test(t):
print(f"--- Test #{t} ---")
a = A()
b = B()
print(f"n = {b.n}")
print("You can ask 7 questions:")
qs = []
for _ in range(7):
l = list(map(int, input().strip().split()))
if len(l) % 2 != 0:
err("You must give me an even number of numbers!")
if len(l) != len(set(l)):
err("All numbers must be distinct!")
qs.append(l)
secret = getRandomRange(0, 2048)
ans(secret, qs, a, b)
print("Can you guess my secret?")
user = int(input())
if user != secret:
err("Seems like you can't")
else:
print("Correct!")
def timeout_handler(signum, frame):
print("Timeout!")
sys.exit(1)
def main():
signal.signal(signal.SIGALRM, timeout_handler)
for i in range(10):
test(i)
flag = open('flag.txt', "r").read()
print(f"Here you go: {flag}")
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2025/crypto/Prime_Genes/chall.py | ctfs/TBTL/2025/crypto/Prime_Genes/chall.py | #!/usr/bin/env python3
import math
import secrets
from Crypto.Util.number import *
from redacted import FLAG
PM = 0.05
def genetic_prime_gen(target_size_bits):
population = ['10', '11', '101']
number_large = 0
while True:
a, b = secrets.choice(population), secrets.choice(population)
# Crossover
child = a + b
if secrets.randbelow(100) < PM*100:
# Mutation
x = secrets.randbelow(len(child))
child = child[:x] + ('1' if child[x] == '0' else '0') + child[x+1:]
if isPrime(int(child, 2)) and child not in population:
if len(child) > target_size_bits:
number_large += 1
population.append(child)
if number_large >= 2:
break
population.sort(key=lambda x: len(x), reverse=True)
return population[0], population[1]
for i in range(20):
p, q = genetic_prime_gen(512)
p = int(p, 2)
q = int(q, 2)
N = p*q
e = 65537
c = pow(bytes_to_long(FLAG), e, N)
print(f'{N=}')
print(f'{e=}')
print(f'{c=}')
print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2025/crypto/Free_Candy/server.py | ctfs/TBTL/2025/crypto/Free_Candy/server.py | #!/usr/bin/python3
import base64
import binascii
import hashlib
import json
import signal
import sys
from sage.all import *
from Crypto.Util.number import *
BANNER = """
███ ▄█ ▄████████ ▄█ ▄█▄ ▄████████ ███ ▄████████ ▄█ █▄ ▄██████▄ ▄███████▄
▀█████████▄ ███ ███ ███ ███ ▄███▀ ███ ███ ▀█████████▄ ███ ███ ███ ███ ███ ███ ███ ███
▀███▀▀██ ███▌ ███ █▀ ███▐██▀ ███ █▀ ▀███▀▀██ ███ █▀ ███ ███ ███ ███ ███ ███
███ ▀ ███▌ ███ ▄█████▀ ▄███▄▄▄ ███ ▀ ███ ▄███▄▄▄▄███▄▄ ███ ███ ███ ███
███ ███▌ ███ ▀▀█████▄ ▀▀███▀▀▀ ███ ▀███████████ ▀▀███▀▀▀▀███▀ ███ ███ ▀█████████▀
███ ███ ███ █▄ ███▐██▄ ███ █▄ ███ ███ ███ ███ ███ ███ ███
███ ███ ███ ███ ███ ▀███▄ ███ ███ ███ ▄█ ███ ███ ███ ███ ███ ███
▄████▀ █▀ ████████▀ ███ ▀█▀ ██████████ ▄████▀ ▄████████▀ ███ █▀ ▀██████▀ ▄████▀
▀
In our shop, you are guaranteed to win!
"""
MENU = """
Choose an action:
1) Get a free ticket
2) Claim your prize
"""
class RNG:
def __init__(self, p):
assert isPrime(p), "p must be prime"
self.p = Integer(p)
self.F = GF(self.p)
self.H = QuaternionAlgebra(self.F, -1, -1)
self.i = self.H.gen(0)
self.j = self.H.gen(1)
self.k = self.i * self.j
self.half = self.F(1) / self.F(2)
while True:
a = self.F.random_element()
b = self.F.random_element()
c = self.F.random_element()
d = self.F.random_element()
if b != 0:
break
self.q = a + b*self.i + c*self.j + d*self.k
self.n = Integer(0)
def seed(self):
self.n = ZZ.random_element(self.p)
def print_params(self):
print(f"seed = {self.n}")
print(f"q = {self.q}")
def gen(self):
Q = self.q ** int(self.n)
ret = -self.half * (self.i * Q).reduced_trace()
self.n += 1
return int(ret)
class Signer:
_p = Integer(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F)
_a4 = Integer(0)
_a6 = Integer(7)
_n = Integer(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141)
_Gx = Integer(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798)
_Gy = Integer(0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
def __init__(self, rng):
self.rng = rng
F = GF(self._p)
self.E = EllipticCurve(F, [0, 0, 0, self._a4, self._a6])
self.G = self.E(self._Gx, self._Gy)
self.n = self._n
self.d = Integer(1 + ZZ.random_element(self.n - 1))
self.Q = (self.d * self.G)
self.rng.seed()
def _hash_to_int(self, msg):
h = hashlib.sha256(msg).digest()
return Integer(int.from_bytes(h, 'big')) % self.n
def _next_k(self):
while True:
k = Integer(self.rng.gen())
if k != 0:
return k
def sign(self, msg):
z = self._hash_to_int(msg)
while True:
k = self._next_k()
R = (k * self.G)
if R.is_zero():
continue
r = Integer(R.xy()[0]) % self.n
if r == 0:
continue
try:
kinv = Integer(k).inverse_mod(self.n)
except ZeroDivisionError:
continue
s = (kinv * (z + r * self.d)) % self.n
if s == 0:
continue
return (int(r), int(s))
def verify(self, msg, sig):
r, s = map(Integer, sig)
if not (1 <= r < self.n and 1 <= s < self.n):
return False
z = self._hash_to_int(msg)
try:
w = Integer(s).inverse_mod(self.n)
except ZeroDivisionError:
return False
u1 = (z * w) % self.n
u2 = (r * w) % self.n
V = u1 * self.G + u2 * self.Q
if V.is_zero():
return False
xV = Integer(V.xy()[0]) % self.n
return xV == r
def pubkey(self):
P = self.Q.xy()
return (int(P[0]), int(P[1]))
def privkey(self):
return int(self.d)
class Ticket:
def __init__(self, rng, signer, cnt = 1):
self.signer = signer
self.cnt = cnt
self.rng = rng
rng.seed()
def reset(self):
self.cnt = 1
def fresh(self):
if self.cnt <= 0:
return "No more tickets for you..."
self.cnt -= 1
ticket_id = int(self.rng.gen())
payload = {"ticket_id": ticket_id}
payload_bytes = json.dumps(payload, separators=(',', ':'), sort_keys=True).encode()
r, s = self.signer.sign(payload_bytes)
r_bytes = int(r).to_bytes(32, 'big')
s_bytes = int(s).to_bytes(32, 'big')
sig_hex = (r_bytes + s_bytes).hex()
ticket = {
"payload": payload,
"signature": sig_hex,
}
ticket_json = json.dumps(ticket, separators=(',', ':'), sort_keys=True).encode()
return base64.b64encode(ticket_json).decode()
class PrizePool:
def __init__(self, signer, ticket_shop):
self.signer = signer
self.ticket_shop = ticket_shop
self._used = set()
def claim_prize(self, ticket_b64):
try:
raw = base64.b64decode(ticket_b64, validate=True)
except Exception:
return "Invalid ticket: bad base64"
try:
ticket = json.loads(raw.decode())
except Exception:
return "Invalid ticket: bad JSON"
if not isinstance(ticket, dict) or "payload" not in ticket or "signature" not in ticket:
return "Invalid ticket: missing fields"
payload = ticket["payload"]
sig_hex = ticket["signature"]
if not isinstance(payload, dict) or "ticket_id" not in payload:
return "Invalid ticket: bad payload"
tid = payload["ticket_id"]
try:
tid = int(tid)
except Exception:
return "Invalid ticket: ticket_id not integer"
payload_bytes = json.dumps({"ticket_id": tid}, separators=(',', ':'), sort_keys=True).encode()
if not isinstance(sig_hex, str):
return "Invalid ticket: signature not a string"
try:
sig_bytes = bytes.fromhex(sig_hex)
except (ValueError, binascii.Error):
return "Invalid ticket: signature not hex"
if len(sig_bytes) != 64:
return "Invalid ticket: signature wrong length"
r = int.from_bytes(sig_bytes[:32], 'big')
s = int.from_bytes(sig_bytes[32:], 'big')
if not self.signer.verify(payload_bytes, (r, s)):
return "Invalid ticket: bad signature"
if tid in self._used:
print("Go away hacker!")
exit(1)
self._used.add(tid)
if tid == bytes_to_long(hashlib.sha256(b"I'd like the flag please").digest()):
flag = open("flag.txt", "r").read()
flag_prize = f"""
░▒▓█▓▒░░▒▓██████▓▒░ ░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░ ░▒▓██████▓▒░▒▓████████▓▒░▒▓█▓▒░
░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░▒▓████████▓▒░▒▓█▓▒░ ░▒▓███████▓▒░░▒▓███████▓▒░░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓██████▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
{flag}
"""
return flag_prize
if tid % 2 == 0:
self.ticket_shop.reset()
ticket = self.ticket_shop.fresh()
return f"You won a brand new ticket: {ticket}"
prize = """You won some free candy:
/\.--./\\
\/'--'\/
/\.--./\ /\.--./\\
\/'--'\/ \/'--'\/
"""
return prize
def timeout_handler(signum, frame):
print("Timeout!")
sys.exit(1)
def main():
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(120)
print(BANNER)
rng_ticket = RNG(int(Signer._n))
rng_signer = copy(rng_ticket)
signer = Signer(rng_signer)
ticket_shop = Ticket(rng_ticket, signer)
prize_pool = PrizePool(signer, ticket_shop);
while True:
print(MENU)
option = int(input())
if option not in [1, 2]:
print("W00t?")
continue
if option == 1:
print(f"{ticket_shop.fresh()}")
else:
print("Enter your ticket: ")
ticket = input().strip()
print(f"{prize_pool.claim_prize(ticket)}")
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TBTL/2025/web/Jey_is_not_my_son/app.py | ctfs/TBTL/2025/web/Jey_is_not_my_son/app.py | from flask import Flask, render_template, request
from jsonquerylang import jsonquery
import json
import string
app = Flask(__name__)
with open('data.json') as f:
data = json.load(f)
def count_baby_names(name: str, year: int) -> int:
query = f"""
.collection
| filter(.Name == "{name}" and .Year == "{year}")
| pick(.Count)
| map(values())
| flatten()
| map(number(get()))
| sum()
"""
output = jsonquery(data, query)
return int(output)
def contains_digit(name: str) -> bool:
for num in string.digits:
if num in name:
return True
return False
@app.route("/", methods=["GET"])
def home():
name = None
year = None
result = None
error = None
name = request.args.get("name", default="(no name)")
year = request.args.get("year", type=int)
if not name or contains_digit(name):
error = "Please enter a name."
elif not year:
error = "Please enter a year."
else:
if year < 1880 or year > 2025:
error = "Year must be between 1880 and 2025."
try:
result = count_baby_names(name=name, year=year)
except Exception as e:
error = f"Unexpected error: {e}"
return render_template("index.html", name=name, year=year, count=result, error=error)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BroncoCTF/2024/rev/Serpents_Pass/SerpentsServer.py | ctfs/BroncoCTF/2024/rev/Serpents_Pass/SerpentsServer.py | import sys
import errno
import socket
import threading
import math
from functools import lru_cache
def getLine(data: bytes) -> str:
inpData = data[0:data.index(b'\n')]
return str(inpData)[2:-1] # filter out the b''
def gate1():
return pow(10 * 9 + 7 - 2, 2)
def is_square(num: int) -> bool:
int_sqrt = lambda x: int(math.sqrt(num))
return pow(int_sqrt(num), 2) == num
def gate2(guess: int) -> bool:
if guess > 20:
return False
binString = '0'
for _ in range(0, guess):
binString += '1'
binary = int(binString, 2)
return chr(binary) == '?'
@lru_cache()
def mystery(n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
else:
return mystery(n - 1) + mystery(n - 2)
def gate3(guess: int) -> bool:
return is_square(mystery(guess))
def handleConnection(conn, addr) -> bool:
print('handling connection')
try:
with conn:
print('Connected by', addr)
conn.sendall(b"You approach The Serpent's Pass. The monster will let you through if you can answer three questions.\n")
conn.sendall(b"Question 1: What number is the Serpent thinking of?\n")
data = conn.recv(128)
if not data:
return False
guess1 = int(getLine(data))
if guess1 == gate1():
conn.sendall(b'The Serpent is surprised, but continues on with his questions.\n')
conn.sendall(b"Question 2: What is the Serpent's favorite number?\n")
data = conn.recv(128)
if not data:
return False
guess2 = int(getLine(data))
if gate2(guess2):
conn.sendall(b"You now have the Serpent's full attention. It stares at you with its beady eyes. It asks you one last question:\n")
conn.sendall(b"Question 3: What is the Serpent's least favorite number?\n")
data = conn.recv(128)
if not data:
return False
guess3 = int(getLine(data))
if gate3(guess3) == 1:
conn.sendall(b'The Serpent bows its head in defeat and slinks off. You run to the other side of the pass and retrieve your flag.\n')
conn.sendall(b'The flag has an inscription on it. It reads:\n')
try:
with open('flag.txt', 'r') as f:
flag = f.read()
except FileNotFoundError:
conn.sendall(b"Flag file not found. If you're seeing this, contact an admin ASAP.\n")
return True
conn.sendall(bytes(flag + '\n', 'utf-8'))
conn.close()
return True
elif gate3(guess3) == 0:
conn.sendall(b'As soon as you answer, the monster lashes back and throws you across the pond. Better luck next time.\n')
conn.close()
return True
else:
conn.sendall(b'The Serpent tries to think about your answer, but realizes that it takes too much of his (quite small) brainpower. He throws you across the pond anyway. Try a smaller guess next time.\n')
conn.close()
return True
else:
conn.sendall(b'As soon as you answer, the monster lashes back and throws you across the pond. Better luck next time.\n')
conn.close()
return True
else:
conn.sendall(b'As soon as you answer, the monster lashes back and throws you across the pond. Better luck next time.\n')
conn.close()
return True
except ConnectionResetError:
print(f'Connection reset. Connection by {addr} closing...')
def connect(s):
try:
print('connected')
while True:
try:
conn, addr = s.accept()
except ConnectionAbortedError:
print(f'Client disconnected')
return
thread = threading.Thread(target=handleConnection, args=(conn, addr))
thread.start()
print(f'# active threads: {threading.active_count()}')
except KeyboardInterrupt:
s.close()
print('exiting...')
sys.exit(130)
def bind() -> bool:
HOST = '0.0.0.0'
PORT = 8080
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
print(f'Listening on {PORT}')
connect(s)
s.close()
return False
def main():
try:
bind()
except OSError as error:
if error.errno == errno.EBADF:
print(error)
print('continuing...')
if __name__ == '__main__':
while True:
try:
main()
except KeyboardInterrupt:
print('exiting...')
sys.exit(130) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/pwn/boring-flag-runner/getprog.py | ctfs/RaRCTF/2021/pwn/boring-flag-runner/getprog.py | import sys
prog = input("enter your program: ").encode("latin-1")
open(f"{sys.argv[1]}", "wb").write(prog[:4000])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/mini-A3S/mini.py | ctfs/RaRCTF/2021/crypto/mini-A3S/mini.py | '''
Base-3 AES
Just use SAGE lmao
'''
T_SIZE = 3 # Fixed trits in a tryte
W_SIZE = 3 # Fixed trytes in a word (determines size of matrix)
POLY = (2, 0, 1, 1) # Len = T_SIZE + 1
POLY2 = ((2, 0, 1), (1, 2, 0), (0, 2, 1), (2, 0, 1)) # Len = W_SIZE + 1
CONS = ((1, 2, 0), (2, 0, 1), (1, 1, 1)) # Len = W_SIZE
I_CONS = ((0, 0, 2), (2, 2, 1), (2, 2, 2)) # Inverse of CONS (mod POLY2)
# Secure enough ig
SBOX = (9, 10, 11, 1, 2, 0, 20, 18, 19, 3, 4, 5, 22, 23, 21, 14, 12, 26, 24, 25, 13, 16, 17, 15, 8, 6, 7)
KEYLEN = 8
def up(array, size, filler): # If only there was APL in python :pensiv:
''' Groups up things in a tuple based on size '''
l = len(array)
array += (filler,) * (-l % size)
return tuple([array[i:i + size] for i in range(0, l, size)])
def down(array):
''' Ungroups objects in tuple '''
return sum(array, ())
def look(array):
if type(array) is int:
return array
while type(array[0]) is not int:
array = down(array)
return sum(array)
def clean(array):
while len(array) > 1:
if look(array[-1]):
break
array = array[:-1]
return tuple(array)
def int_to_tri(num): # positive only
out = []
while num:
num, trit = divmod(num, 3)
out.append(trit)
return tuple(out) if out else (0,)
def tri_to_int(tri):
out = 0
for i in tri[::-1]:
out *= 3
out += i
return out
tri_to_tyt = lambda tri: up(tri, T_SIZE, 0)
tyt_to_tri = lambda tyt: down(tyt)
int_to_tyt = lambda num: tri_to_tyt(int_to_tri(num))
tyt_to_int = lambda tyt: tri_to_int(down(tyt))
tyt_to_wrd = lambda tyt: up(tyt, W_SIZE, (0,) * T_SIZE)
wrd_to_tyt = lambda wrd: down(wrd)
def apply(func, filler=None): # scale up operations (same len only)
def wrapper(a, b):
return tuple(func(i, j) for i, j in zip(a, b))
return wrapper
xor = lambda a, b: (a + b) % 3
uxor = lambda a, b: (a - b) % 3
t_xor = apply(xor)
t_uxor = apply(uxor)
T_xor = apply(t_xor)
T_uxor = apply(t_uxor)
W_xor = apply(T_xor)
W_uxor = apply(T_uxor)
def tri_mul(A, B):
c = [0] * len(B)
for a in A[::-1]:
c = [0] + c
x = tuple(b * a % 3 for b in B)
c[:len(x)] = t_xor(c, x) # wtf slice assignment exists???
return clean(c)
def tri_divmod(A, B):
B = clean(B)
A2 = list(A)
c = [0]
while len(A2) >= len(B):
c = [0] + c
while A2[-1]:
A2[-len(B):] = t_uxor(A2[-len(B):], B)
c[0] = xor(c[0], 1)
A2.pop()
return clean(c), clean(A2) if sum(A2) else (0,)
def tri_mulmod(A, B, mod=POLY):
c = [0] * (len(mod) - 1)
for a in A[::-1]:
c = [0] + c
x = tuple(b * a % 3 for b in B)
c[:len(x)] = t_xor(c, x) # wtf slice assignment exists???
while c[-1]:
c[:] = t_xor(c, mod)
c.pop()
return tuple(c)
def egcd(a, b):
x0, x1, y0, y1 = (0,), (1,), b, a
while sum(y1):
q, _ = tri_divmod(y0, y1)
u, v = tri_mul(q, y1), tri_mul(q, x1)
x0, y0 = x0 + (0,) * len(u), y0 + (0,) * len(v)
y0, y1 = y1, clean(t_uxor(y0, u) + y0[len(u):])
x0, x1 = x1, clean(t_uxor(x0, v) + x0[len(v):])
return x0, y0
def modinv(a, m=POLY):
_, a = tri_divmod(a, m)
x, y = egcd(a, m)
if len(y) > 1:
raise Exception('modular inverse does not exist')
return tri_divmod(x, y)[0]
def tyt_mulmod(A, B, mod=POLY2, mod2=POLY):
fil = [(0,) * T_SIZE]
C = fil * (len(mod) - 1)
for a in A[::-1]:
C = fil + C
x = tuple(tri_mulmod(b, a, mod2) for b in B)
C[:len(x)] = T_xor(C, x)
num = modinv(mod[-1], mod2)
num2 = tri_mulmod(num, C[-1], mod2)
x = tuple(tri_mulmod(m, num2, mod2) for m in mod)
C[:len(x)] = T_uxor(C, x)
C.pop()
return C
'''
AES functions
'''
int_to_byt = lambda x: x.to_bytes((x.bit_length() + 7) // 8, "big")
byt_to_int = lambda x: int.from_bytes(x, byteorder="big")
def gen_row(size = W_SIZE):
out = ()
for i in range(size):
row = tuple(list(range(i * size, (i + 1) * size)))
out += row[i:] + row[:i]
return out
SHIFT_ROWS = gen_row()
UN_SHIFT_ROWS = tuple([SHIFT_ROWS.index(i) for i in range(len(SHIFT_ROWS))])
def rot_wrd(tyt): # only 1 word so treat as tyt array
return tyt[1:] + tyt[:1]
def sub_wrd(tyt):
return tuple(int_to_tyt(SBOX[tri_to_int(tri)])[0] for tri in tyt)
def u_sub_wrd(tyt):
return tuple(int_to_tyt(SBOX.index(tri_to_int(tri)))[0] for tri in tyt)
def rcon(num): # num gives number of constants given
out = int_to_tyt(1)
for _ in range(num - 1):
j = (0,) + out[-1]
while j[-1]: # xor until back in finite field
j = t_xor(j, POLY)
out += (j[:T_SIZE],)
return out
def expand(tyt):
words = tyt_to_wrd(tyt)
size = len(words)
rnum = size + 3
rcons = rcon(rnum * 3 // size)
for i in range(size, rnum * 3):
k = words[i - size]
l = words[i - 1]
if i % size == 0:
s = sub_wrd(rot_wrd(l))
k = T_xor(k, s)
k = (t_xor(k[0], rcons[i // size - 1]),) + k[1:]
else:
k = T_xor(k, l)
words = words + (k,)
return up(down(words[:rnum * 3]), W_SIZE ** 2, int_to_tyt(0)[0])
def mix_columns(tyt, cons=CONS):
tyt = list(tyt)
for i in range(W_SIZE):
tyt[i::W_SIZE] = tyt_mulmod(tyt[i::W_SIZE], cons)
return tuple(tyt)
def a3s(msg, key):
m = byt_to_int(msg)
k = byt_to_int(key)
m = up(int_to_tyt(m), W_SIZE ** 2, int_to_tyt(0)[0])[-1] # Fixed block size
k = int_to_tyt(k)
keys = expand(k) # tryte array
assert len(keys) == KEYLEN
ctt = T_xor(m, keys[0])
for r in range(1, len(keys) - 1):
ctt = sub_wrd(ctt) # SUB...
ctt = tuple([ctt[i] for i in SHIFT_ROWS]) # SHIFT...
ctt = mix_columns(ctt) # MIX...
ctt = T_xor(ctt, keys[r]) # ADD!
ctt = sub_wrd(ctt)
ctt = tuple([ctt[i] for i in SHIFT_ROWS])
ctt = T_xor(ctt, keys[-1]) # last key
ctt = tyt_to_int(ctt)
return int_to_byt(ctt)
def d_a3s(ctt, key):
c = byt_to_int(ctt)
k = byt_to_int(key)
c = up(int_to_tyt(c), W_SIZE ** 2, int_to_tyt(0)[0])[-1] # Fixed block size
k = int_to_tyt(k)
keys = expand(k)[::-1] # tryte array
assert len(keys) == KEYLEN
msg = c
msg = T_uxor(msg, keys[0])
for r in range(1, len(keys) - 1):
msg = tuple([msg[i] for i in UN_SHIFT_ROWS]) # UN SHIFT...
msg = u_sub_wrd(msg) # UN SUB...
msg = T_uxor(msg, keys[r]) # UN ADD...
msg = mix_columns(msg, I_CONS) # UN MIX!
msg = tuple([msg[i] for i in UN_SHIFT_ROWS])
msg = u_sub_wrd(msg)
msg = T_uxor(msg, keys[-1]) # last key
msg = tyt_to_int(msg)
return int_to_byt(msg)
def chunk(c):
c = byt_to_int(c)
c = up(int_to_tyt(c), W_SIZE ** 2, int_to_tyt(0)[0])
x = tuple(tyt_to_int(i) for i in c)
x = tuple(int_to_byt(i) for i in x)
return x
def unchunk(c):
out = []
for i in c:
j = byt_to_int(i)
j = up(int_to_tyt(j), W_SIZE ** 2, int_to_tyt(0)[0])
assert len(j) == 1
out.append(j[0])
out = down(out)
out = tyt_to_int(out)
return int_to_byt(out)
def pad(a):
return a + b"\x00" * (64 - len(a))
def byte_xor(a, b):
return bytes([i ^ j for i, j in zip(a, b)])
def gen():
from hashlib import sha512
flag, key = eval(open("secret.txt", "r").read())
hsh = sha512(key).digest()
with open("output.txt", "w+") as f:
f.write(f"Hash(Key) ^ Flag = {byte_xor(hsh, pad(flag))}" + "\n")
f.write(f"Enc(i, Key) for 0..3^9 = {tuple(a3s(int_to_byt(i), key) for i in range(3 ** 9))}")
if __name__ == "__main__":
gen()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/PsychECC/server.py | ctfs/RaRCTF/2021/crypto/PsychECC/server.py | from collections import namedtuple
import random
def moddiv(x,y,p):
return (x * pow(y, -1, p)) %p
Point = namedtuple("Point","x y")
class EllipticCurve:
INF = Point(0,0)
def __init__(self, a, b, p):
self.a = a
self.b = b
self.p = p
def add(self,P,Q):
if P == self.INF:
return Q
elif Q == self.INF:
return P
if P.x == Q.x and P.y == (-Q.y % self.p):
return self.INF
if P != Q:
Lambda = moddiv(Q.y - P.y, Q.x - P.x, self.p)
else:
Lambda = moddiv(3 * P.x**2 + self.a,2 * P.y , self.p)
Rx = (Lambda**2 - P.x - Q.x) % self.p
Ry = (Lambda * (P.x - Rx) - P.y) % self.p
return Point(Rx,Ry)
def multiply(self,P,n):
n %= self.p
if n != abs(n):
ans = self.multiply(P,abs(n))
return Point(ans.x, -ans.y % p)
R = self.INF
while n > 0:
if n % 2 == 1:
R = self.add(R,P)
P = self.add(P,P)
n = n // 2
return R
# P256 parameters, secure.
p = 115792089210356248762697446949407573530086143415290314195533631308867097853951
order = 115792089210356248762697446949407573529996955224135760342422259061068512044369
a = -3
b = 41058363725152142129326129780047268409114441015993725554835256314039467401291
E = EllipticCurve(a,b,p)
print("""Welcome to my prediction centre!
We're always looking out for psychics!
We're gonna choose a random number. You get to choose a point. We'll multiply that point by our random number.
Since this curve is of perfect and prime order, it'll be impossible to break this test.
Only a psychic could know!
Be psychic, get the flag.""")
x = int(input("Enter point x: "))
y = int(input("Enter point y: "))
P = Point(x,y)
n = random.randint(1,order)
Q = E.multiply(P,n)
print("Ok, where do you think the point will go?")
px = int(input("Enter point x: "))
py = int(input("Enter point y: "))
prediction = Point(px,py)
if prediction == E.INF or prediction == P:
print("Psychics don't use dirty tricks.")
quit()
if prediction == Q:
print("Wow! You're truly psychic!")
print(open("/challenge/flag.txt").read())
quit()
print("Better luck next time.")
print(f"Point was {Q}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/A3S/a3s.py | ctfs/RaRCTF/2021/crypto/A3S/a3s.py | '''
Base-3 AES
Just use SAGE lmao
'''
T_SIZE = 3 # Fixed trits in a tryte
W_SIZE = 3 # Fixed trytes in a word (determines size of matrix)
POLY = (2, 0, 1, 1) # Len = T_SIZE + 1
POLY2 = ((2, 0, 1), (1, 2, 0), (0, 2, 1), (2, 0, 1)) # Len = W_SIZE + 1
CONS = ((1, 2, 0), (2, 0, 1), (1, 1, 1)) # Len = W_SIZE
I_CONS = ((0, 0, 2), (2, 2, 1), (2, 2, 2)) # Inverse of CONS (mod POLY2)
# Secure enough ig
SBOX = (6, 25, 17, 11, 0, 19, 22, 14, 3, 4, 23, 12, 15, 7, 26, 20, 9, 1, 2, 18, 10, 13, 5, 21, 24, 16, 8)
KEYLEN = 28
def up(array, size, filler): # If only there was APL in python :pensiv:
''' Groups up things in a tuple based on size '''
l = len(array)
array += (filler,) * (-l % size)
return tuple([array[i:i + size] for i in range(0, l, size)])
def down(array):
''' Ungroups objects in tuple '''
return sum(array, ())
def look(array):
if type(array) is int:
return array
while type(array[0]) is not int:
array = down(array)
return sum(array)
def clean(array):
while len(array) > 1:
if look(array[-1]):
break
array = array[:-1]
return tuple(array)
def int_to_tri(num): # positive only
out = []
while num:
num, trit = divmod(num, 3)
out.append(trit)
return tuple(out) if out else (0,)
def tri_to_int(tri):
out = 0
for i in tri[::-1]:
out *= 3
out += i
return out
tri_to_tyt = lambda tri: up(tri, T_SIZE, 0)
tyt_to_tri = lambda tyt: down(tyt)
int_to_tyt = lambda num: tri_to_tyt(int_to_tri(num))
tyt_to_int = lambda tyt: tri_to_int(down(tyt))
tyt_to_wrd = lambda tyt: up(tyt, W_SIZE, (0,) * T_SIZE)
wrd_to_tyt = lambda wrd: down(wrd)
def apply(func, filler=None): # scale up operations (same len only)
def wrapper(a, b):
return tuple(func(i, j) for i, j in zip(a, b))
return wrapper
xor = lambda a, b: (a + b) % 3
uxor = lambda a, b: (a - b) % 3
t_xor = apply(xor)
t_uxor = apply(uxor)
T_xor = apply(t_xor)
T_uxor = apply(t_uxor)
W_xor = apply(T_xor)
W_uxor = apply(T_uxor)
def tri_mul(A, B):
c = [0] * len(B)
for a in A[::-1]:
c = [0] + c
x = tuple(b * a % 3 for b in B)
c[:len(x)] = t_xor(c, x) # wtf slice assignment exists???
return clean(c)
def tri_divmod(A, B):
B = clean(B)
A2 = list(A)
c = [0]
while len(A2) >= len(B):
c = [0] + c
while A2[-1]:
A2[-len(B):] = t_uxor(A2[-len(B):], B)
c[0] = xor(c[0], 1)
A2.pop()
return clean(c), clean(A2) if sum(A2) else (0,)
def tri_mulmod(A, B, mod=POLY):
c = [0] * (len(mod) - 1)
for a in A[::-1]:
c = [0] + c
x = tuple(b * a % 3 for b in B)
c[:len(x)] = t_xor(c, x) # wtf slice assignment exists???
while c[-1]:
c[:] = t_xor(c, mod)
c.pop()
return tuple(c)
def egcd(a, b):
x0, x1, y0, y1 = (0,), (1,), b, a
while sum(y1):
q, _ = tri_divmod(y0, y1)
u, v = tri_mul(q, y1), tri_mul(q, x1)
x0, y0 = x0 + (0,) * len(u), y0 + (0,) * len(v)
y0, y1 = y1, clean(t_uxor(y0, u) + y0[len(u):])
x0, x1 = x1, clean(t_uxor(x0, v) + x0[len(v):])
return x0, y0
def modinv(a, m=POLY):
_, a = tri_divmod(a, m)
x, y = egcd(a, m)
if len(y) > 1:
raise Exception('modular inverse does not exist')
return tri_divmod(x, y)[0]
def tyt_mulmod(A, B, mod=POLY2, mod2=POLY):
fil = [(0,) * T_SIZE]
C = fil * (len(mod) - 1)
for a in A[::-1]:
C = fil + C
x = tuple(tri_mulmod(b, a, mod2) for b in B)
C[:len(x)] = T_xor(C, x)
num = modinv(mod[-1], mod2)
num2 = tri_mulmod(num, C[-1], mod2)
x = tuple(tri_mulmod(m, num2, mod2) for m in mod)
C[:len(x)] = T_uxor(C, x)
C.pop()
return C
'''
AES functions
'''
int_to_byt = lambda x: x.to_bytes((x.bit_length() + 7) // 8, "big")
byt_to_int = lambda x: int.from_bytes(x, byteorder="big")
def gen_row(size = W_SIZE):
out = ()
for i in range(size):
row = tuple(list(range(i * size, (i + 1) * size)))
out += row[i:] + row[:i]
return out
SHIFT_ROWS = gen_row()
UN_SHIFT_ROWS = tuple([SHIFT_ROWS.index(i) for i in range(len(SHIFT_ROWS))])
def rot_wrd(tyt): # only 1 word so treat as tyt array
return tyt[1:] + tyt[:1]
def sub_wrd(tyt):
return tuple(int_to_tyt(SBOX[tri_to_int(tri)])[0] for tri in tyt)
def u_sub_wrd(tyt):
return tuple(int_to_tyt(SBOX.index(tri_to_int(tri)))[0] for tri in tyt)
def rcon(num): # num gives number of constants given
out = int_to_tyt(1)
for _ in range(num - 1):
j = (0,) + out[-1]
while j[-1]: # xor until back in finite field
j = t_xor(j, POLY)
out += (j[:T_SIZE],)
return out
def expand(tyt):
words = tyt_to_wrd(tyt)
size = len(words)
rnum = size + 3
rcons = rcon(rnum * 3 // size)
for i in range(size, rnum * 3):
k = words[i - size]
l = words[i - 1]
if i % size == 0:
s = sub_wrd(rot_wrd(l))
k = T_xor(k, s)
k = (t_xor(k[0], rcons[i // size - 1]),) + k[1:]
else:
k = T_xor(k, l)
words = words + (k,)
return up(down(words[:rnum * 3]), W_SIZE ** 2, int_to_tyt(0)[0])
def mix_columns(tyt, cons=CONS):
tyt = list(tyt)
for i in range(W_SIZE):
tyt[i::W_SIZE] = tyt_mulmod(tyt[i::W_SIZE], cons)
return tuple(tyt)
def a3s(msg, key):
m = byt_to_int(msg)
k = byt_to_int(key)
m = up(int_to_tyt(m), W_SIZE ** 2, int_to_tyt(0)[0])[-1] # Fixed block size
k = int_to_tyt(k)
keys = expand(k) # tryte array
assert len(keys) == KEYLEN
ctt = T_xor(m, keys[0])
for r in range(1, len(keys) - 1):
ctt = sub_wrd(ctt) # SUB...
ctt = tuple([ctt[i] for i in SHIFT_ROWS]) # SHIFT...
ctt = mix_columns(ctt) # MIX...
ctt = T_xor(ctt, keys[r]) # ADD!
ctt = sub_wrd(ctt)
ctt = tuple([ctt[i] for i in SHIFT_ROWS])
ctt = T_xor(ctt, keys[-1]) # last key
ctt = tyt_to_int(ctt)
return int_to_byt(ctt)
def d_a3s(ctt, key):
c = byt_to_int(ctt)
k = byt_to_int(key)
c = up(int_to_tyt(c), W_SIZE ** 2, int_to_tyt(0)[0])[-1] # Fixed block size
k = int_to_tyt(k)
keys = expand(k)[::-1] # tryte array
assert len(keys) == KEYLEN
msg = c
msg = T_uxor(msg, keys[0])
for r in range(1, len(keys) - 1):
msg = tuple([msg[i] for i in UN_SHIFT_ROWS]) # UN SHIFT...
msg = u_sub_wrd(msg) # UN SUB...
msg = T_uxor(msg, keys[r]) # UN ADD...
msg = mix_columns(msg, I_CONS) # UN MIX!
msg = tuple([msg[i] for i in UN_SHIFT_ROWS])
msg = u_sub_wrd(msg)
msg = T_uxor(msg, keys[-1]) # last key
msg = tyt_to_int(msg)
return int_to_byt(msg)
def chunk(c):
c = byt_to_int(c)
c = up(int_to_tyt(c), W_SIZE ** 2, int_to_tyt(0)[0])
x = tuple(tyt_to_int(i) for i in c)
x = tuple(int_to_byt(i) for i in x)
return x
def unchunk(c):
out = []
for i in c:
j = byt_to_int(i)
j = up(int_to_tyt(j), W_SIZE ** 2, int_to_tyt(0)[0])
assert len(j) == 1
out.append(j[0])
out = down(out)
out = tyt_to_int(out)
return int_to_byt(out)
def gen():
flag, key = eval(open("secret.txt", "r").read())
out = []
for i in chunk(flag):
out.append(a3s(i, key))
with open("challenge.txt", "w+") as f:
f.write(f'Encryption of "sus.": {a3s(b"sus.", key)}' + "\n")
f.write(f"Encryption of the flag: {unchunk(out)}" + "\n")
if __name__ == "__main__":
gen()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/snore/script.py | ctfs/RaRCTF/2021/crypto/snore/script.py | from Crypto.Util.number import *
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
from hashlib import sha224
from random import randrange
import os
p = 148982911401264734500617017580518449923542719532318121475997727602675813514863
g = 2
assert isPrime(p//2) # safe prime
x = randrange(p)
y = pow(g, x, p)
def verify(s, e, msg):
r_v = (pow(g, s, p) * pow(y, e, p)) % p
return bytes_to_long(sha224(long_to_bytes(r_v) + msg).digest()) == e
def sign(msg, k):
r = pow(g, k, p)
e = bytes_to_long(sha224(long_to_bytes(r) + msg).digest()) % p
s = (k - (x * e)) % (p - 1)
return (s, e)
def xor(ba1,ba2):
return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])
otp = os.urandom(32)
messages = [
b"Never gonna give you up",
b"Never gonna let you down",
b"Never gonna run around and desert you",
b"Never gonna make you cry",
b"Never gonna say goodbye",
b"Never gonna tell a lie and hurt you"
]
print("p = ", p)
print("g = ", g)
print("y = ", y)
for message in messages:
k = bytes_to_long(xor(pad(message, 32)[::-1], otp)) # OTP secure
s, e = sign(message, k % p)
assert (verify(s, e, message))
print(message, sign(message, k % p))
flag = open("flag.txt","rb").read()
key = sha224(long_to_bytes(x)).digest()[:16]
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(flag, 16)).hex()
print("ct = ", ct)
print("iv = ", iv.hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/babycrypt/server.py | ctfs/RaRCTF/2021/crypto/babycrypt/server.py | from Crypto.Util.number import getPrime, bytes_to_long
flag = bytes_to_long(open("/challenge/flag.txt", "rb").read())
def genkey():
e = 0x10001
p, q = getPrime(256), getPrime(256)
if p <= q:
p, q = q, p
n = p * q
pubkey = (e, n)
privkey = (p, q)
return pubkey, privkey
def encrypt(m, pubkey):
e, n = pubkey
c = pow(m, e, n)
return c
pubkey, privkey = genkey()
c = encrypt(flag, pubkey)
hint = pubkey[1] % (privkey[1] - 1)
print('pubkey:', pubkey)
print('hint:', hint)
print('c:', c)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/sRSA/script.py | ctfs/RaRCTF/2021/crypto/sRSA/script.py | from Crypto.Util.number import *
p = getPrime(256)
q = getPrime(256)
n = p * q
e = 0x69420
flag = bytes_to_long(open("flag.txt", "rb").read())
print("n =",n)
print("e =", e)
print("ct =",(flag * e) % n)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/unrandompad/unrandompad.py | ctfs/RaRCTF/2021/crypto/unrandompad/unrandompad.py | from random import getrandbits
from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long
def keygen(): # normal rsa key generation
primes = []
e = 3
for _ in range(2):
while True:
p = getPrime(1024)
if (p - 1) % 3:
break
primes.append(p)
return e, primes[0] * primes[1]
def pad(m, n): # pkcs#1 v1.5
ms = long_to_bytes(m)
ns = long_to_bytes(n)
if len(ms) >= len(ns) - 11:
return -1
padlength = len(ns) - len(ms) - 3
ps = long_to_bytes(getrandbits(padlength * 8)).rjust(padlength, b"\x00")
return int.from_bytes(b"\x00\x02" + ps + b"\x00" + ms, "big")
def encrypt(m, e, n): # standard rsa
res = pad(m, n)
if res != -1:
print(f"c: {pow(m, e, n)}")
else:
print("error :(", "message too long")
menu = """
[1] enc()
[2] enc(flag)
[3] quit
"""[1:]
e, n = keygen()
print(f"e: {e}")
print(f"n: {n}")
while True:
try:
print(menu)
opt = input("opt: ")
if opt == "1":
encrypt(int(input("msg: ")), e, n)
elif opt == "2":
encrypt(bytes_to_long(open("/challenge/flag.txt", "rb").read()), e, n)
elif opt == "3":
print("bye")
exit(0)
else:
print("idk")
except Exception as e:
print("error :(", e) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/rotoRSA/source.py | ctfs/RaRCTF/2021/crypto/rotoRSA/source.py | from sympy import poly, symbols
from collections import deque
import Crypto.Random.random as random
from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes
def build_poly(coeffs):
x = symbols('x')
return poly(sum(coeff * x ** i for i, coeff in enumerate(coeffs)))
def encrypt_msg(msg, poly, e, N):
return long_to_bytes(pow(poly(msg), e, N)).hex()
p = getPrime(256)
q = getPrime(256)
N = p * q
e = 11
flag = bytes_to_long(open("/challenge/flag.txt", "rb").read())
coeffs = deque([random.randint(0, 128) for _ in range(16)])
welcome_message = f"""
Welcome to RotorSA!
With our state of the art encryption system, you have two options:
1. Encrypt a message
2. Get the encrypted flag
The current public key is
n = {N}
e = {e}
"""
print(welcome_message)
while True:
padding = build_poly(coeffs)
choice = int(input('What is your choice? '))
if choice == 1:
message = int(input('What is your message? '), 16)
encrypted = encrypt_msg(message, padding, e, N)
print(f'The encrypted message is {encrypted}')
elif choice == 2:
encrypted_flag = encrypt_msg(flag, padding, e, N)
print(f'The encrypted flag is {encrypted_flag}')
coeffs.rotate(1) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/Shamirs_Stingy_Sharing/stingy.py | ctfs/RaRCTF/2021/crypto/Shamirs_Stingy_Sharing/stingy.py | import random, sys
from Crypto.Util.number import long_to_bytes
def bxor(ba1,ba2):
return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])
BITS = 128
SHARES = 30
poly = [random.getrandbits(BITS) for _ in range(SHARES)]
flag = open("/challenge/flag.txt","rb").read()
random.seed(poly[0])
print(bxor(flag, long_to_bytes(random.getrandbits(len(flag)*8))).hex())
try:
x = int(input('Take a share... BUT ONLY ONE. '))
except:
print('Do you know what an integer is?')
sys.exit(1)
if abs(x) < 1:
print('No.')
else:
print(sum(map(lambda i: poly[i] * pow(x, i), range(len(poly))))) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/randompad/randompad.py | ctfs/RaRCTF/2021/crypto/randompad/randompad.py | from random import getrandbits
from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long
def keygen(): # normal rsa key generation
primes = []
e = 3
for _ in range(2):
while True:
p = getPrime(1024)
if (p - 1) % 3:
break
primes.append(p)
return e, primes[0] * primes[1]
def pad(m, n): # pkcs#1 v1.5
ms = long_to_bytes(m)
ns = long_to_bytes(n)
if len(ms) >= len(ns) - 11:
return -1
padlength = len(ns) - len(ms) - 3
ps = long_to_bytes(getrandbits(padlength * 8)).rjust(padlength, b"\x00")
return int.from_bytes(b"\x00\x02" + ps + b"\x00" + ms, "big")
def encrypt(m, e, n): # standard rsa
res = pad(m, n)
if res != -1:
print(f"c: {pow(res, e, n)}")
else:
print("error :(", "message too long")
menu = """
[1] enc()
[2] enc(flag)
[3] quit
"""[1:]
e, n = keygen()
print(f"e: {e}")
print(f"n: {n}")
assert len(open("/challenge/flag.txt", "rb").read()) < 55
while True:
try:
print(menu)
opt = input("opt: ")
if opt == "1":
encrypt(int(input("msg: ")), e, n)
elif opt == "2":
encrypt(bytes_to_long(open("/challenge/flag.txt", "rb").read()), e, n)
elif opt == "3":
print("bye")
exit(0)
else:
print("idk")
except Exception as e:
print("error :(", e) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/crypto/minigen/minigen.py | ctfs/RaRCTF/2021/crypto/minigen/minigen.py | exec('def f(x):'+'yield((x:=-~x)*x+-~-x)%727;'*100)
g=f(id(f));print(*map(lambda c:ord(c)^next(g),list(open('f').read()))) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/secureuploader/app/app.py | ctfs/RaRCTF/2021/web/secureuploader/app/app.py | from flask import Flask, request, redirect, g
import sqlite3
import os
import uuid
app = Flask(__name__)
SCHEMA = """CREATE TABLE files (
id text primary key,
path text
);
"""
def db():
g_db = getattr(g, '_database', None)
if g_db is None:
g_db = g._database = sqlite3.connect("database.db")
return g_db
@app.before_first_request
def setup():
os.remove("database.db")
cur = db().cursor()
cur.executescript(SCHEMA)
@app.route('/')
def hello_world():
return """<!DOCTYPE html>
<html>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>"""
@app.route('/upload', methods=['POST'])
def upload():
if 'file' not in request.files:
return redirect('/')
file = request.files['file']
if "." in file.filename:
return "Bad filename!", 403
conn = db()
cur = conn.cursor()
uid = uuid.uuid4().hex
try:
cur.execute("insert into files (id, path) values (?, ?)", (uid, file.filename,))
except sqlite3.IntegrityError:
return "Duplicate file"
conn.commit()
file.save('uploads/' + file.filename)
return redirect('/file/' + uid)
@app.route('/file/<id>')
def file(id):
conn = db()
cur = conn.cursor()
cur.execute("select path from files where id=?", (id,))
res = cur.fetchone()
if res is None:
return "File not found", 404
with open(os.path.join("uploads/", res[0]), "r") as f:
return f.read()
if __name__ == '__main__':
app.run(host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/FBG/template-solve.py | ctfs/RaRCTF/2021/web/FBG/template-solve.py | import requests
import hashlib
import uuid
import binascii
import os
import sys
def generate():
return uuid.uuid4().hex[:4], uuid.uuid4().hex[:4]
def verify(prefix, suffix, answer, difficulty=6):
hash = hashlib.sha256(prefix.encode() + answer.encode() + suffix.encode()).hexdigest()
return hash.endswith("0"*difficulty)
def solve(prefix, suffix, difficulty):
while True:
test = binascii.hexlify(os.urandom(4)).decode()
if verify(prefix, suffix, test, difficulty):
return test
s = requests.Session()
host = "https://fbg.rars.win/"
data = s.get(host + "pow").json()
print("Solving POW")
solution = solve(data['pref'], data['suff'], 5)
print(f"Solved: {solution}")
s.post(host + "pow", json={"answer": solution})
name = "" # change this
link = "" # change this
r = s.get(host + f"admin?title={name}&link={link}")
print(r.text) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/FBG/chall/pow.py | ctfs/RaRCTF/2021/web/FBG/chall/pow.py | import hashlib
import uuid
import binascii
import os
def generate():
return uuid.uuid4().hex[:4], uuid.uuid4().hex[:4]
def verify(prefix, suffix, answer, difficulty=6):
hash = hashlib.sha256(prefix.encode() + answer.encode() + suffix.encode()).hexdigest()
return hash.endswith("0"*difficulty)
def solve(prefix, suffix, difficulty):
while True:
test = binascii.hexlify(os.urandom(4)).decode()
if verify(prefix, suffix, test, difficulty):
return test
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/FBG/chall/server.py | ctfs/RaRCTF/2021/web/FBG/chall/server.py | from flask import Flask, render_template, request, session, redirect, jsonify
import requests
import random
import time
from binascii import hexlify
import os
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/button')
def button():
title = request.args.get('title')
link = request.args.get('link')
return render_template('button.html', title=title, link=link)
@app.route('/admin')
def admin():
if (not session.get("verified")) or (not session.get("end")):
return redirect("/pow")
if session.get("end") < time.time():
del session['pref']
del session['suff']
del session['end']
del session['verified']
return redirect("/pow")
title = request.args.get('title')
link = request.args.get('link')
host = random.choice(["admin", "admin2", "admin3"])
r = requests.post(f"http://{host}/xss/add", json={"title": title, "link": link}, headers={"Authorization": os.getenv("XSSBOT_SECRET")})
return f'Nice button! The admin will take a look. Current queue position: {r.json()["position"]}'
@app.route("/pow", methods=["GET", "POST"])
def do_pow():
if request.method == 'GET':
import pow
pref, suff = pow.generate()
session['pref'], session['suff'] = pref, suff
time.sleep(1)
return jsonify({"pref": pref, "suff": suff})
else:
import pow
difficulty = int(os.getenv("DIFFICULTY", "5"))
pref, suff = session['pref'], session['suff']
answer = request.json.get('answer')
if pow.verify(pref, suff, answer, difficulty):
session['verified'] = True
session['end'] = time.time() + 30
return "Thank you!"
else:
return "POW incorrect"
app.secret_key = hexlify(os.urandom(24))
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/Electroplating/app/pow.py | ctfs/RaRCTF/2021/web/Electroplating/app/pow.py | import hashlib
import uuid
import binascii
import os
def generate():
return uuid.uuid4().hex[:4], uuid.uuid4().hex[:4]
def verify(prefix, suffix, answer, difficulty=6):
hash = hashlib.sha256(prefix.encode() + answer.encode() + suffix.encode()).hexdigest()
return hash.endswith("0"*difficulty)
def solve(prefix, suffix, difficulty):
while True:
test = binascii.hexlify(os.urandom(4)).decode()
if verify(prefix, suffix, test, difficulty):
return test
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/Electroplating/app/app.py | ctfs/RaRCTF/2021/web/Electroplating/app/app.py | import shutil
from bs4 import BeautifulSoup
import os
import random
import time
import tempfile
from flask import Flask, request, render_template, session, jsonify
from werkzeug.utils import secure_filename
import requests
app = Flask(__name__)
rust_template = """
#![allow(warnings, unused)]
use std::collections::HashMap;
use std::fs;
use std::env;
extern crate seccomp;
extern crate libc;
extern crate tiny_http;
extern crate seccomp_sys;
use seccomp::*;
use tiny_http::{Server, Response, Header, Request};
static ALLOWED: &'static [usize] = &[0, 1, 3, 11, 44,
60, 89, 131, 202,
231, 318];
fn main() {
let mut dir = env::current_exe().unwrap();
dir.pop();
dir.push("../../app.htmlrs");
let template = fs::read_to_string(dir.to_str().unwrap()).unwrap();
let server = Server::http("127.0.0.1:%s").unwrap();
apply_seccomp();
for request in server.incoming_requests() {
println!("received request! method: {:?}, url: {:?}",
request.method(),
request.url(),
);
handle_request(request, &template);
std::process::exit(0);
}
}
fn handle_request(req: Request, template: &String) {
let mut methods: HashMap<_, fn() -> String> = HashMap::new();
%s
let mut html = template.clone();
for (name, fun) in methods.iter() {
html = html.replace(name, &fun());
}
let header = Header::from_bytes(
&b"Content-Type"[..], &b"text/html"[..]
).unwrap();
let mut response = Response::from_string(html);
response.add_header(header);
req.respond(response).unwrap();
}
fn apply_seccomp() {
let mut ctx = Context::default(Action::KillProcess).unwrap();
for i in ALLOWED {
let rule = Rule::new(*i, None, Action::Allow);
ctx.add_rule(rule).unwrap();
}
ctx.load();
}
%s
"""
templ_fun = """
fn temp%s() -> String {
%s
}
"""
def get_result(template_path: str):
with open(template_path) as f:
templ = f.read()
with tempfile.TemporaryDirectory() as tmpdir:
shutil.copytree('skeleton', tmpdir, dirs_exist_ok=True)
os.chdir(tmpdir)
port = str(random.randrange(40000, 50000))
with open('src/main.rs', 'w') as f:
soup = BeautifulSoup(templ, 'html.parser')
funcs = []
for i, temp in enumerate(soup.find_all('templ')):
funcs.append(templ_fun % (i, temp.text))
templ = templ.replace(f'<templ>{temp.text}</templ>', f'temp{i}', 1)
hashmap = ""
for i in range(len(funcs)):
hashmap += f"""methods.insert("temp{i}", temp{i});\n"""
f.write(rust_template % (port, hashmap, '\n'.join(funcs)))
with open('app.htmlrs', 'w') as f:
f.write(templ)
os.system('cargo run --offline -q &')
for _ in range(10):
time.sleep(1)
try:
r = requests.get(f'http://localhost:{port}')
os.chdir('/app')
return r.text
except:
pass
return "App failed to start"
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if not session.get('verified'):
return "Please complete <pre>/pow</pre>", 403
os.chdir('/app')
if request.method == 'POST':
try:
file = request.files['file']
path = os.path.join('uploads', secure_filename(file.filename))
file.save(path)
response = get_result(path)
os.remove(path)
except:
return "There was an error"
del session['verified']
return render_template('upload.html', response=response)
else:
return render_template('upload.html')
@app.route("/pow", methods=["GET", "POST"])
def do_pow():
if request.method == 'GET':
import pow
pref, suff = pow.generate()
session['pref'], session['suff'], session['end'] = pref, suff, time.time() + 30
time.sleep(1)
return jsonify({"pref": pref, "suff": suff})
else:
import pow
difficulty = int(os.getenv("DIFFICULTY", "6"))
pref, suff = session['pref'], session['suff']
answer = request.json.get('answer')
if pow.verify(pref, suff, answer, difficulty):
session['verified'] = True
return "Thank you!"
else:
return "POW incorrect"
@app.before_request
def clear_cookies():
# Prevent replay attack
if session.get('end') and session['end'] < time.time():
del session['pref']
del session['suff']
del session['end']
def load_app(key):
app.secret_key = key
return app
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.