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/Balsn/2023/misc/Matrix/share/config.py | ctfs/Balsn/2023/misc/Matrix/share/config.py | FLAG = b'BALSN{dummy flag}'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/assembler.py | ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/assembler.py | from pwn import *
def aasm(code):
def check(condition):
if not condition:
print(f'invalid argument on line {lnum + 1} : {origLine}')
exit()
def getReg(rs):
if rs == 'pc':
return 4
elif rs == 'lr':
return 5
elif rs == 'inplen':
return 11
elif rs == 'caller':
return 12
elif rs == 'flag':
return 13
elif rs == 'sp':
return 14
elif rs == 'bp':
return 15
check(rs[0] == 'r')
try:
reg = int(rs[1:])
except:
check(False)
check(reg >= 0 and reg < 16)
return reg
def getNum(n, size, unsigned = False, dontCareSign = False):
if n[0] == '-':
sign = -1
n = n[1:]
else:
sign = 1
if len(n) > 2 and n[:2] == '0x':
base = 16
else:
base = 10
try:
n = int(n, base)
except:
check(False)
n *= sign
if dontCareSign:
Min = -(1 << size) // 2
Max = (1 << size) - 1
else:
if unsigned is False:
Min = -(1 << size) // 2
Max = (1 << size) // 2 - 1
else:
Min = 0
Max = (1 << size) - 1
check(n >= Min and n <= Max)
if n < 0:
n += (1 << size)
return n
JMP = {
'call': 0x40,
'jmp' : 0x41,
'jb' : 0x42,
'jae' : 0x43,
'je' : 0x44,
'jne' : 0x45,
'jbe' : 0x46,
'ja' : 0x47,
}
ALU = {
'add' : 0x50,
'sub' : 0x51,
'mul' : 0x52,
'div' : 0x53,
'and' : 0x54,
'or' : 0x55,
'xor' : 0x56,
'shr' : 0x57,
'shl' : 0x58,
'mov' : 0x59,
'cmp' : 0x5a,
}
JMPDST = {}
RESOLVE = {}
code = code.strip().split('\n')
bcode = b''
for lnum, line in enumerate(code):
origLine = line
comment = line.find('//')
if comment != -1:
line = line[:comment]
line = line.strip()
if line=='':
continue
#print(line)
line = line.split()
if line[0] == 'push':
check(len(line) == 2 or len(line) == 3)
if len(line) == 2:
#shorthand to not specify push imm size
n = getNum(line[1], 64, dontCareSign = True)
if n == 0:
S = 1
else:
S = (n.bit_length() + 7) // 8
bcode += p8(0x08 | (S - 1)) + int.to_bytes(n, S, 'little')
else:
check(len(line[1]) > 2 and line[1][0] == '<' and line[1][-1] == '>')
S = getNum(line[1][1:-1], 4, unsigned = True)
check(1 <= S and S <= 8)
if line[2][0].isdigit():
n = getNum(line[2], S * 8, dontCareSign = True)
bcode += p8(0x08 | (S - 1)) + int.to_bytes(n, S, 'little')
else:
r0 = getReg(line[2])
bcode += p8(0x18 | (S - 1)) + p8(r0)
elif line[0] == 'pop':
check(len(line) == 3)
check(len(line[1]) > 2 and line[1][0] == '<' and line[1][-1] == '>')
S = getNum(line[1][1:-1], 4, unsigned = True)
check(1 <= S and S <=8)
r0 = getReg(line[2])
bcode += p8(0x10 | (S - 1)) + p8(r0)
elif line[0] == 'load':
line = ' '.join(line[1:]).split(',')
check(len(line) == 2)
hasSize = line[0][0] == '<'
if not hasSize:
#shorthand to not specify load imm size
r0 = getReg(line[0].strip())
n = getNum(line[1].strip(), 64, dontCareSign = True)
if n == 0:
S = 1
else:
S = (n.bit_length() + 7) // 8
bcode += p8(0x30 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
S, r0 = line[0].strip().split()
check(len(S) > 2 and S[0] == '<' and S[-1] == '>')
S = getNum(S[1:-1], 4, unsigned = True)
check(1 <= S and S <= 8)
r0 = getReg(r0)
line[1] = line[1].strip()
if line[1][0] != '[':
n = getNum(line[1], S * 8, dontCareSign = True)
bcode += p8(0x30 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
check(line[1][0] == '[' and line[1][-1] == ']')
r1 = getReg(line[1][1:-1])
bcode += p8(0x20 | (S - 1)) + p8(r0 | (r1 << 4))
elif line[0] == 'store':
line = ' '.join(line[1:]).split(',')
check(len(line) == 2)
hasSize = line[0][0] == '<'
if not hasSize:
#shorthand to not specify store imm size
line[0] = line[0].strip()
check(line[0][0] == '[' and line[0][-1] == ']')
r0 = getReg(line[0][1:-1])
n = getNum(line[1].strip(), 64, dontCareSign = True)
if n == 0:
S = 1
else:
S = (n.bit_length() + 7) // 8
bcode += p8(0x38 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
S = line[0].strip().split()[0]
dst = line[0][len(S):].strip()
check(len(S) > 2 and S[0] == '<' and S[-1] == '>')
S = getNum(S[1:-1], 4, unsigned = True)
check(1 <= S and S <= 8)
dst = dst.strip()
check(dst[0] == '[' and dst[-1] == ']')
dst = dst[1:-1]
line[1] = line[1].strip()
if line[1][0] != 'r':
r0 = getReg(dst)
n = getNum(line[1], S * 8, dontCareSign = True)
bcode += p8(0x38 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
r0 = getReg(dst)
r1 = getReg(line[1])
bcode += p8(0x28 | (S - 1)) + p8(r0 | (r1 << 4))
elif line[0] in JMP:
check(len(line) == 2)
if line[1][0].isdigit() or line[1] not in ('r0','r1','r2','r3','r4','r5','r6','r7','r8','r9','r10','r11','r12','r13','r14','r15','pc','lr','inplen','caller','flag','sp','bp'):
if line[1][0].isdigit():
#Theoretically, we shouldn't do this, jumping to static offset is error prone, but allow for flexibility
n = getNum(line[1], 16)
bcode += p8(JMP[line[0]]) + p16(n)
else:
tag = line[1]
offset = len(bcode) + 3
if tag in JMPDST:
#This is a backward jump, so delta must be negative
delta = JMPDST[tag] - offset + (1 << 16)
bcode += p8(JMP[line[0]]) + p16(delta)
else:
RESOLVE[offset] = (tag, lnum, origLine)
bcode += p8(JMP[line[0]]) + p16(0)
else:
check(False)
'''
else:
r0 = getReg(line[1])
bcode += p8(JMP[line[0]] | 0x08) + p8(r0)
'''
elif line[0] in ALU:
opc = line[0]
line = ' '.join(line[1:]).strip().split(',')
check(len(line) == 2)
r0, r1 = getReg(line[0].strip()), getReg(line[1].strip())
bcode += p8(ALU[opc]) + p8(r0 | (r1 << 4))
elif line[0] == 'return':
check(len(line) == 1)
bcode += b'\xfd'
elif line[0] == 'invoke':
check(len(line) == 1)
bcode += b'\xfe'
elif line[0] == 'exit':
check(len(line) == 1)
bcode += b'\xff'
else:
check(len(line) == 1 and len(line[0]) > 1)
check(line[0][-1] == ':')
check(not line[0][0].isdigit())
tag = line[0][:-1]
check(tag not in JMPDST)
JMPDST[tag] = len(bcode)
for offset in RESOLVE:
tag, lnum, origLine = RESOLVE[offset]
if tag not in JMPDST:
print(f'unknown tag on line {lnum} : {origLine}')
exit()
delta = JMPDST[tag] - offset
bcode = bcode[:offset-2] + p16(delta) + bcode[offset:]
return bcode
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/interpreter.py | ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/interpreter.py | def interpret(bcode = [], inp = [], storage = []):
PC = 4
LR = 5
INPLEN = 11
CALLER = 12
FLAG = 13
SP = 14
BP = 15
def translateAddr(addr):
idx = addr>>32
offset = addr&0xffffffff
if idx > 4 or offset > 0x1000:
print(f'invalid addr : {hex(addr)}')
exit()
return idx, offset
def getMem(mem, addr, size):
idx, offset = translateAddr(addr)
if offset + size > 0x1000:
print(f'invalid mem get : {hex(addr)} {hex(size)}')
return int.from_bytes(mem[idx][offset : offset + size],'little')
def setMem(mem, addr, size, val):
idx, offset = translateAddr(addr)
if offset + size > 0x1000:
print(f'invalid mem set : {hex(addr)} {hex(size)}')
val = val & ((1 << (size * 8)) - 1)
v = int.to_bytes(val, size, 'little')
for i in range(size):
mem[idx][offset + i] = v[i]
if type(bcode) == bytes:
bcode = list(bcode)
if type(inp) == bytes:
inp = list(inp)
if type(storage) == bytes:
storage = list(storage)
regs = [0 for i in range(0x10)]
regs[PC] = 0x200000000 #pc
regs[LR] = 0xffffffffffffffff #lr
regs[FLAG] = 0 #flag
regs[SP] = 0x300001000 #sp
regs[BP] = 0x300001000 #bp
mem = [inp + [0 for i in range(0x1000 - len(inp))],
storage + [0 for i in range(0x1000 - len(storage))],
bcode + [0 for i in range(0x1000 - len(bcode))],
[0 for i in range(0x1000)],
[0 for i in range(0x1000)]]
while True:
opcode = getMem(mem, regs[PC], 1)
if (opcode & 0xf0) == 0 and (opcode & 0x8) == 0x8:
size = (opcode & 0x7) + 1
v = getMem(mem, regs[PC] + 1, size)
regs[PC] += 1 + size
regs[SP] -= size
setMem(mem, regs[SP], size, v)
elif (opcode & 0xf0) == 0x10:
size = (opcode & 0x7) + 1
r = getMem(mem, regs[PC] + 1, 1) & 0xf
regs[PC] += 2
if r in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0x8) == 0:
regs[r] = getMem(mem, regs[SP], size)
regs[SP] += size
else:
regs[SP] -= size
setMem(mem, regs[SP], size, regs[r])
elif (opcode & 0xf0) == 0x20:
size = (opcode & 0x7) + 1
r = getMem(mem, regs[PC] + 1, 1)
regs[PC] += 2
r1 = r & 0xf
r2 = r >> 4
if r1 in (PC, LR) or r2 in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0x8) == 0:
regs[r1] = getMem(mem, regs[r2], size)
else:
setMem(mem, regs[r1], size, regs[r2])
elif (opcode & 0xf0) == 0x30:
size = (opcode & 0x7) + 1
r = getMem(mem, regs[PC] + 1, 1) & 0xf
v = getMem(mem, regs[PC] + 2, size)
regs[PC] += 2 + size
if r in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0x8) == 0:
regs[r] = v
else:
setMem(mem, regs[r], size, v)
elif (opcode & 0xf0) == 0x40:
if (opcode & 0x8) == 0x8:
'''
r = getMem(mem, regs[PC] + 1, 1) & 0xf
regs[PC] += 2
dst = regs[r]
'''
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
else:
dst = getMem(mem, regs[PC] + 1, 2)
if dst >= 0x8000:
dst -= 0x10000
regs[PC] += 3
dst += regs[PC]
if (opcode & 0xf) == 0:
regs[PC] = dst
elif (opcode & 0xf) == 1:
regs[SP] -= 6
setMem(mem, regs[SP], 6, regs[LR]) #push lr
regs[SP] -= 6
setMem(mem, regs[SP], 6, regs[BP]) #push bp
regs[BP] = regs[SP]
regs[LR] = regs[PC]
regs[PC] = dst
elif (opcode & 0xf) == 2 and (regs[FLAG] & 4) == 4:
regs[PC] = dst
elif (opcode & 0xf) == 3 and (regs[FLAG] & 3) != 0:
regs[PC] = dst
elif (opcode & 0xf) == 4 and (regs[FLAG] & 1) == 1:
regs[PC] = dst
elif (opcode & 0xf) == 5 and (regs[FLAG] & 1) == 0:
regs[PC] = dst
elif (opcode & 0xf) == 6 and (regs[FLAG] & 5) != 0:
regs[PC] = dst
elif (opcode & 0xf) == 7 and (regs[FLAG] & 2) == 2:
regs[PC] = dst
elif (opcode & 0xf0) == 0x50 and (opcode & 0xf) <= 0xa:
r = getMem(mem, regs[PC] + 1, 1)
regs[PC] += 2
r1 = r & 0xf
r2 = r >> 4
if r1 in (PC, LR) or r2 in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0xf) == 0:
regs[r1] = (regs[r1] - regs[r2]) & 0xffffffffffffffff
if regs[r1] < 0:
regs[r1] += 0x10000000000000000
elif (opcode & 0xf) == 1:
regs[r1] = (regs[r1] + regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 2:
regs[r1] = (regs[r1] * regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 3:
regs[r1] = (regs[r1] // regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 4:
regs[r1] = (regs[r1] & regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 5:
regs[r1] = (regs[r1] | regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 6:
regs[r1] = (regs[r1] ^ regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 7:
regs[r1] = (regs[r1] >> (regs[r2] & 0x3f)) & 0xffffffffffffffff
elif (opcode & 0xf) == 8:
regs[r1] = (regs[r1] << (regs[r2] & 0x3f)) & 0xffffffffffffffff
elif (opcode & 0xf) == 9:
regs[r1] = regs[r2]
elif (opcode & 0xf) == 10:
flag = 0
if regs[r1] == regs[r2]:
flag |= 1
if regs[r1] > regs[r2]:
flag |= 2
if regs[r1] < regs[r2]:
flag |= 4
regs[FLAG] = flag
elif (opcode & 0xf0) == 0xf0 and (opcode & 0xf) >= 0xd:
if opcode == 0xfd:
regs[SP] = regs[BP]
regs[BP] = getMem(mem, regs[SP], 6)
regs[SP] += 6
regs[PC] = regs[LR]
regs[LR] = getMem(mem, regs[SP], 6)
regs[SP] += 6
elif opcode == 0xfe:
regs[PC] += 1
input('invoke')
elif opcode == 0xff:
regs[PC] += 1
return mem, regs
else:
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/crypto/Many_Time_QKD/const.py | ctfs/Balsn/2023/crypto/Many_Time_QKD/const.py | KEYLEN = 256
SEEDLEN = KEYLEN * 3
THRESHOLD = 0.1
SUCCESS = 0
FAILED = -1 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/crypto/Many_Time_QKD/main.py | ctfs/Balsn/2023/crypto/Many_Time_QKD/main.py | import sys, socket
from protocol import *
from player import *
DESCRIPTION = """
[Many-Time-QKD]
# Description
Alice and Bob are communicating through a noiseless channel, and you task is to steal their secret!
# Hint
When there are n qubits (quantum bits) being transmitted, you can input a string of length n.
To observe the i-th qubit, set the i-th character to '1'.
Otherwise, set the i-th character to '0'.
"""
def main():
print(DESCRIPTION)
f = open("/home/guessq/flag", "r")
flag = f.read()
alice = Player(msg=flag)
bob = Player()
qkd = QKD(alice, bob)
qkd.run()
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/Balsn/2023/crypto/Many_Time_QKD/quantum.py | ctfs/Balsn/2023/crypto/Many_Time_QKD/quantum.py | import numpy as np
class Qubit(object):
"A (pure) qubit."
def __init__(self, v:list):
assert len(v) == 2
norm = (abs(v[0])**2 + abs(v[1])**2)**0.5
self.v = np.array(v) / norm
def orthogonal(self):
return Qubit(np.conj([self.v[1], -self.v[0]]))
class Basis(object):
"A basis for C^2."
def __init__(self, qubit:Qubit):
self.basis = [qubit, qubit.orthogonal()]
def measure(self, q:Qubit, verbose=False):
"Measure a qubit."
probability = [abs(np.vdot(q.v, self.basis[0].v))**2,
abs(np.vdot(q.v, self.basis[1].v))**2]
probability = probability / sum(probability)
if verbose:
print(probability)
measured_bit = np.random.choice(2, p=probability)
collapased_qubit = self.basis[measured_bit]
return collapased_qubit, measured_bit
PAULI_BASES = [Basis(Qubit([1+0j, 1+0j])), Basis(Qubit([1+0j, 0+0j]))]
THETA = np.pi/8
MAGIC_QUBIT = Qubit([np.cos(THETA)+0j, np.sin(THETA)+0j])
MAGIC_BASIS = Basis(MAGIC_QUBIT) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/crypto/Many_Time_QKD/protocol.py | ctfs/Balsn/2023/crypto/Many_Time_QKD/protocol.py | from quantum import *
from const import *
class QKD(object):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def run(self):
status = FAILED
while status != SUCCESS:
self.p1.init()
self.p2.init()
self.quantum_protocol()
status = self.classical_protocol()
def quantum_protocol(self):
ans = input(f"[{SEEDLEN} qubits are transmitted.]\n")
observed = ""
for i in range(SEEDLEN):
qubit = self.p1.send_qubit(i)
if 0 <= i < len(ans) and ans[i] == "1":
collapsed_qubit, measured_bit = MAGIC_BASIS.measure(qubit)
qubit = collapsed_qubit
observed = observed + str(measured_bit)
else:
observed = observed + "?"
self.p2.recv_qubit(qubit, i)
print(observed)
return SUCCESS
def classical_protocol(self):
basis1 = self.p1.send_basis()
basis2 = self.p2.send_basis()
self.p1.recv_basis(basis2)
self.p2.recv_basis(basis1)
index_key = [i for i in range(SEEDLEN) if basis1[i] == basis2[i]]
index_key.sort()
index_key_str = ','.join([str(i) for i in index_key]) + "\n"
print(index_key_str)
key1 = self.p1.send_key()
key2 = self.p2.send_key()
ber = len([i for i in range(len(key1)) if key1[i] != key2[i]]) / len(index_key)
if self.p1.is_safe(ber):
ciphertext, nonce = self.p1.send_secret_message()
print(ciphertext.hex())
print(nonce.hex())
return SUCCESS
else:
return FAILED | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/crypto/Many_Time_QKD/player.py | ctfs/Balsn/2023/crypto/Many_Time_QKD/player.py | import os
import random
import bitstring
from Crypto.Cipher import AES
from quantum import *
from const import *
class Player(object):
def __init__(self, msg=""):
self.seed = bitstring.BitArray(os.urandom(SEEDLEN//8))
self.key = None
self.basis = None
self.msg = msg
def init(self):
self.basis = bitstring.BitArray(os.urandom(SEEDLEN//8))
def send_qubit(self, index):
return PAULI_BASES[self.basis[index]].basis[self.seed[index]]
def recv_qubit(self, qubit, index):
_, measured_bit = PAULI_BASES[self.basis[index]].measure(qubit)
self.seed[index] = measured_bit
def send_basis(self):
return self.basis
def recv_basis(self, basis):
index_same_basis = [i for i in range(SEEDLEN) if self.basis[i] == basis[i]]
self.key = self.seed[index_same_basis]
def send_key(self):
return self.key
def is_safe(self, ber):
return (len(self.key) >= KEYLEN) and (ber > THRESHOLD)
def send_secret_message(self):
key_in_bytes = self.key[0:KEYLEN].tobytes()
cipher = AES.new(key_in_bytes, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(self.msg.encode())
return ciphertext, nonce | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/crypto/Geometry_Hash/chall.py | ctfs/Balsn/2023/crypto/Geometry_Hash/chall.py | import secrets
from sympy import N, Float, Point, Triangle
from secret import FLAG
PRECISION = 1337
def main():
import signal
signal.alarm(20)
levels = [
lambda x: x.centroid,
lambda x: x.circumcenter,
lambda x: x.incenter,
]
try:
for level in levels:
challenge(level)
print(FLAG)
except:
print("Wasted")
def challenge(hash_function):
# raise an error if the user fails the challenge
print("===== Challenge =====")
A = RandomLine()
B = RandomLine()
C = RandomLine()
# print parameters
A.print()
B.print()
C.print()
i, j, k = [secrets.randbits(32) for _ in range(3)]
triangle = Triangle(A[i], B[j], C[k])
hsh = hash_function(triangle)
print(Float(hsh.x, PRECISION))
print(Float(hsh.y, PRECISION))
_i, _j, _k = map(int, input("> ").split(" "))
assert (i, j, k) == (_i, _j, _k)
print("Mission passed")
class RandomLine:
def __init__(self):
self.x = randFloat()
self.y = randFloat()
self.dx = randFloat()
self.dy = randFloat()
def __getitem__(self, i):
return Point(self.x + self.dx * i, self.y + self.dy * i, evaluate=False)
def print(self):
print(self.x)
print(self.y)
print(self.dx)
print(self.dy)
def randFloat():
# return a random float between -1 and 1
return -1 + 2 * Float(secrets.randbits(PRECISION), PRECISION) / (1 << PRECISION)
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/Balsn/2022/pwn/sentinel/share/instanceManager.py | ctfs/Balsn/2022/pwn/sentinel/share/instanceManager.py | #!/usr/bin/python3
import os
import sys
import subprocess
import string
import uuid
import hashlib
import random
###Boilerplate utils
def printError(errMsg):
print(errMsg)
exit()
def myInput(prompt):
'''
python input prompts to stderr by default, and there is no option to change this afaik
this wrapper is just normal input with stdout prompt
'''
print(prompt,end='')
return input()
def doPow(difficulty,adminSecret):
challenge = ''.join(random.choices(string.ascii_letters,k=10))
print(f"(int.from_bytes(hashlib.sha256(('{challenge}' + answer).encode()).digest(), byteorder='little') & ((1 << {difficulty}) - 1)) == 0")
answer = myInput('answer > ')
if answer==adminSecret or (int.from_bytes(hashlib.sha256((challenge+answer).encode()).digest(),byteorder='little')&((1<<difficulty)-1))==0:
return True
else:
return False
###Instance management utils
def genInstanceId():
return str(uuid.uuid4()).replace('-','')
def checkInstanceId(instanceId):
if len(instanceId)!=32:
return False
instanceIdCSET = set(string.ascii_lowercase+string.digits)
for c in instanceId:
if c not in instanceIdCSET:
return False
return True
def instanceExists(instancePath,secret=None):
if not os.path.exists(instancePath):
return False
if secret is not None:
with open(os.path.join(instancePath,'secret'),'r') as f:
secretF = f.read().strip()
if secret!=secretF:
return False
return True
def instanceIsRunning(instanceId):
if subprocess.getoutput('docker container ls -q -f "name=config_sentinel{instanceId}.*" 2>/dev/null')!='':
return True
return False
def populateInstanceConfig(instanceId,instancePath,instanceConfigPath,guestHomeDir):
Dockerfile = f'''
from ubuntu:jammy
RUN useradd -m sentinel
USER sentinel
WORKDIR /home/sentinel/
ENTRYPOINT ["./sentinel"]
'''
dockerCompose = f'''
version: '3'
volumes:
storage{instanceId}:
driver: local
driver_opts:
type: overlay
o: lowerdir={guestHomeDir},upperdir={os.path.join(instancePath,'upper')},workdir={os.path.join(instancePath,'work')}
device: overlay
services:
sentinel{instanceId}:
build: ./
volumes:
- storage{instanceId}:/home/sentinel/
stdin_open : true
'''
with open(os.path.join(instanceConfigPath,'Dockerfile'),'w') as f:
f.write(Dockerfile)
with open(os.path.join(instanceConfigPath,'docker-compose.yml'),'w') as f:
f.write(dockerCompose)
def buildInstanceDocker(instanceId,instancePath):
configPath = os.path.join(instancePath,'config')
cwd = os.getcwd()
os.chdir(configPath)
os.system(f'docker-compose build sentinel{instanceId} 1>/dev/null 2>/dev/null')
os.chdir(cwd)
def cleanupInstanceDocker(instanceId):
os.system(f'docker rmi -f config_sentinel{instanceId} 1>/dev/null 2>/dev/null')
os.system(f'docker volume rm config_storage{instanceId} 1>/dev/null 2>/dev/null')
def resetInstance(instanceId,instancePath,noCleanup=False):
upperdirPath = os.path.join(instancePath,'upper')
workdirPath = os.path.join(instancePath,'work')
if noCleanup is False:
cleanupInstanceDocker(instanceId)
os.system(f'chmod -fR 777 {upperdirPath}')
os.system(f'chmod -fR 777 {workdirPath}')
os.system(f'rm -fr {upperdirPath}')
os.system(f'rm -fr {workdirPath}')
if os.path.exists(upperdirPath) or os.path.exists(workdirPath):
printError(f'reset instance {instanceId} failed, please contact admin')
os.system(f"mkdir -p {os.path.join(upperdirPath,'work')} && chmod 555 {upperdirPath} && chmod 777 {os.path.join(upperdirPath,'work')}")
os.system(f'mkdir {workdirPath} && chmod 555 {workdirPath}')
buildInstanceDocker(instanceId,instancePath)
def launchInstance(instanceId,instanceConfigPath):
os.chdir(instanceConfigPath)
print(os.getcwd())
os.system(f'docker-compose run --rm sentinel{instanceId}')
def createInstance(instanceRootDir,guestHomeDir):
secret = hashlib.sha256(myInput('secret > ').strip().encode()).hexdigest()
instanceId = genInstanceId()
instancePath = os.path.join(instanceRootDir,instanceId)
while instanceExists(instancePath):
instanceId = getInstanceId()
instancePath = os.path.join(instanceRootDir,instanceId)
os.mkdir(instancePath)
with open(os.path.join(instancePath,'secret'),'w') as f:
f.write(secret)
instanceConfigPath = os.path.join(instancePath,'config')
os.mkdir(instanceConfigPath)
populateInstanceConfig(instanceId,instancePath,instanceConfigPath,guestHomeDir)
print(f'instanceId : {instanceId} (keep this for future reference)')
sys.stdout.flush()
resetInstance(instanceId,instancePath,noCleanup=True)
launchInstance(instanceId,instanceConfigPath)
def resumeInstance(instanceRootDir,reset=False):
instanceId = myInput('instanceId > ').strip()
secret = hashlib.sha256(myInput('secret > ').strip().encode()).hexdigest()
if checkInstanceId(instanceId) is False:
printError(f'illegal instanceId : {instanceId}')
instancePath = os.path.join(instanceRootDir,instanceId)
if not instanceExists(instancePath,secret):
printError(f'instance {instanceId}:{secret} does not exist')
if instanceIsRunning(instanceId):
printError(f'cannot reset/resume {instanceId} while it is running')
if reset:
resetInstance(instanceId,instancePath)
instanceConfigPath = os.path.join(instancePath,'config')
launchInstance(instanceId,instanceConfigPath)
def removeInstance(instanceRootDir):
instanceId = myInput('instanceId > ').strip()
secret = hashlib.sha256(myInput('secret > ').strip().encode()).hexdigest()
if checkInstanceId(instanceId) is False:
printError(f'illegal instanceId : {instanceId}')
instancePath = os.path.join(instanceRootDir,instanceId)
if not instanceExists(instancePath,secret):
printError(f'instance {instanceId}:{secret} does not exist')
if instanceIsRunning(instanceId):
printError(f'cannot delete {instanceId} while it is running')
cleanupInstanceDocker(instanceId)
os.system(f'chmod -fR 777 {instancePath}')
os.system(f'rm -fr {instancePath}')
###Service
def menu():
print('========================================')
print(' Sentinel ')
print(' Flag Secure Computing as a Service ')
print('========================================')
print(' 1. Create new instance ')
print(' 2. Resume previous instance ')
print(' 3. Reset and resume previous instance ')
print(' 4. Remove instance ')
print(' 5. Leave ')
print('========================================')
return int(myInput('Choice > ').strip())
if __name__=='__main__':
if len(sys.argv)!=5:
printError('usage : python3 instanceManager.py [instanceRootDir] [guestHomeDir] [powDifficulty] [adminSecret]')
instanceRootDir = sys.argv[1]
guestHomeDir = sys.argv[2]
powDifficulty = int(sys.argv[3])
adminSecret = sys.argv[4]
match menu():
case 1:
if doPow(powDifficulty,adminSecret) is False:
printError('invalid pow')
createInstance(instanceRootDir,guestHomeDir)
case 2:
resumeInstance(instanceRootDir,reset=False)
case 3:
resumeInstance(instanceRootDir,reset=True)
case 4:
removeInstance(instanceRootDir)
case 5:
print('goodbye')
case _:
print('unrecognized option')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2022/pwn/flag_market/src/backend/backend.py | ctfs/Balsn/2022/pwn/flag_market/src/backend/backend.py | #!/usr/bin/env python3
import os
from datetime import datetime
from flask import Flask, abort, request
def create_app():
app = Flask(__name__)
@app.errorhandler(Exception)
def help(error):
return "Try to buy a flag!\n"
@app.route("/buy_flag", methods=["SPECIAL_METHOD_TO_BUY_FLAG"])
def buy_flag():
args = request.args
data = request.form
keys = ["card_holder", "card_number", "card_exp_year", "card_exp_month", "card_cvv", "card_money"]
if any(k not in args for k in keys):
abort(404)
if "padding" not in data:
abort(404)
if args["card_holder"] != "M3OW/ME0W":
abort(404)
if args["card_number"] != "4518961863728788":
abort(404)
exp_date = f'{args["card_exp_month"]}/{args["card_exp_year"]}'
card_exp = datetime.strptime(exp_date, "%m/%Y")
if card_exp < datetime.now():
abort(404)
if args["card_cvv"] != "618":
abort(404)
if int(args["card_money"]) < 133731337:
abort(404)
if any(chr(c) not in data["padding"] for c in range(256)):
abort(404)
return f'{os.getenv("FLAG2", "BALSN{FLAG2}")}\n'
return app
# if __name__ == '__main__':
# app = create_app()
# port = int(os.getenv("BACKEND_PORT", 29092))
# app.run(host="0.0.0.0", port=port, debug=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2022/pwn/Want_my_signature/share/main.py | ctfs/Balsn/2022/pwn/Want_my_signature/share/main.py | #!/usr/bin/env python3
import uuid
import os
import shutil
import tarfile
import time
import re
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
app = Flask(__name__, template_folder='templates')
app.config['MAX_CONTENT_LENGTH'] = 4 * 1000 * 1000
@app.route("/")
def upload():
return render_template('./upload.html')
@app.route('/uploader', methods = ['POST'])
def upload_file():
if request.method == 'POST':
old_umask = os.umask(0o77)
dir_name = os.path.join('/tmp/tmp', str(uuid.uuid4()))
file_name = os.path.join(dir_name, str(uuid.uuid4()))
os.makedirs(dir_name, exist_ok=True)
try:
f = request.files['file']
f.save(file_name)
if tarfile.is_tarfile(file_name):
mal = False
with tarfile.open(file_name) as t:
for name in t.getnames():
if name[0] == '/' or '..' in name:
mal = True
break
mem = t.getmember(name)
if '/' in mem.linkname or '..' in mem.linkname:
mal = True
break
if not mal:
t.extractall(dir_name)
os.remove(file_name)
if not mal:
r = os.system('LD_PRELOAD=/home/want_my_signature/libmsgpackc.so.2 /home/want_my_signature/verify '+dir_name)
if r == 0:
ret = 'File uploaded successfully<br>Hi'
else:
ret = 'No hack! >:('
else:
ret = 'No hack! >:('
else:
ret = 'Can only upload tar file >:('
except Exception as e:
ret = 'Something went wrong :( <br>' + str(e)
finally:
shutil.rmtree(dir_name)
return ret
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2022/rev/Propaganda/run.py | ctfs/Balsn/2022/rev/Propaganda/run.py | import subprocess
flag = b'BALSN{____this__is______not_a_flag_______}'
answer = [9128846476475241493, 7901709191400900973, 9127969212443560833, 8731519357089725617, 4447363623394058601, 616855300804233277]
output = []
for i in range(0, len(flag), 8):
number = int.from_bytes(flag[i:i+8], 'little')
output.append(int((subprocess.check_output(['node', 'launcher.js', str(number)]))[:-2]))
print(output == answer)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2022/crypto/LFSR/chall.py | ctfs/Balsn/2022/crypto/LFSR/chall.py | from Crypto.Util.number import *
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
import os
import base64
from hashlib import sha256
from secret import flag
# LFSR template by Cryptanalyse
class StreamCipher:
def __init__(self, key):
assert len(key) == 128, "Error: the key must be of exactly 128 bits."
self._s = key
self._t = [0, 1, 2, 7]
self._p = [0, 8, 16, 32, 64, 120]
self._f = [[0], [2], [3], [5], [0, 1], [0, 3], [1, 4], [2, 3],\
[0, 1, 4], [2, 3, 4], [0, 1, 2, 4, 5], [1, 2, 3, 4, 5]]
def _prod(self, L):
return all(x for x in L)
def _sum(self, L):
return sum(L) & 1
def _clock(self):
x = [self._s[p] for p in self._p]
self._s = self._s[1:] + [self._sum(self._s[p] for p in self._t)]
return self._sum(self._prod(x[v] for v in m) for m in self._f)
def keystream(self, size):
c = []
for i in range(size):
b = 0
for _ in range(8):
b = (b << 1) | self._clock()
c += [b]
return bytes(c)
key = os.urandom(16)
lfsr = StreamCipher(list(map(int, list(f"{bytes_to_long(key):0128b}"))))
ks = lfsr.keystream(1 << 10)
cipher = AES.new(key, AES.MODE_CBC, iv=b"\0" * 16)
ciphertext = cipher.encrypt(pad(flag, 16))
f = open("out.txt", "w")
f.write(base64.b64encode(ks).decode("ascii") + "\n" + ciphertext.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2022/crypto/Yet_another_RSA_with_hint/chall.py | ctfs/Balsn/2022/crypto/Yet_another_RSA_with_hint/chall.py | from Crypto.Util.number import *
from secret import flag
p = getPrime(512)
q = getPrime(512)
n = p * q
e = 0x10001
c = pow(bytes_to_long(flag), e, n)
def digitsSum(n, base):
ret = 0
while n:
ret += n % base
n //= base
return ret
hint = [digitsSum(p, i) for i in range(2, 200)]
print(f"{n = }")
print(f"{e = }")
print(f"{c = }")
print(f"{hint = }") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2022/crypto/vss/chall.py | ctfs/Balsn/2022/crypto/vss/chall.py | from Crypto.Util.number import *
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import os
import random
from hashlib import sha256
from secret import FLAG
class ShareScheme:
def __init__(self, key: bytes):
assert len(key) == 128
self.key1 = bytes_to_long(key[:64])
self.key2 = bytes_to_long(key[64:])
def getShare(self):
p = getPrime(512)
a = random.randint(2, p - 1)
b = random.randint(2, p - 1)
c = random.randint(2, p - 1)
y = (a + self.key1 * b + self.key2 * c) % p
return p, a, b, c, y
def commit(val: int):
p = getPrime(512)
g = random.randint(2, p - 1)
print(f"Commitment: {p} {g} {pow(g, val, p)}")
key = os.urandom(128)
ss = ShareScheme(key)
real_key = sha256(key).digest()[:16]
cipher = AES.new(real_key, AES.MODE_ECB)
enc_flag = cipher.encrypt(pad(FLAG, 16))
print(f"flag = {enc_flag.hex()}")
while True:
op = int(input("Option: "))
if op == 1:
p, a, b, c, y = ss.getShare()
print(f"{p = }")
print(f"{a = }")
print(f"{b = }")
print(f"{c = }")
commit(y)
else:
exit(0) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/crypto/Small_Inscription/SmallInscription.py | ctfs/DanteCTF/2023/crypto/Small_Inscription/SmallInscription.py | #!/usr/bin/env python3
from Crypto.Util.number import bytes_to_long, getPrime
from secret import FLAG
assert len(FLAG) < 30
if __name__ == '__main__':
msg = bytes_to_long(
b'There is something reeeally important you should know, the flag is '+FLAG)
N = getPrime(1024)*getPrime(1024)
e = 3
ct = pow(msg, e, N)
print(f'{ct=}')
print(f'{N=}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/crypto/DIY_enc/DIYenc.py | ctfs/DanteCTF/2023/crypto/DIY_enc/DIYenc.py | #!/usr/bin/env python3
import os
from Crypto.Cipher import AES
from base64 import b64encode
from secret import FLAG
assert len(FLAG) == 19
if __name__ == '__main__':
print('Encrypting flag...')
key = os.urandom(16)
nonce = os.urandom(15)
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
# longer ciphertext => safer ciphertext
flag_enc = cipher.encrypt(FLAG*3).hex()
print(f'Encrypted flag = {flag_enc}\n')
print('You can choose only the length of the plaintext, but not the plaintext. You will not trick me :)')
for i in range(7):
length = int(input('> '))
assert length > 3 and length < 100, "Invalid input"
pt = b64encode(os.urandom(length))
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
ct = cipher.encrypt(pt).hex()
print(f'ct = {ct}')
print('Enough.')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/crypto/PiedPic/PiedPic.py | ctfs/DanteCTF/2023/crypto/PiedPic/PiedPic.py | #!/usr/bin/env python3
from PIL import Image
from Crypto.Random import get_random_bytes
from io import BytesIO
from base64 import b64encode, b64decode
flag_file = "flag.png"
def encrypt_image(image, key):
perm_table = {0: (0, 1, 2), 1: (0, 2, 1), 2: (1, 0, 2), 3: (1, 2, 0), 4: (2, 0, 1), 5: (2, 1, 0)}
size = image.size[0] * image.size[1]
assert(size == len(key))
pixels = list(image.getdata())
for i in range(len(pixels)):
p = pixels[i]
kbyte = key[i]
color = [p[i]^255 if kbyte & (1 << i) else p[i] for i in range(3)]
(r,g,b) = perm_table[int(kbyte) % 6]
pixels[i] = (color[r], color[g], color[b])
image.putdata(pixels)
bs = BytesIO()
image.save(bs, format=flag_file[-3:])
return b64encode(bs.getvalue())
def handle():
print("Dante took many pictures of his journey to the afterlife.")
print("They contain many revelations. I give you one of these pictures if you give me one of yours!")
answer = input("Do you accept the exchange [y/n]?")
if answer == 'y':
flag = Image.open(flag_file)
key = get_random_bytes(flag.size[0] * flag.size[1])
encrypted_flag = encrypt_image(flag, key)
print(f"My picture:\n\n{encrypted_flag.decode()}\n\n")
data = input("Your picture:")
image = Image.frombytes(data=b64decode(data), mode=flag.mode, size=flag.size)
encrypted_data = encrypt_image(image, key)
print(f"This is for you:\n\n{encrypted_data.decode()}\n\n")
print("Bye!")
if __name__ == '__main__':
try:
handle()
except Exception:
print("Something went wrong, bye!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/run.py | ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/run.py | import time
import secrets
from flask import Flask, session, redirect, jsonify, request, make_response
from utils.db_connection import Connector
from utils.renders import render_template
import jwt
from waitress import serve
app = Flask(__name__)
conn = Connector()
cursor = conn.initMySQL()
token_jwt = secrets.token_bytes(32).decode()
@app.before_request
def checkBefore():
global cursor
global session
cursor = conn.initMySQL()
if session and "time" in session and time.time() - session['time'] > 7000: #2-hours
session.pop("time", None)
return redirect("/")
def verifyAndDecodeToken(encoded):
decodedJWT = ""
error = False
try:
decodedJWT = jwt.decode(encoded, token_jwt, algorithms=["HS256"])
except Exception:
error = True
return decodedJWT if not error else False
@app.route('/addToCart', methods=["POST"])
def addToCart():
if session and "encodedJWT" in request.cookies:
decodedJWT = verifyAndDecodeToken(request.cookies.get('encodedJWT'))
if decodedJWT and decodedJWT['authorized'] == "true":
productid = request.form["productid"]
productInCart = conn.addProductToCart(cursor, productid, decodedJWT['userId'])
if productInCart:
return jsonify({"success":"Product added to the cart of " + decodedJWT['username'] })
return redirect('/')
@app.route('/shop', methods=["GET", "POST"])
def shop():
if session and "encodedJWT" in request.cookies:
decodedJWT = verifyAndDecodeToken(request.cookies.get('encodedJWT'))
if decodedJWT and decodedJWT['authorized'] == "true":
productsList = conn.getProductsFromDb(cursor)
return render_template('shop.html', products = productsList)
return redirect('/')
@app.route('/showCart', methods=["GET"])
def showCart():
if session and "encodedJWT" in request.cookies:
decodedJWT = verifyAndDecodeToken(request.cookies.get('encodedJWT'))
if decodedJWT and decodedJWT['authorized'] == "true":
productInCart = conn.getProductFromCart(cursor, decodedJWT['userId'])
message = 'No items found yet in your cart'
if len(productInCart)> 0:
message = decodedJWT['username'] + " Here is your cart"
return render_template('cart.html', products = productInCart, message=message, display="block")
return redirect('/')
@app.route('/refreshTime', methods=['HEAD'])
def refresh():
if "time" not in session:
session['time'] = time.time()
return redirect('/')
@app.route('/', methods=["GET", "POST"])
def login():
if request.method == "POST" and "identifier" in request.cookies:
username = request.form["username"]
password = request.form["password"]
identifier = request.cookies['identifier']
loginResult = conn.loginUserCheck(username, password, identifier, cursor)
if (loginResult):
#set jwt token to allow the access to the shop
encodedJwt = jwt.encode({"authorized": "true", "username":username, \
"identifier":identifier, "userId":loginResult}, token_jwt, algorithm="HS256")
resp = make_response(redirect('/shop'))
resp.set_cookie('encodedJWT', encodedJwt)
return resp
return jsonify({"error":"Invalid Credentials"})
return render_template('login.html')
@app.route('/register', methods=["GET", "POST"])
def register():
if session and "authorized" in session and session['authorized'] == True:
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
if len(password) < 8:
return jsonify({"error":"Password must have at least 8 chars"})
registerResult = conn.registerUser(username, password, cursor)
if not registerResult:
return jsonify({"error":"Account registration was not succesfull"})
resp = make_response(redirect('/'))
resp.set_cookie('identifier', registerResult)
return resp
return render_template('register.html')
return jsonify({"error":"We're developing the site. Registrations are not allowed yet."})
if __name__ == "__main__":
app.secret_key = secrets.token_hex(16)
serve(app, host='0.0.0.0', port=1999)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/secrets.py | ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/secrets.py | from random import choice
def token_hex(value):
alphabet = 'abcdef0123456789'
return ''.join(choice(alphabet) for _ in range(5))
def token_bytes(value):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(choice(alphabet) for _ in range(value)).encode()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/utils/renders.py | ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/utils/renders.py | from flask import render_template_string
def __openTemplate(template):
with open('./templates/'+template, "r") as f:
return f.read()
def render_template(template, **kwargs):
temp = __openTemplate(template).format(**kwargs)
return render_template_string(temp, **kwargs) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/utils/db_connection.py | ctfs/DanteCTF/2023/web/CryptoMarket/challenge/flask/utils/db_connection.py | import mysql.connector
import os
import bcrypt
import hashlib
import secrets
class Connector(object):
def __init__(self):
self.host = os.getenv('MYSQL_DATABASE_HOST')
self.user = os.getenv('MYSQL_DATABASE_USER')
self.password = os.getenv('MYSQL_DATABASE_PASSWORD')
self.db = os.getenv('MYSQL_DATABASE_DB')
self.connection = None
def initMySQL(self):
self.connection = mysql.connector.connect(host=self.host,
database=self.db,
user=self.user,
password=self.password)
return self.connection.cursor(prepared=True, dictionary=True)
def loginUserCheck(self, username, password, identifier, cursor):
query = "SELECT id,password FROM user WHERE username = %s AND identifier = %s"
user_to_retrivie = (username, identifier)
cursor.execute(query, user_to_retrivie)
rows = cursor.fetchall()
return str(rows[0]['id']) if len(rows) > 0 and\
bcrypt.checkpw(password.encode(), rows[0]['password'].encode())\
else False
def getProductsFromDb(self, cursor):
query = "SELECT * FROM products"
cursor.execute(query)
rows = cursor.fetchall()
return rows
def addProductToCart(self, cursor, productid, userid):
query = """INSERT INTO cart (productid,userid) VALUES (%s,%s)"""
to_parameterize = (int(productid), int(userid))
thrownEx = False
try:
cursor.execute(query, to_parameterize)
self.connection.commit()
except Exception:
thrownEx = True
return not thrownEx
def getProductFromCart(self, cursor, userid):
rows = []
query = """SELECT name,price FROM products AS P JOIN cart
as C ON P.id = C.productid WHERE C.userid = %s"""
useridBind = (userid,)
cursor.execute(query, useridBind)
rows = cursor.fetchall()
return rows
def registerUser(self, username, password, cursor):
sql_insert_query = """ INSERT INTO user
(username, password, identifier) VALUES (%s,%s,%s)"""
identifier = hashlib.sha256(secrets.token_bytes(64)).hexdigest()
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
user_to_inser = (username, hashed, identifier)
thrownEx = False
try:
cursor.execute(sql_insert_query, user_to_inser)
self.connection.commit()
except Exception:
thrownEx = True
return identifier if not thrownEx else False
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/run.py | ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/run.py | from flask import Flask, render_template, request, session, redirect, jsonify, make_response
from flask_mysqldb import MySQL
from utils.db_connection import db_Connection as cnn
from utils.userUtils import userUtils as utl
from serverRequestHandler import serverHandler as server
from waitress import serve
import os
app = Flask(__name__)
# Inizialization Classes
utils = utl()
sqler = cnn(app, MySQL(), utils)
cursor = None
jwt_token = os.environ['JWT_SECRET']
backend = server()
@app.before_request
def updateConnection():
global cursor
cursor = sqler.initMySql()
@app.route('/')
def root():
if not session or session['username'] != sqler.staticAdminSelector(cursor):
return redirect('/getinfo/1')
return redirect('/dashboard')
@app.route('/getinfo/<id>')
def dosomething(id):
# I'm still learning sql + python
# Method for code skills testing purposes
try:
user_id = int(id)
except ValueError:
return "Nope"
cursor.execute(f"SELECT * FROM user WHERE id = ':{user_id}:'")
rows = cursor.fetchall()
resp = jsonify(rows)
return resp
@app.route('/panel', methods=["GET", "POST"])
def panel():
if session and session['username'] == sqler.staticAdminSelector(cursor):
if request.method == "POST":
key = request.form["key"]
value = request.form["value"]
backendResponseList = backend.sendRequest(key, value, jwt_token, utils)
resp = make_response(render_template('dashboard.html', adminName=session['username'], display="yes", responseFromServer=backendResponseList[0]))
resp.set_cookie("magicToken", backendResponseList[1])
return resp
return redirect('/dashboard')
return redirect('/login')
@app.route('/getSignedCookie', methods=["POST"])
def getSignedCookie():
if session and session['username'] == sqler.staticAdminSelector(cursor):
if request.method == "POST":
key = request.form["key"]
value = request.form["value"]
encoded_jwt = utils.jwtSignerMethod({key: value}, jwt_token)
resp = make_response(render_template('dashboard.html', adminName=session['username'], display="none"))
resp.set_cookie("magicToken", encoded_jwt)
return resp
return redirect('/dashboard')
return redirect('/login')
@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
if session and session['username'] == sqler.staticAdminSelector(cursor):
return render_template("dashboard.html", adminName=session['username'], display="none", response_from_server="")
return redirect('/login')
@app.route('/login', methods=["GET", "POST"])
def performLogin():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
if username == "" or password == "":
return render_template("login.html", displayStatus="block")
login = sqler.queryExecutor(query=username, cursor=cursor)
if (login):
verified = utils.hash_verifier(password=password, recoveredPassword=login['password'])
if verified:
session['username'] = login['username']
return redirect("/dashboard")
return render_template("login.html", displayStatus="block")
return render_template("login.html", displayStatus="none")
if __name__ == "__main__":
app.secret_key = utils.generateRandomToken(16)
serve(app, host='0.0.0.0', port=1999)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/serverRequestHandler.py | ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/serverRequestHandler.py | import requests as r
import base64
import hashlib
import os
class serverHandler:
requestObject = ''
urllocation = ''
def __init__(self):
self.urllocation = f'http://{os.environ["BACKEND_HOST"]}:1717/index.php'
self.requestObject = 'TzoxMToiTUQ1REJFbmdpbmUiOjI6e3M6MjE6IgBNRDVEQkVuZ2luZQBvYmpBcnJheSI7YToxOntzOjM6Im9iaiI7cjoxO31zOjIzOiIATUQ1REJFbmdpbmUASGFzaFN0cmluZyI7czozMjoiMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiO30='
def sendRequest(self, key, word, jwt_token, utils):
value = base64.b64decode(self.requestObject.encode()).decode()
value = value.replace('00000000000000000000000000000000', hashlib.md5(word.encode()).hexdigest())
myDict = {key: base64.b64encode(value.encode()).decode()}
encoded_jwt = utils.jwtSignerMethod(myDict, jwt_token)
cookies = {'decodeMyJwt': encoded_jwt}
response = r.get(self.urllocation, cookies=cookies).text
return [response if 'FOUND' in response else 'Your password is secure, no matches in our dbs', encoded_jwt]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/utils/db_connection.py | ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/utils/db_connection.py | import os
import re
class db_Connection(object):
def __init__(self, app, mysql, utils) -> None:
self.app = app
self.mysql = mysql
self.utils = utils
# MySQL configurations
self.app.config['MYSQL_USER'] = os.getenv('MYSQL_DATABASE_USER')
self.app.config['MYSQL_PASSWORD'] = os.getenv('MYSQL_DATABASE_PASSWORD')
self.app.config['MYSQL_DB'] = os.getenv('MYSQL_DATABASE_DB')
self.app.config['MYSQL_HOST'] = os.getenv('MYSQL_DATABASE_HOST')
self.app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
self.mysql.init_app(self.app)
def initMySql(self):
return self.mysql.connection.cursor()
def __recursiveStrip(self, query):
# Copied from stack overflow, I don't even know what it filters exactly
matches = ["updatexml", "extract", "%", "unhex", "hex",
"join", "roles", "id", "rolestring", "role",
"ascii", "concat", "lower", "upper", "mid", "substr", "substring",
"replace", "right", "left", "strcmp", "rtrim", "rpad", "ucase", "lcase",
"max", "cast", "conv", "convert", "if", "benchmark", ">", "<",
"->", "/", "*", "aes", "char", "compress", "find", "base64", "instr",
"is", "json", "left", "md5", "oct", "ord", "regexp", "sha", "space", "digest",
"trim", "uncompress", "xor", "~", "|", "case", "when"]
patterns = [".*,.*[uU][sS][eE][rR][nN][aA][mM][eE]"]
for x in patterns:
if re.match(x, query.lower()):
query = query.lower()
query = re.sub(x, "", query)
for x in matches:
if x in query.lower():
query = query.lower()
query = query.replace(x, "")
return self.__recursiveStrip(query) \
if any([x in query.lower() for x in matches]) \
or any([re.match(query.lower(), x) for x in patterns]) \
else query
def staticAdminSelector(self, cursor):
cursor.execute(f"SELECT username FROM user as u JOIN roles as r ON u.id = r.id WHERE r.roleString = 'admin'")
got = cursor.fetchall()
return got[0]['username'] if len(got) > 0 else self.utils.generateRandomToken(20)
def queryExecutor(self, query, cursor):
query = query.replace("'", "\\'")
matches = ["select", "where", "sleep"]
# Adding some personal filters just to be 100% sure
if any([x in query.lower() for x in matches]):
query = re.sub("[Ss][Ee][Ll][Ee][Cc][Tt]", "", query)
query = re.sub("[Ww][Hh][Ee][Rr][Ee]", "", query)
query = re.sub("[Ss][Ll][Ee][Ee][Pp]", "", query)
escaped = self.__recursiveStrip(query)
thrownException = False
got = []
try:
cursor.execute(f"SELECT * FROM user WHERE username = '{escaped}'")
got = cursor.fetchall()
except:
thrownException = True
return got[0] if not thrownException and len(got) > 0 else None
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/utils/userUtils.py | ctfs/DanteCTF/2023/web/SecureHashedDb/challenge/app/src/utils/userUtils.py | import bcrypt
import jwt
import secrets
class userUtils:
def __init__(self) -> None:
pass
def hash_verifier(self, password, recoveredPassword):
result = False
exception = False
try:
result = bcrypt.checkpw(password.encode(), recoveredPassword.encode())
except Exception:
exception = True
return result \
if recoveredPassword.startswith("$2y$") and not exception else False
def jwtSignerMethod(self, dictToEncode, jwt_token):
return jwt.encode(dictToEncode, jwt_token, algorithm="HS256")
def generateRandomToken(self, length):
return secrets.token_hex(length)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/misc/replayflow/model.py | ctfs/osuigaming/2024/misc/replayflow/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class ReplayFlow(nn.Module):
def __init__(self, D=8, W=256):
super(ReplayFlow, self).__init__()
self.linears = nn.ModuleList(
# input: (t, x, y)
[nn.Linear(3, W)] +
[nn.Linear(W, W) for _ in range(D)]
)
# (dx/t, dy/dt)
self.vel_output = nn.Linear(W, 2)
def forward(self, x):
for l in self.linears:
x = F.leaky_relu(l(x))
v = self.vel_output(x)
return v
model = ReplayFlow()
model.load_state_dict(torch.load("model.pt")) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/misc/i_hate_anime_girls/server.py | ctfs/osuigaming/2024/misc/i_hate_anime_girls/server.py | #!/usr/local/bin/python
import base64
import sys
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
import torchvision.transforms as T
from torchvision.models import resnet18
model = resnet18()
model.fc = nn.Linear(model.fc.in_features, 1)
model.load_state_dict(torch.load("model.pt"))
resize = T.Resize((224, 224))
to_tensor = T.ToTensor()
normalize = T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
original = np.array(Image.open("hitorigoto.png"))
inp = input(f"Enter a base64 encoded image.\n")
try:
img = np.frombuffer(base64.standard_b64decode(inp), dtype=np.uint8)
img = img.reshape(original.shape)
assert np.max(np.abs(original.astype(np.int32) - img.astype(np.int32))) <= 8
except:
print("That doesn't look like hitorigoto!")
sys.exit(0)
image = Image.fromarray(img)
x = normalize(resize(to_tensor(image)).unsqueeze(0))
with torch.no_grad():
y = torch.sigmoid(model(x))
if y < 0.5:
print("That's obviously an anime girl.")
sys.exit(0)
elif y < 0.825:
print("I'm not fully convinced that's not an anime girl.")
sys.exit(0)
with open("flag.txt") as f:
print("Surely that's not an anime girl.")
print(f.read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/pwn/osu_v8/server.py | ctfs/osuigaming/2024/pwn/osu_v8/server.py | import sys
import os
sys.stdout.write("script size:\n")
sys.stdout.flush()
size = int(sys.stdin.readline().strip())
if size > 102400:
sys.stdout.write("No way!\n")
sys.stdout.flush()
sys.exit(1)
sys.stdout.write("script:\n")
sys.stdout.flush()
script = sys.stdin.read(size)
with open(sys.argv[1], 'w') as f:
f.write(script)
os.system("/home/ctf/d8 " + sys.argv[1]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/crypto/base727/727.py | ctfs/osuigaming/2024/crypto/base727/727.py | import binascii
flag = open('flag.txt').read()
def encode_base_727(string):
base = 727
encoded_value = 0
for char in string:
encoded_value = encoded_value * 256 + ord(char)
encoded_string = ""
while encoded_value > 0:
encoded_string = chr(encoded_value % base) + encoded_string
encoded_value //= base
return encoded_string
encoded_string = encode_base_727(flag)
print(binascii.hexlify(encoded_string.encode()))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/crypto/no_dorchadas/server.py | ctfs/osuigaming/2024/crypto/no_dorchadas/server.py | from hashlib import md5
from secret import flag, secret_slider
from base64 import b64encode, b64decode
assert len(secret_slider) == 244
dorchadas_slider = b"0,328,33297,6,0,B|48:323|61:274|61:274|45:207|45:207|63:169|103:169|103:169|249:199|249:199|215:214|205:254,1,450.000017166138,6|6,1:1|2:1,0:0:0:0:"
def sign(beatmap):
hsh = md5(secret_slider + beatmap)
return hsh.hexdigest()
def verify(beatmap, signature):
return md5(secret_slider + beatmap).hexdigest() == signature
def has_dorchadas(beatmap):
return dorchadas_slider in beatmap
MENU = """
--------------------------
| [1] Sign a beatmap |
| [2] Verify a beatmap |
--------------------------"""
def main():
print("Welcome to the osu! Beatmap Signer")
while True:
print(MENU)
try:
option = input("Enter your option: ")
if option == "1":
beatmap = b64decode(input("Enter your beatmap in base64: "))
if has_dorchadas(beatmap):
print("I won't sign anything with a dorchadas slider in it >:(")
else:
signature = sign(beatmap)
print("Okay, I've signed that for you: " + signature)
elif option == "2":
beatmap = b64decode(input("Enter your beatmap in base64: "))
signature = input("Enter your signature for that beatmap: ")
if verify(beatmap, signature) and has_dorchadas(beatmap):
print("How did you add that dorchadas slider?? Anyway, here's a flag: " + flag)
elif verify(beatmap, signature):
print("Signature is valid!")
else:
print("Signature is invalid :(")
except:
print("An error occurred!")
exit(-1)
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/crypto/korean_offline_mafia/server.py | ctfs/osuigaming/2024/crypto/korean_offline_mafia/server.py | from topsecret import n, secret_ids, flag
import math, random
assert all([math.gcd(num, n) == 1 for num in secret_ids])
assert len(secret_ids) == 32
vs = [pow(num, 2, n) for num in secret_ids]
print('n =', n)
print('vs =', vs)
correct = 0
for _ in range(1000):
x = int(input('Pick a random r, give me x = r^2 (mod n): '))
assert x > 0
mask = '{:032b}'.format(random.getrandbits(32))
print("Here's a random mask: ", mask)
y = int(input('Now give me r*product of IDs with mask applied: '))
assert y > 0
# i.e: if bit i is 1, include id i in the product--otherwise, don't
val = x
for i in range(32):
if mask[i] == '1':
val = (val * vs[i]) % n
if pow(y, 2, n) == val:
correct += 1
print('Phase', correct, 'of verification complete.')
else:
correct = 0
print('Verification failed. Try again.')
if correct >= 10:
print('Verification succeeded. Welcome.')
print(flag)
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/crypto/wysi_prime/script.py | ctfs/osuigaming/2024/crypto/wysi_prime/script.py | from Crypto.Util.number import isPrime, bytes_to_long
import random
import os
def getWYSIprime():
while True:
digits = [random.choice("727") for _ in range(272)]
prime = int("".join(digits))
if isPrime(prime):
return prime
# RSA encryption using the WYSI primes
p = getWYSIprime()
q = getWYSIprime()
n = p * q
e = 65537
flag = bytes_to_long(os.getenv("FLAG", b"osu{fake_flag_for_testing}"))
ciphertext = pow(flag, e, n)
print(f"{n = }")
print(f"{e = }")
print(f"{ciphertext = }") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/crypto/lucky_roll_gaming/script.py | ctfs/osuigaming/2024/crypto/lucky_roll_gaming/script.py | from Crypto.Util.number import getPrime # https://pypi.org/project/pycryptodome/
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from random import randrange
from math import floor
def lcg(s, a, b, p):
return (a * s + b) % p
p = getPrime(floor(72.7))
a = randrange(0, p)
b = randrange(0, p)
seed = randrange(0, p)
print(f"{p = }")
print(f"{a = }")
print(f"{b = }")
def get_roll():
global seed
seed = lcg(seed, a, b, p)
return seed % 100
out = []
for _ in range(floor(72.7)):
out.append(get_roll())
print(f"{out = }")
flag = open("flag.txt", "rb").read()
key = bytes([get_roll() for _ in range(16)])
iv = bytes([get_roll() for _ in range(16)])
cipher = AES.new(key, AES.MODE_CBC, iv)
print(cipher.encrypt(pad(flag, 16)).hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/osuigaming/2024/crypto/secret_map/enc.py | ctfs/osuigaming/2024/crypto/secret_map/enc.py | import os
xor_key = os.urandom(16)
with open("flag.osu", 'rb') as f:
plaintext = f.read()
encrypted_data = bytes([plaintext[i] ^ xor_key[i % len(xor_key)] for i in range(len(plaintext))])
with open("flag.osu.enc", 'wb') as f:
f.write(encrypted_data)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/wtf/2021/crypto/Pr4nK/3ncrypt.py | ctfs/wtf/2021/crypto/Pr4nK/3ncrypt.py | import binascii
import random
flag = ""
fl = int(binascii.hexlify(flag), 16)
p = 1 << 1024
b = random.randint(0, p) | 1
s = random.randint(0, p)
x = pow(b, s, p)
print('p: {}'.format(p))
print('b: {}'.format(b))
print('x: {}'.format(x))
y = int(input('y: '))
z = pow(y, s, p)
Message = fl ^ z
print('Message: {}'.format(Message))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/wtf/2021/crypto/H4ck3r_Vs_C0d3r/encr3pt.py | ctfs/wtf/2021/crypto/H4ck3r_Vs_C0d3r/encr3pt.py | from PIL import Image, ImageDraw
import os
import sys
from random import SystemRandom
random = SystemRandom()
xrange = range
I3 = Image.open
if len(sys.argv) != 2:
exit()
fl = str(sys.argv[1])
O1 = os.path.isfile
O2 = os.path.splitext
if not O1(fl):
exit()
i = I3(fl)
f, e = O2(fl)
O_A = f+"_A.png"
O_B = f+"_B.png"
i = i.convert('1')
I1 = Image.new
I2 = ImageDraw.Draw
a = i.size[0]*2
b = i.size[1]*2
i_A = I1('1', (a, b))
d_A = I2(i_A)
i_B = I1('1', (a, b))
d_B = I2(i_B)
ps = ((1, 1, 0, 0), (1, 0, 1, 0), (1, 0, 0, 1),
(0, 1, 1, 0), (0, 1, 0, 1), (0, 0, 1, 1))
for x in xrange(0, int(a/2)):
for y in xrange(0, int(b/2)):
pix = i.getpixel((x, y))
p = random.choice(ps)
d_A.point((x*2, y*2), p[0])
d_A.point((x*2+1, y*2), p[1])
d_A.point((x*2, y*2+1), p[2])
d_A.point((x*2+1, y*2+1), p[3])
if pix == 0:
d_B.point((x*2, y*2), 1-p[0])
d_B.point((x*2+1, y*2), 1-p[1])
d_B.point((x*2, y*2+1), 1-p[2])
d_B.point((x*2+1, y*2+1), 1-p[3])
else:
d_B.point((x*2, y*2), p[0])
d_B.point((x*2+1, y*2), p[1])
d_B.point((x*2, y*2+1), p[2])
d_B.point((x*2+1, y*2+1), p[3])
i_A.save(O_A, 'PNG')
i_B.save(O_B, 'PNG')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/wtf/2022/rev/A_Tale_of_code/briefcase.py | ctfs/wtf/2022/rev/A_Tale_of_code/briefcase.py | import hashlib
def flagify(f):
fl = str(int(f)**5)
l1 = list(fl)
l2 = [115, 110, 102, 60, 75, 69, 114, 112, 51, 43, 87, 50, 91, 89, 43, 106, 94, 47, 43, 49, 44, 122]
flag = []
for i in range(len(l1)):
flag.append(chr(int(l1[i])+l2[i]))
return "".join(flag)
code = input("Enter the code:")
chk = "6799b5a7f2b55b86346ba9cc9fe1b5239282274a46d4c63bb78bf17223f8ca8d"
if chk == hashlib.sha3_256(code.encode()).hexdigest():
print("Inside the suitcase you find a dozen eggs!\nAlso, " + flagify(code))
else:
print("The suitcase doesn't open") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/wtf/2022/crypto/pixels/encrypt.py | ctfs/wtf/2022/crypto/pixels/encrypt.py | from PIL import Image
im = Image.open("flag.png")
col,row = im.size
pix = im.load()
key = ''
k = []
for i in key:
k.append(ord(i))
enc = Image.new(im.mode,im.size)
out = enc.load()
for i in range(col):
for j in range(row):
ca = (k[0] + k[1]*i) % col
ra = (k[2] + k[3]*j) % row
out[ca,ra] = pix[i,j]
for i in range(0,col,2):
for j in range(0,row,2):
out[i,j] = out[i,j] ^ k[4]
out[i+1,j] = out[i+1,j] ^ k[5]
out[i,j+1] = out[i,j+1] ^ k[6]
out[i+1,j+1] = out[i+1,j+1] ^ k[7]
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/TJCTF/2024/misc/ml_project/encode.py | ctfs/TJCTF/2024/misc/ml_project/encode.py | import torch
flag = open("flag.txt").read().strip()
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.f1 = torch.nn.Linear(len(flag), 22)
self.relu = torch.nn.ReLU()
self.f2 = torch.nn.Linear(22, 18)
def forward(self, x):
x = self.relu(self.f1(x))
return self.f2(x)
model = Model()
model.f1.weight = torch.nn.Parameter(torch.randint(0, 10, (22, len(flag)), dtype=torch.float64))
model.f1.bias = torch.nn.Parameter(torch.randint(0, 10, (22,), dtype=torch.float64))
model.f2.weight = torch.nn.Parameter(torch.randint(0, 10, (18, 22), dtype=torch.float64))
model.f2.bias = torch.nn.Parameter(torch.randint(0, 10, (18,), dtype=torch.float64))
torch.save(model.state_dict(), "model.pth")
x = torch.tensor([ord(c) for c in flag], dtype=torch.float64).unsqueeze(0)
y = model(x)
torch.save(y.detach(), "output.pth")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/misc/roundabout/enc.py | ctfs/TJCTF/2024/misc/roundabout/enc.py | import dataclasses
import re
import secrets
import sys
from pyrage import passphrase # type: ignore
args = sys.argv[1:]
def make_password(num_words):
text = open("amontillado.txt").read()
words = list(set(re.sub("[^a-z]", " ", text.lower()).split()))
return "".join(secrets.choice(words) for _ in range(num_words))
@dataclasses.dataclass
class Node:
letter: str
id: int
@dataclasses.dataclass
class Edge:
a: Node
b: Node
@dataclasses.dataclass
class Graph:
nodes: list[Node]
edges: list[Edge]
class IdGen:
def __init__(self):
self.ids = set()
def generate_id(self):
while True:
new_id = secrets.randbelow(1024**3)
if new_id not in self.ids:
self.ids.add(new_id)
return new_id
def make_hint(password):
graph = Graph([], [])
idg = IdGen()
random = secrets.SystemRandom()
graph.nodes = [Node(letter, idg.generate_id()) for letter in password]
edgelst = list(zip(graph.nodes, graph.nodes[1:]))
for _ in range(len(password) * 3):
edgelst.append(tuple(random.sample(graph.nodes, 2))) # type: ignore
graph.edges = [
Edge(b, a) if random.random() % 2 else Edge(a, b) for a, b in edgelst
]
random.shuffle(graph.nodes)
random.shuffle(graph.edges)
return graph
def encrypt(num_words, secret):
password = make_password(num_words)
print(password + f" {len(password)}")
graph = make_hint(password)
with open("hint.txt", "w") as f:
f.write(
"\n".join([f"{n.id} [{n.letter}];" for n in graph.nodes])
+ "\n"
+ "\n".join([f"{e.a.id} -- {e.b.id};" for e in graph.edges])
)
with open("secret.txt", "wb") as f:
f.write(passphrase.encrypt(secret.encode(), password))
def main():
encrypt(int(args[0]), open("flag.txt").read())
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/TJCTF/2024/misc/golf_harder/golf.py | ctfs/TJCTF/2024/misc/golf_harder/golf.py | #!/usr/local/bin/python3.11
import regex # le duh
import os
import tomllib
from tabulate import tabulate
from importlib import import_module
from itertools import zip_longest as zp
def check_regex(pattern, matches, nonmatches):
try:
re = regex.compile(pattern, flags=regex.V1)
except:
print("nope")
return False
for text in matches:
if not re.search(text):
print(f"whoops, didn't match on {text}")
return False
for text in nonmatches:
if re.search(text):
print(f"whoops, matched on {text}")
return False
return True
def main():
for dir in sorted(os.listdir("challenges")):
tomlpath = os.sep.join(["challenges", dir, "info.toml"])
with open(tomlpath, "rb") as f:
info = tomllib.load(f)
matches = info["matches"]
nonmatches = info["nonmatches"]
length = info["length"]
print(info["description"])
print(
tabulate(
zp(matches, nonmatches),
[
"Match on all of these:",
"But none of these: ",
],
disable_numparse=True,
tablefmt="simple",
)
)
print(f"\nMaximum allowable length is {length}\n")
# include some test cases that may be inconvenient to display
# only some challenges have extra tests
# fear not, the intended pattern will remain the same
ext = import_module(f"challenges.{dir}.extensions")
matches.extend(ext.more_matches())
nonmatches.extend(ext.more_nonmatches())
pattern = input("> ")
if len(pattern) > length:
print(f"whoops, too long")
return
if not check_regex(pattern, matches, nonmatches):
return
print(open("flag.txt").read())
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/TJCTF/2024/misc/golf_hard/golf.py | ctfs/TJCTF/2024/misc/golf_hard/golf.py | #!/usr/local/bin/python3.11
import regex # le duh
import os
import tomllib
from tabulate import tabulate
from importlib import import_module
from itertools import zip_longest as zp
def check_regex(pattern, matches, nonmatches):
try:
re = regex.compile(pattern, flags=regex.V1)
except:
print("nope")
return False
for text in matches:
if not re.search(text):
print(f"whoops, didn't match on {text}")
return False
for text in nonmatches:
if re.search(text):
print(f"whoops, matched on {text}")
return False
return True
def main():
for dir in sorted(os.listdir("challenges")):
tomlpath = os.sep.join(["challenges", dir, "info.toml"])
with open(tomlpath, "rb") as f:
info = tomllib.load(f)
matches = info["matches"]
nonmatches = info["nonmatches"]
length = info["length"]
print(info["description"])
print(
tabulate(
zp(matches, nonmatches),
[
"Match on all of these:",
"But none of these: ",
],
disable_numparse=True,
tablefmt="simple",
)
)
print(f"\nMaximum allowable length is {length}\n")
# include some test cases that may be inconvenient to display
# only some challenges have extra tests
# fear not, the intended pattern will remain the same
ext = import_module(f"challenges.{dir}.extensions")
matches.extend(ext.more_matches())
nonmatches.extend(ext.more_nonmatches())
pattern = input("> ")
if len(pattern) > length:
print(f"whoops, too long")
return
if not check_regex(pattern, matches, nonmatches):
return
print(open("flag.txt").read())
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/TJCTF/2024/rev/pseudo_brainrot/encode.py | ctfs/TJCTF/2024/rev/pseudo_brainrot/encode.py | from PIL import Image
import random
random.seed(42)
lmao = random.randint(12345678,123456789)
random.seed(lmao)
img = Image.open("skibidi.png")
width, height = img.size
flag = open("flag.txt", "rb").read()
st = ""
for i in bytearray(flag):
tmp = bin(i)[2:]
while(len(tmp))<8:
tmp = "0"+tmp
st+=tmp
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
inds = [i for i in range(288)]
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
randnum = random.randint(1,500)
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
for i in range(random.randint(0,500), random.randint(500,1000)):
random.seed(i)
random.shuffle(inds)
if i==randnum:
break
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
new_flag = "".join([st[i] for i in inds])
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
troll = [random.randint(random.randint(-lmao,0),random.randint(0,lmao)) for _ in range(random.randint(1,5000))]
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
pic_inds = []
while len(pic_inds)!=288:
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
pic_inds.append(random.randint(0,width*height))
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
for i in range(288):
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
cur_ind = pic_inds[i]
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
row = cur_ind//height
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
col = cur_ind%width
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
colors = list(img.getpixel((row,col)))
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
change = random.randint(0,2)
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
colors[change] = (colors[change]& 0b11111110) | int(new_flag[i])
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
img.putpixel((row,col),tuple(colors))
troll = random.randint(random.randint(-lmao,0),random.randint(0,lmao))
if(i%randnum==0):
random.seed(random.randint(random.randint(-lmao,0),random.randint(0,lmao)))
img.save("skibidi_encoded.png")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/rev/cagnus_marlsen/endgamemaker.py | ctfs/TJCTF/2024/rev/cagnus_marlsen/endgamemaker.py | import tkinter
global root, myCanvas
root = tkinter.Tk()
myCanvas = tkinter.Canvas(root, bg="white", height=320, width=320)
turn = 0
grid = [0]*64
def selectWhite():
global turn
turn = 1
L3.config(text="Filling white")
def selectBlack():
global turn
turn = 0
L3.config(text="Filling black")
def verify():
b0 = int(''.join(str(i) for i in grid[0:8]), 2)
b1 = int(''.join(str(i) for i in grid[8:16]), 2)
b2 = int(''.join(str(i) for i in grid[16:24]), 2)
b3 = int(''.join(str(i) for i in grid[24:32]), 2)
b4 = int(''.join(str(i) for i in grid[32:40]), 2)
b5 = int(''.join(str(i) for i in grid[40:48]), 2)
b6 = int(''.join(str(i) for i in grid[48:56]), 2)
b7 = int(''.join(str(i) for i in grid[56:64]), 2)
b8 = int(''.join(str(i) for i in grid[0:64:8]), 2)
b9 = int(''.join(str(i) for i in grid[1:64:8]), 2)
b10 = int(''.join(str(i) for i in grid[2:64:8]), 2)
b11 = int(''.join(str(i) for i in grid[3:64:8]), 2)
b12 = int(''.join(str(i) for i in grid[4:64:8]), 2)
b13 = int(''.join(str(i) for i in grid[5:64:8]), 2)
b14 = int(''.join(str(i) for i in grid[6:64:8]), 2)
b15 = int(''.join(str(i) for i in grid[7:64:8]), 2)
b16 = int(''.join(str(i) for i in grid[0:64:9]), 2)
b17 = int(''.join(str(i) for i in grid[7:63:7]), 2)
touchesgrass = True
touchesgrass &= grid[1]+grid[10]+grid[62] == 2
touchesgrass &= (grid[15] > grid[23])
touchesgrass &= grid[9]+grid[10]+grid[14] == 2
touchesgrass &= grid[26] << 3 == grid[43]+grid[44]
touchesgrass &= (grid[32]+grid[33] < grid[1] + grid[62])
touchesgrass &= (sum(int(i)==int(j) for i,j in [*zip(format(b2,"#010b"),format(b4,"#010b"))][2:]))==3
touchesgrass &= bin(b6).count('1') == 5
touchesgrass &= grid[61] + grid[42] + grid[43] == grid[25] + grid[26] + grid[27]
touchesgrass &= grid[38]+grid[46]+grid[54]+grid[62]+grid[39]+grid[47]+grid[55]+grid[63] == 5
touchesgrass &= (grid[14]^1!=grid[15])
touchesgrass &= grid[57] + grid[59] + grid[60] == 3
touchesgrass &= grid[18] != grid[23]
touchesgrass &= grid[11]^grid[19]==1
touchesgrass &= grid[50]==grid[51]
touchesgrass &= grid[20]^grid[7]==1
touchesgrass &= (grid[63]>>1 != grid[63]<<1)
touchesgrass &= (sum(int(i)!=int(j) for i,j in [*zip(format(b9,"#010b"),format(b1,"#010b"))][2:]))==2
touchesgrass &= grid[57] + grid[58] + grid[59] == 2
touchesgrass &= grid[37]|grid[38] == grid[2]
touchesgrass &= grid[4]==grid[48]==grid[49]
touchesgrass &= grid[17] >=grid[30]
touchesgrass &= (grid[0] == grid[19])
touchesgrass &= grid[26] + grid[28] + grid[29] == grid[51] << 1
touchesgrass &= grid[3] + grid[5] + grid[55] == 1
touchesgrass &= (grid[30]==grid[34])
touchesgrass &= sum(grid[14:17]) > grid[56] + grid[30] + grid[47]
touchesgrass &= grid[7]!=grid[52]
touchesgrass &= (b16//4)%2==0
touchesgrass &= grid[8] == grid[9]
touchesgrass &= (sum(int(i)!=int(j) for i,j in [*zip(format(b16,"#010b"),format(b15,"#010b"))][2:]))==3
touchesgrass &= grid[6]^grid[56]==0
touchesgrass &= (sum(grid[30:36])==3)
touchesgrass &= grid[24]+grid[40] == grid[2]
touchesgrass &= ~(grid[27]^grid[22])==-1
touchesgrass &= grid[11]^grid[12]^grid[13]==grid[12]==grid[4]
touchesgrass &= grid[31] == grid[47]
touchesgrass &= grid[47]^grid[46] == 1
touchesgrass &= grid[10] * 2 == grid[25] * 2 + grid[41]
if(touchesgrass):
return 'tjctf{'+chr(b2)+chr(b9)+chr(b15)+chr(b16)+chr(b7)+chr(b4)+chr(b10)+chr(b12)+'}'
else:
return touchesgrass
def clicked(event):
row = max(0,min(320,event.y))//40
col = max(0,min(320,event.x))//40
grid[row*8+col] = turn
myCanvas.create_oval(40*col+5, 40*row+5, 40*(col+1)-5, 40*(row+1)-5, fill=("white" if turn==1 else "black"))
L2.config(text=f"{'Black wins' if grid.count(0)>grid.count(1) else 'White wins' if grid.count(0)<grid.count(1) else 'Tie' } {grid.count(0)}-{grid.count(1)}")
if((thefunny:=verify())):
print("yay you're a winner")
print(thefunny)
# exit()
def makeCanvas(root, myCanvas):
global L2, L3
L1 = tkinter.Label(root, text="Othello endgame generator")
L1.config(font=("Courier",20))
L1.pack()
btn = tkinter.Button(root, text="Fill black", height=25, bd='5',command=selectBlack)
btn.pack(side='left')
btn = tkinter.Button(root, text="Fill white", height=25, bd='5',command=selectWhite)
btn.pack(side='right')
for r in range(0,8):
for c in range(0,8):
myCanvas.create_rectangle(r*40, c*40, (r+1)*40, (c+1)*40, fill='green')
myCanvas.create_oval(40*r+5, 40*c+5, 40*(r+1)-5, 40*(c+1)-5, fill="black")
myCanvas.bind("<Button-1>", clicked)
myCanvas.pack()
L2= tkinter.Label(root, text="Black wins 64-0")
L2.config(font=("Courier",20))
L2.pack()
L3= tkinter.Label(root, text="Filling black")
L3.config(font=("Courier",20))
L3.pack()
makeCanvas(root, myCanvas)
root.mainloop()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/crypto/hulksmash/main.py | ctfs/TJCTF/2024/crypto/hulksmash/main.py | from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
key = open("key.txt", "rb").read().strip()
flag = pad(open("flag.txt", "rb").read(), 16)
cipher = AES.new(key, AES.MODE_ECB)
open("output.txt", "w+").write(cipher.encrypt(flag).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/crypto/weird_crypto/a.py | ctfs/TJCTF/2024/crypto/weird_crypto/a.py | from math import lcm
from Crypto.Util.number import bytes_to_long, getPrime
with open('flag.txt', 'rb') as f:
flag = bytes_to_long(f.read().strip())
oops = getPrime(20)
p1 = getPrime(512)
p2 = getPrime(512)
haha = (p1-1)*(p2-1)
crazy_number = pow(oops, -1, haha)
discord_mod = p1 * p2
hehe_secret = pow(flag, crazy_number, discord_mod)
print('admin =', discord_mod)
print('hehe_secret =', hehe_secret)
print('crazy number =', crazy_number)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/crypto/alkane/main.py | ctfs/TJCTF/2024/crypto/alkane/main.py | schedule = [[117, 30, 102, 114, 82, 127, 125, 85, 59, 122, 117, 107, 29, 103, 27, 120, 26, 26, 80, 7, 39, 74, 88, 47, 30, 62, 100, 113, 62, 13, 1, 50, 6, 1, 41, 91, 42, 79, 20, 70, 41, 62, 38, 114, 111, 113, 123, 93, 62, 117, 17, 75, 73, 46, 109, 112, 119, 2, 109, 95, 113, 88, 27, 63], [44, 1, 36, 119, 73, 7, 121, 62, 102, 84, 11, 122, 117, 111, 76, 33, 51, 13, 25, 59, 8, 59, 19, 76, 102, 125, 92, 86, 95, 7, 76, 94, 54, 68, 117, 15, 4, 111, 97, 22, 70, 92, 80, 47, 7, 57, 11, 75, 81, 48, 60, 22, 95, 69, 13, 20, 12, 118, 67, 17, 108, 101, 21, 32], [86, 111, 25, 49, 71, 68, 96, 53, 59, 127, 18, 0, 110, 61, 112, 51, 125, 86, 33, 122, 53, 69, 75, 12, 38, 100, 118, 29, 69, 110, 111, 73, 114, 71, 13, 123, 108, 120, 29, 108, 126, 98, 81, 39, 26, 105, 92, 0, 100, 50, 7, 48, 77, 113, 63, 77, 66, 87, 83, 44, 28, 119, 25, 85], [123, 58, 10, 30, 36, 35, 109, 107, 103, 74, 111, 35, 65, 122, 126, 3, 33, 26, 100, 51, 82, 73, 0, 33, 15, 52, 125, 67, 75, 74, 52, 33, 119, 105, 106, 17, 83, 58, 64, 94, 85, 63, 34, 103, 49, 6, 75, 51, 29, 119, 57, 127, 79, 81, 47, 1, 39, 20, 93, 47, 32, 67, 103, 35], [63, 97, 106, 108, 108, 78, 56, 70, 116, 60, 85, 113, 124, 16, 5, 27, 110, 25, 24, 88, 54, 48, 103, 24, 120, 101, 16, 90, 111, 67, 32, 30, 81, 73, 48, 92, 26, 75, 5, 75, 29, 36, 20, 18, 84, 100, 9, 118, 27, 13, 124, 93, 62, 33, 30, 26, 90, 44, 109, 86, 63, 72, 71, 110], [45, 16, 53, 2, 97, 88, 109, 62, 107, 31, 11, 38, 13, 112, 67, 31, 103, 65, 118, 87, 65, 120, 126, 41, 59, 38, 89, 67, 51, 117, 77, 61, 126, 109, 81, 6, 61, 57, 59, 85, 80, 36, 3, 68, 97, 30, 100, 23, 22, 14, 12, 20, 105, 36, 22, 93, 45, 54, 36, 93, 78, 72, 44, 71], [11, 66, 102, 110, 75, 83, 51, 85, 40, 60, 115, 9, 109, 88, 63, 106, 50, 60, 5, 47, 109, 112, 89, 34, 10, 9, 28, 64, 102, 65, 50, 69, 66, 106, 34, 114, 100, 46, 125, 70, 126, 74, 127, 40, 33, 32, 100, 117, 61, 125, 117, 105, 113, 56, 27, 49, 6, 107, 13, 42, 35, 33, 60, 108], [10, 53, 20, 85, 14, 2, 108, 75, 38, 24, 0, 32, 119, 49, 54, 46, 13, 2, 94, 79, 59, 87, 19, 30, 111, 70, 16, 67, 105, 1, 86, 8, 100, 21, 23, 14, 78, 95, 1, 47, 0, 45, 35, 42, 96, 96, 95, 117, 107, 104, 72, 114, 70, 125, 3, 84, 29, 55, 124, 47, 42, 69, 97, 72], [56, 89, 34, 102, 119, 20, 35, 108, 3, 38, 54, 34, 21, 93, 113, 95, 68, 72, 80, 68, 21, 50, 8, 18, 37, 81, 98, 126, 43, 105, 97, 28, 90, 114, 103, 2, 12, 48, 31, 19, 7, 44, 34, 24, 38, 49, 3, 104, 126, 2, 78, 70, 32, 91, 83, 47, 120, 80, 35, 28, 99, 71, 69, 100], [26, 43, 87, 126, 112, 57, 75, 95, 12, 69, 9, 10, 81, 111, 69, 49, 100, 53, 109, 46, 120, 113, 50, 92, 49, 116, 108, 64, 62, 39, 96, 56, 19, 92, 21, 114, 79, 19, 55, 121, 67, 55, 7, 20, 122, 68, 82, 53, 30, 111, 8, 3, 58, 64, 127, 56, 58, 65, 112, 83, 104, 36, 60, 0], [25, 9, 73, 124, 124, 116, 42, 107, 3, 30, 21, 110, 34, 59, 19, 32, 100, 56, 12, 54, 53, 123, 74, 38, 11, 42, 20, 9, 14, 22, 127, 26, 110, 24, 47, 124, 94, 36, 37, 18, 97, 26, 23, 67, 51, 15, 68, 59, 60, 126, 43, 72, 105, 35, 122, 34, 107, 107, 125, 6, 45, 68, 112, 37], [40, 11, 69, 55, 59, 3, 32, 121, 34, 87, 93, 14, 102, 49, 56, 41, 126, 101, 119, 87, 42, 70, 114, 89, 28, 125, 66, 63, 65, 58, 58, 31, 19, 22, 65, 77, 40, 15, 58, 18, 64, 20, 30, 55, 69, 14, 57, 121, 42, 109, 107, 23, 103, 29, 50, 93, 52, 98, 74, 107, 46, 115, 77, 73], [23, 23, 119, 106, 73, 16, 109, 53, 113, 101, 126, 80, 90, 8, 77, 111, 44, 86, 57, 54, 27, 18, 91, 119, 47, 126, 38, 73, 44, 11, 39, 65, 84, 126, 85, 9, 20, 29, 115, 68, 52, 49, 80, 34, 123, 5, 106, 125, 127, 100, 117, 108, 102, 76, 88, 77, 6, 8, 88, 84, 91, 39, 52, 12], [22, 50, 30, 27, 94, 124, 73, 92, 21, 17, 112, 19, 66, 123, 20, 104, 4, 106, 83, 21, 89, 125, 54, 118, 67, 74, 71, 27, 88, 63, 50, 60, 40, 126, 102, 114, 90, 42, 114, 29, 53, 93, 40, 67, 104, 96, 74, 114, 47, 42, 59, 64, 45, 98, 63, 5, 87, 119, 51, 11, 36, 114, 97, 65], [12, 60, 35, 27, 55, 15, 44, 88, 86, 39, 0, 59, 126, 118, 60, 126, 117, 32, 63, 123, 67, 89, 3, 9, 62, 107, 94, 46, 100, 97, 7, 5, 108, 76, 19, 115, 38, 49, 125, 7, 5, 122, 44, 90, 77, 110, 77, 65, 37, 71, 16, 82, 118, 83, 99, 65, 50, 125, 118, 110, 121, 41, 75, 127], [20, 47, 95, 54, 86, 122, 5, 101, 86, 120, 28, 100, 24, 3, 87, 19, 82, 33, 12, 35, 38, 43, 122, 92, 47, 2, 115, 64, 105, 98, 55, 50, 30, 75, 98, 14, 9, 124, 49, 106, 91, 96, 87, 70, 84, 1, 10, 10, 107, 0, 37, 52, 99, 105, 35, 2, 7, 75, 64, 36, 110, 0, 56, 96], [36, 32, 42, 4, 69, 86, 76, 76, 125, 35, 31, 50, 115, 41, 47, 90, 106, 106, 110, 77, 103, 32, 76, 54, 73, 114, 20, 108, 84, 120, 120, 82, 19, 22, 122, 31, 89, 82, 111, 59, 56, 55, 53, 48, 63, 92, 97, 76, 19, 103, 100, 15, 60, 96, 47, 17, 86, 80, 6, 97, 96, 116, 47, 117], [6, 55, 98, 66, 66, 108, 84, 88, 80, 19, 33, 7, 46, 61, 113, 87, 15, 112, 28, 86, 11, 82, 93, 13, 116, 79, 114, 10, 73, 51, 123, 40, 73, 125, 42, 56, 64, 24, 3, 42, 20, 92, 80, 46, 9, 74, 38, 22, 7, 63, 101, 31, 51, 97, 120, 71, 80, 99, 39, 51, 78, 95, 28, 107], [92, 68, 16, 117, 9, 70, 44, 15, 60, 78, 0, 56, 124, 4, 104, 74, 25, 14, 26, 120, 64, 32, 49, 7, 6, 108, 72, 26, 20, 95, 66, 17, 20, 38, 104, 76, 78, 96, 127, 55, 55, 11, 46, 9, 37, 6, 85, 79, 75, 37, 61, 16, 58, 6, 116, 110, 30, 103, 77, 6, 99, 33, 127, 37], [3, 61, 83, 4, 18, 57, 18, 66, 95, 43, 85, 48, 80, 31, 112, 65, 27, 45, 70, 4, 28, 37, 92, 8, 114, 16, 9, 46, 85, 56, 35, 112, 77, 30, 103, 23, 41, 98, 120, 78, 47, 12, 92, 72, 84, 94, 108, 60, 45, 57, 71, 110, 61, 20, 109, 83, 21, 14, 15, 6, 121, 97, 46, 120], [8, 28, 83, 70, 68, 63, 2, 29, 32, 38, 117, 40, 49, 105, 41, 59, 124, 59, 20, 67, 24, 38, 38, 64, 112, 5, 27, 87, 107, 26, 44, 42, 1, 51, 5, 25, 115, 4, 123, 45, 17, 120, 8, 102, 126, 118, 119, 116, 61, 90, 54, 108, 117, 83, 0, 44, 3, 9, 48, 41, 37, 100, 7, 124], [40, 68, 95, 74, 124, 57, 79, 36, 117, 114, 78, 19, 82, 103, 37, 82, 22, 43, 98, 78, 36, 41, 79, 108, 7, 112, 107, 111, 87, 59, 89, 15, 26, 55, 51, 66, 7, 49, 47, 67, 112, 36, 71, 60, 44, 105, 117, 47, 83, 16, 12, 75, 120, 110, 47, 72, 96, 77, 66, 46, 87, 104, 18, 84], [116, 74, 71, 23, 18, 61, 104, 7, 13, 101, 99, 72, 64, 73, 63, 122, 59, 43, 104, 61, 30, 64, 66, 45, 119, 65, 73, 86, 85, 79, 45, 26, 14, 6, 96, 20, 51, 23, 119, 41, 62, 41, 97, 51, 45, 39, 21, 67, 75, 0, 59, 72, 85, 26, 68, 113, 118, 54, 123, 53, 0, 72, 102, 8], [17, 116, 59, 79, 125, 118, 44, 49, 88, 13, 3, 73, 60, 121, 3, 30, 21, 70, 78, 96, 117, 102, 48, 4, 59, 57, 55, 114, 82, 83, 16, 74, 92, 41, 105, 123, 6, 67, 6, 66, 122, 81, 56, 36, 90, 115, 124, 92, 17, 42, 44, 57, 100, 120, 9, 89, 95, 117, 63, 16, 116, 11, 38, 0], [40, 37, 3, 79, 106, 53, 63, 108, 65, 105, 105, 108, 30, 81, 78, 20, 116, 107, 89, 39, 122, 121, 106, 48, 73, 91, 26, 22, 120, 82, 22, 37, 124, 98, 103, 41, 59, 119, 78, 33, 83, 28, 58, 58, 65, 66, 40, 26, 8, 95, 44, 12, 82, 14, 78, 57, 64, 119, 50, 127, 59, 86, 22, 56], [97, 42, 5, 9, 96, 89, 113, 1, 40, 38, 108, 23, 105, 12, 62, 19, 41, 8, 98, 18, 15, 6, 44, 4, 38, 81, 89, 28, 41, 8, 63, 108, 24, 30, 119, 19, 23, 19, 64, 23, 63, 24, 28, 27, 37, 63, 68, 11, 125, 61, 95, 32, 127, 2, 93, 44, 13, 55, 44, 102, 70, 8, 104, 98], [56, 75, 122, 105, 89, 16, 88, 53, 3, 39, 123, 91, 113, 10, 79, 22, 0, 89, 115, 67, 55, 59, 20, 27, 87, 72, 12, 125, 105, 24, 16, 103, 12, 115, 83, 12, 27, 20, 7, 121, 100, 27, 26, 127, 25, 113, 116, 121, 1, 109, 82, 50, 124, 69, 77, 110, 19, 68, 116, 59, 74, 65, 21, 93], [50, 15, 76, 16, 125, 0, 7, 92, 59, 15, 115, 39, 25, 9, 1, 70, 94, 103, 66, 48, 63, 39, 67, 102, 119, 84, 59, 46, 42, 111, 125, 8, 121, 38, 124, 68, 8, 46, 14, 34, 107, 61, 113, 24, 5, 42, 110, 114, 99, 6, 64, 35, 119, 74, 125, 42, 23, 106, 79, 9, 89, 73, 89, 90], [17, 92, 97, 105, 29, 57, 11, 51, 118, 101, 112, 108, 29, 35, 105, 37, 18, 93, 87, 13, 4, 88, 115, 120, 4, 119, 25, 84, 17, 24, 22, 13, 47, 100, 125, 56, 79, 75, 78, 69, 59, 59, 89, 108, 40, 120, 61, 91, 59, 32, 98, 49, 5, 32, 19, 1, 71, 6, 116, 107, 40, 36, 20, 113], [85, 66, 62, 87, 55, 72, 119, 16, 89, 66, 40, 38, 36, 52, 31, 77, 99, 59, 62, 50, 15, 1, 9, 58, 62, 79, 49, 26, 66, 72, 66, 78, 34, 62, 24, 51, 79, 125, 125, 49, 50, 23, 24, 5, 36, 67, 2, 27, 89, 84, 52, 109, 47, 111, 89, 37, 106, 79, 85, 59, 44, 58, 35, 45], [104, 119, 99, 116, 102, 127, 57, 33, 48, 120, 24, 103, 67, 44, 110, 120, 44, 1, 36, 14, 97, 5, 114, 30, 21, 89, 92, 54, 100, 19, 40, 91, 20, 108, 80, 0, 111, 56, 36, 1, 33, 30, 115, 101, 63, 117, 108, 8, 4, 63, 126, 3, 38, 82, 4, 23, 5, 126, 49, 97, 34, 37, 25, 122], [29, 2, 69, 120, 6, 104, 21, 32, 41, 102, 85, 126, 114, 116, 66, 101, 16, 53, 98, 18, 4, 39, 104, 115, 41, 72, 44, 10, 42, 83, 21, 103, 97, 99, 60, 101, 25, 83, 10, 42, 57, 118, 10, 76, 10, 103, 81, 10, 19, 110, 126, 51, 50, 18, 40, 35, 68, 3, 75, 97, 26, 89, 57, 59], [126, 31, 97, 26, 5, 59, 54, 41, 60, 111, 32, 57, 29, 86, 4, 21, 58, 115, 12, 107, 75, 7, 9, 59, 83, 120, 81, 78, 17, 16, 109, 63, 36, 76, 64, 12, 22, 39, 16, 126, 100, 117, 96, 21, 87, 38, 24, 11, 88, 71, 50, 115, 108, 110, 70, 115, 79, 62, 99, 103, 93, 90, 122, 84], [42, 1, 71, 1, 45, 112, 121, 38, 69, 78, 46, 39, 10, 90, 54, 46, 114, 21, 12, 56, 19, 126, 36, 81, 38, 6, 88, 93, 64, 62, 28, 28, 107, 120, 120, 45, 83, 33, 103, 0, 110, 4, 0, 110, 7, 37, 70, 110, 73, 42, 65, 95, 31, 72, 60, 8, 121, 69, 70, 69, 49, 16, 46, 110], [19, 106, 21, 2, 76, 67, 85, 98, 114, 28, 32, 74, 9, 50, 45, 35, 32, 36, 123, 108, 103, 95, 89, 108, 36, 120, 33, 103, 11, 43, 47, 31, 84, 101, 20, 43, 76, 110, 94, 123, 13, 54, 66, 31, 43, 35, 8, 13, 93, 28, 43, 28, 106, 11, 109, 61, 101, 104, 1, 74, 62, 59, 117, 95], [33, 16, 77, 39, 89, 56, 100, 100, 57, 91, 38, 120, 103, 63, 90, 118, 61, 85, 17, 98, 49, 51, 40, 111, 114, 30, 36, 74, 122, 39, 84, 78, 12, 111, 8, 69, 20, 73, 75, 48, 53, 106, 111, 20, 39, 93, 103, 10, 64, 85, 27, 93, 57, 19, 31, 94, 110, 25, 35, 71, 53, 69, 6, 96], [75, 93, 39, 15, 45, 19, 46, 100, 96, 28, 62, 5, 69, 70, 7, 30, 109, 55, 78, 114, 127, 17, 46, 55, 46, 38, 100, 57, 121, 5, 84, 2, 109, 109, 90, 19, 58, 41, 69, 12, 46, 82, 122, 46, 93, 1, 49, 12, 50, 101, 6, 76, 77, 84, 54, 120, 45, 11, 122, 12, 36, 108, 92, 39], [57, 85, 70, 29, 52, 83, 11, 24, 2, 74, 13, 57, 58, 23, 86, 52, 36, 47, 51, 64, 108, 72, 50, 87, 105, 7, 123, 24, 68, 17, 23, 6, 101, 18, 83, 45, 48, 73, 52, 55, 56, 0, 93, 66, 121, 83, 15, 123, 79, 20, 99, 19, 36, 118, 62, 41, 59, 15, 66, 89, 15, 73, 64, 101], [15, 114, 109, 5, 115, 68, 7, 6, 58, 40, 56, 40, 23, 86, 74, 95, 37, 105, 36, 4, 118, 75, 112, 0, 85, 70, 34, 54, 54, 65, 10, 38, 94, 79, 53, 52, 60, 117, 35, 40, 107, 6, 52, 65, 43, 10, 80, 11, 76, 44, 99, 102, 92, 8, 16, 124, 37, 105, 64, 68, 92, 34, 22, 41], [126, 70, 29, 36, 125, 61, 126, 51, 119, 36, 51, 99, 94, 7, 17, 7, 43, 86, 91, 4, 126, 97, 56, 1, 97, 5, 62, 107, 10, 110, 15, 125, 14, 23, 22, 10, 101, 16, 28, 89, 107, 94, 41, 73, 46, 3, 109, 25, 121, 45, 0, 85, 0, 67, 65, 11, 65, 28, 16, 9, 126, 118, 105, 37], [31, 92, 54, 53, 123, 93, 54, 7, 127, 44, 52, 88, 86, 117, 89, 67, 54, 60, 34, 14, 89, 65, 7, 43, 55, 122, 73, 51, 96, 59, 71, 12, 7, 125, 107, 1, 21, 85, 24, 68, 95, 28, 67, 104, 85, 127, 77, 48, 22, 65, 123, 63, 33, 13, 112, 95, 47, 69, 48, 108, 61, 13, 31, 45], [34, 127, 122, 98, 34, 110, 99, 99, 44, 1, 49, 107, 76, 121, 63, 70, 77, 11, 104, 45, 103, 89, 51, 56, 65, 87, 43, 110, 90, 38, 17, 88, 31, 3, 120, 117, 61, 55, 64, 55, 28, 67, 80, 52, 10, 124, 40, 88, 31, 44, 58, 87, 116, 93, 59, 33, 25, 95, 59, 39, 71, 50, 85, 127], [73, 90, 47, 109, 5, 11, 80, 85, 86, 111, 18, 100, 78, 13, 102, 95, 54, 75, 43, 115, 60, 32, 2, 14, 82, 68, 57, 14, 98, 17, 10, 100, 0, 113, 5, 122, 1, 80, 126, 97, 81, 83, 32, 12, 58, 18, 1, 98, 59, 123, 15, 26, 2, 91, 4, 23, 107, 50, 68, 45, 44, 39, 30, 58], [59, 20, 97, 51, 90, 69, 99, 50, 86, 115, 38, 32, 92, 66, 82, 2, 77, 63, 40, 34, 68, 49, 80, 56, 7, 48, 104, 31, 85, 11, 111, 100, 3, 107, 21, 77, 22, 45, 62, 7, 66, 53, 20, 28, 9, 85, 55, 71, 20, 16, 35, 56, 24, 24, 0, 123, 37, 77, 66, 114, 104, 89, 51, 27], [26, 63, 5, 100, 90, 108, 73, 105, 61, 14, 39, 16, 13, 100, 104, 89, 43, 35, 71, 16, 32, 79, 44, 59, 123, 92, 6, 0, 72, 74, 76, 62, 73, 97, 41, 98, 84, 2, 52, 37, 121, 94, 45, 116, 0, 32, 92, 66, 116, 23, 101, 93, 54, 73, 27, 75, 66, 56, 89, 60, 59, 31, 74, 38], [37, 47, 62, 31, 94, 82, 23, 39, 87, 72, 78, 109, 22, 116, 88, 52, 2, 121, 82, 50, 78, 64, 43, 71, 24, 46, 14, 0, 50, 17, 105, 89, 84, 80, 56, 7, 14, 4, 107, 33, 103, 21, 2, 67, 17, 82, 67, 112, 109, 103, 27, 10, 3, 40, 118, 39, 87, 127, 29, 24, 62, 7, 70, 15], [117, 38, 59, 57, 94, 12, 103, 104, 4, 8, 127, 29, 86, 47, 18, 43, 92, 110, 112, 79, 63, 58, 32, 109, 104, 20, 43, 106, 29, 93, 1, 125, 113, 118, 115, 84, 21, 50, 49, 99, 108, 70, 92, 98, 124, 67, 46, 10, 54, 124, 44, 48, 122, 2, 69, 35, 117, 92, 105, 98, 54, 40, 91, 71], [113, 104, 102, 56, 32, 119, 18, 124, 6, 107, 123, 27, 57, 39, 49, 91, 1, 30, 30, 113, 107, 91, 13, 69, 119, 88, 37, 48, 75, 87, 35, 96, 23, 109, 75, 77, 17, 47, 108, 19, 68, 41, 80, 46, 23, 122, 50, 101, 54, 114, 41, 27, 105, 117, 42, 19, 94, 5, 93, 13, 125, 96, 41, 122], [12, 58, 106, 67, 50, 32, 109, 77, 19, 114, 61, 98, 53, 127, 65, 89, 54, 103, 11, 64, 85, 95, 51, 2, 21, 36, 115, 72, 68, 96, 94, 116, 7, 98, 120, 98, 60, 13, 27, 37, 82, 117, 103, 74, 62, 60, 114, 82, 111, 19, 51, 110, 16, 80, 43, 22, 7, 50, 72, 53, 56, 71, 2, 7], [0, 103, 122, 47, 55, 4, 55, 108, 82, 17, 33, 15, 50, 58, 77, 68, 50, 72, 68, 85, 64, 6, 87, 77, 75, 10, 96, 18, 73, 111, 110, 60, 15, 80, 9, 77, 43, 24, 40, 104, 11, 64, 36, 87, 71, 5, 69, 35, 97, 32, 62, 25, 61, 37, 58, 118, 35, 66, 98, 81, 17, 121, 108, 31], [19, 62, 24, 102, 109, 16, 64, 91, 122, 110, 77, 35, 36, 13, 67, 0, 49, 110, 2, 36, 46, 77, 120, 95, 60, 36, 122, 93, 48, 108, 42, 8, 76, 118, 127, 121, 118, 107, 51, 86, 26, 27, 93, 43, 122, 54, 83, 52, 107, 76, 68, 49, 65, 81, 52, 30, 113, 52, 79, 118, 39, 5, 23, 107], [8, 98, 112, 82, 106, 102, 62, 52, 23, 50, 111, 108, 73, 50, 51, 41, 101, 64, 80, 32, 114, 69, 51, 50, 12, 29, 32, 40, 64, 52, 121, 108, 84, 124, 32, 56, 31, 48, 124, 103, 71, 83, 85, 124, 56, 19, 18, 117, 116, 17, 120, 1, 83, 71, 22, 119, 77, 46, 68, 30, 16, 108, 65, 113], [94, 24, 21, 69, 97, 30, 24, 112, 107, 42, 121, 46, 11, 39, 117, 47, 46, 7, 36, 81, 4, 25, 67, 93, 66, 77, 64, 111, 42, 116, 50, 41, 3, 47, 28, 109, 22, 48, 103, 76, 117, 102, 59, 7, 117, 50, 27, 124, 38, 39, 57, 12, 65, 67, 124, 104, 74, 53, 123, 78, 90, 66, 23, 127], [46, 88, 51, 45, 98, 33, 121, 1, 4, 19, 77, 21, 33, 49, 52, 62, 11, 78, 71, 63, 40, 122, 18, 118, 112, 56, 115, 69, 7, 10, 0, 102, 37, 57, 89, 75, 103, 115, 110, 78, 34, 9, 100, 88, 126, 114, 89, 75, 116, 37, 64, 71, 110, 85, 17, 116, 88, 35, 71, 44, 91, 15, 88, 97], [94, 82, 51, 90, 93, 11, 33, 52, 29, 34, 127, 52, 64, 28, 55, 25, 94, 33, 77, 44, 32, 0, 103, 70, 7, 79, 17, 26, 11, 22, 115, 37, 73, 61, 38, 107, 99, 55, 39, 11, 82, 66, 24, 94, 20, 41, 69, 72, 36, 34, 15, 25, 85, 108, 30, 119, 102, 65, 37, 76, 85, 55, 23, 85], [71, 39, 48, 77, 89, 98, 41, 61, 75, 20, 7, 24, 108, 101, 71, 59, 45, 60, 116, 58, 51, 46, 72, 89, 93, 7, 91, 53, 92, 4, 68, 32, 124, 18, 96, 2, 127, 14, 52, 119, 69, 30, 90, 92, 114, 126, 109, 69, 95, 102, 86, 76, 73, 97, 112, 93, 57, 41, 18, 70, 72, 122, 7, 9], [118, 80, 24, 94, 43, 90, 122, 9, 98, 63, 21, 21, 67, 116, 62, 93, 19, 75, 40, 54, 80, 3, 45, 43, 40, 12, 124, 7, 69, 1, 82, 100, 78, 120, 41, 42, 126, 26, 102, 26, 113, 65, 86, 56, 119, 49, 35, 7, 71, 118, 51, 7, 24, 13, 103, 51, 64, 90, 19, 91, 84, 110, 99, 62], [93, 23, 15, 31, 85, 90, 26, 8, 126, 75, 71, 46, 2, 33, 8, 116, 23, 70, 103, 99, 83, 11, 103, 6, 17, 126, 63, 0, 103, 99, 2, 115, 57, 82, 75, 25, 32, 105, 28, 89, 126, 12, 100, 82, 78, 42, 18, 114, 74, 33, 69, 105, 1, 86, 8, 43, 58, 98, 52, 26, 16, 62, 71, 122], [43, 36, 54, 95, 53, 70, 28, 83, 33, 9, 126, 78, 42, 37, 72, 93, 17, 110, 30, 43, 94, 7, 105, 67, 64, 19, 103, 53, 108, 118, 29, 101, 81, 77, 91, 51, 115, 55, 40, 91, 92, 100, 87, 29, 55, 33, 48, 86, 93, 61, 91, 76, 111, 33, 96, 118, 34, 6, 99, 15, 109, 6, 121, 70], [57, 11, 120, 110, 71, 38, 63, 87, 11, 90, 102, 84, 47, 48, 19, 14, 60, 47, 67, 71, 25, 105, 84, 107, 114, 20, 55, 6, 96, 40, 40, 122, 47, 107, 15, 27, 21, 4, 79, 14, 3, 18, 78, 78, 25, 42, 59, 97, 62, 7, 82, 121, 93, 33, 83, 36, 105, 64, 26, 0, 85, 78, 51, 37], [37, 35, 89, 44, 21, 93, 64, 57, 83, 89, 54, 89, 124, 57, 127, 12, 1, 72, 2, 28, 57, 63, 7, 65, 98, 3, 4, 64, 114, 36, 23, 20, 38, 73, 115, 1, 99, 28, 120, 23, 58, 30, 77, 125, 21, 41, 76, 107, 96, 59, 107, 39, 42, 52, 57, 34, 96, 8, 20, 120, 79, 51, 42, 104], [45, 83, 67, 111, 50, 13, 50, 99, 18, 116, 37, 12, 68, 39, 102, 79, 110, 93, 127, 3, 100, 97, 96, 19, 12, 66, 70, 6, 9, 111, 59, 6, 109, 114, 48, 107, 51, 95, 127, 108, 100, 20, 44, 71, 36, 9, 27, 96, 35, 65, 26, 0, 101, 13, 4, 34, 31, 51, 108, 11, 122, 42, 62, 111], [15, 13, 102, 7, 63, 8, 44, 101, 92, 62, 29, 112, 14, 3, 30, 36, 22, 116, 102, 10, 58, 34, 36, 109, 25, 76, 4, 51, 39, 116, 95, 66, 35, 80, 17, 100, 122, 120, 81, 119, 88, 65, 123, 127, 31, 19, 65, 22, 53, 3, 12, 67, 25, 12, 65, 3, 102, 107, 6, 9, 40, 110, 116, 1], [47, 34, 13, 106, 65, 0, 125, 57, 107, 10, 17, 73, 101, 96, 82, 4, 16, 15, 5, 7, 47, 40, 10, 13, 5, 35, 38, 5, 93, 69, 101, 43, 93, 105, 112, 82, 57, 31, 40, 65, 30, 16, 108, 84, 84, 14, 19, 69, 67, 68, 106, 6, 43, 22, 98, 118, 80, 89, 97, 37, 67, 108, 50, 6], [41, 52, 78, 23, 72, 55, 92, 101, 72, 114, 33, 49, 35, 48, 0, 85, 94, 69, 19, 58, 42, 45, 79, 114, 43, 36, 102, 4, 125, 63, 49, 83, 122, 42, 127, 59, 94, 81, 87, 35, 18, 24, 118, 7, 58, 55, 119, 18, 83, 121, 60, 107, 57, 96, 50, 122, 87, 92, 114, 98, 103, 107, 50, 51], [49, 2, 39, 68, 54, 61, 56, 98, 97, 44, 53, 102, 3, 17, 80, 51, 63, 62, 11, 61, 100, 80, 70, 53, 120, 68, 77, 27, 6, 63, 10, 6, 59, 85, 12, 79, 11, 78, 20, 68, 115, 48, 109, 121, 19, 79, 111, 22, 124, 70, 17, 43, 25, 95, 12, 127, 47, 35, 124, 108, 110, 95, 106, 104], [71, 52, 9, 22, 31, 4, 119, 106, 10, 44, 30, 16, 5, 123, 1, 30, 105, 68, 89, 66, 101, 101, 110, 116, 98, 68, 50, 96, 121, 3, 1, 1, 54, 73, 38, 45, 70, 117, 78, 120, 91, 102, 123, 40, 21, 113, 34, 8, 65, 94, 14, 5, 79, 100, 97, 106, 109, 13, 112, 99, 104, 79, 56, 84], [127, 117, 31, 36, 112, 9, 116, 89, 41, 117, 3, 70, 34, 13, 51, 117, 83, 34, 110, 78, 38, 74, 64, 103, 31, 68, 3, 45, 10, 121, 67, 66, 77, 108, 31, 1, 93, 0, 122, 30, 48, 63, 98, 85, 122, 92, 20, 70, 36, 61, 68, 99, 66, 61, 47, 102, 20, 26, 66, 72, 107, 99, 14, 45], [95, 82, 102, 19, 74, 114, 77, 39, 99, 90, 35, 2, 89, 102, 51, 3, 46, 56, 49, 87, 22, 61, 91, 74, 25, 1, 66, 123, 19, 11, 23, 49, 124, 76, 94, 41, 44, 103, 59, 38, 97, 117, 118, 43, 102, 61, 17, 83, 80, 9, 74, 45, 95, 21, 60, 33, 113, 22, 89, 68, 106, 110, 118, 60], [50, 75, 61, 11, 2, 46, 33, 19, 89, 50, 93, 45, 81, 23, 118, 106, 26, 80, 34, 111, 1, 72, 42, 121, 12, 46, 78, 1, 95, 2, 22, 57, 73, 93, 87, 22, 52, 18, 21, 4, 74, 61, 125, 109, 5, 21, 24, 28, 2, 2, 116, 126, 105, 96, 55, 104, 94, 73, 61, 45, 62, 18, 9, 121], [37, 96, 123, 4, 105, 106, 59, 85, 55, 86, 82, 5, 109, 77, 98, 108, 4, 26, 47, 111, 47, 43, 0, 125, 80, 31, 34, 86, 2, 0, 106, 108, 68, 117, 127, 115, 57, 40, 96, 23, 49, 30, 54, 87, 55, 29, 58, 7, 104, 42, 95, 67, 75, 125, 80, 13, 124, 48, 123, 112, 4, 48, 103, 45], [38, 89, 57, 83, 68, 12, 112, 113, 23, 27, 3, 17, 123, 63, 125, 79, 110, 110, 105, 12, 45, 104, 85, 108, 36, 42, 1, 65, 5, 90, 3, 30, 13, 122, 59, 69, 102, 90, 89, 13, 126, 62, 92, 114, 82, 85, 72, 83, 70, 113, 72, 88, 108, 85, 39, 25, 101, 56, 12, 71, 117, 82, 85, 18], [0, 14, 119, 54, 10, 86, 70, 10, 108, 99, 87, 93, 127, 121, 125, 2, 55, 116, 20, 25, 29, 1, 95, 22, 63, 123, 51, 123, 73, 45, 40, 86, 60, 44, 108, 94, 108, 6, 6, 101, 49, 102, 114, 34, 124, 19, 38, 10, 94, 73, 116, 16, 77, 99, 20, 112, 11, 85, 38, 30, 71, 28, 112, 23], [70, 104, 89, 34, 119, 125, 111, 127, 32, 85, 54, 112, 18, 8, 79, 119, 109, 61, 90, 62, 7, 117, 34, 12, 75, 57, 19, 115, 124, 124, 60, 109, 127, 89, 42, 9, 111, 102, 41, 23, 63, 9, 113, 67, 95, 62, 84, 124, 30, 82, 15, 113, 34, 17, 31, 39, 117, 94, 24, 92, 68, 54, 98, 24], [61, 55, 26, 109, 9, 115, 117, 2, 13, 113, 94, 58, 52, 37, 8, 12, 75, 120, 45, 13, 88, 86, 31, 15, 78, 40, 99, 118, 37, 22, 69, 37, 49, 26, 72, 47, 85, 70, 19, 52, 54, 86, 24, 22, 99, 0, 120, 0, 108, 52, 12, 88, 42, 24, 49, 113, 51, 15, 72, 59, 7, 102, 53, 12], [35, 71, 41, 71, 38, 49, 58, 32, 70, 75, 25, 24, 82, 34, 1, 7, 74, 124, 116, 103, 91, 22, 25, 106, 57, 33, 7, 13, 17, 12, 127, 0, 48, 111, 81, 118, 51, 106, 1, 124, 85, 50, 19, 49, 84, 105, 100, 120, 23, 49, 37, 48, 24, 80, 123, 10, 56, 39, 39, 68, 43, 57, 15, 62], [0, 74, 8, 26, 51, 105, 25, 56, 4, 88, 32, 75, 25, 83, 46, 61, 114, 23, 81, 73, 36, 77, 45, 51, 57, 59, 24, 95, 89, 49, 15, 48, 53, 94, 92, 83, 48, 93, 56, 46, 62, 21, 87, 37, 36, 29, 87, 35, 119, 14, 11, 109, 44, 26, 118, 34, 79, 17, 66, 46, 50, 64, 105, 81], [24, 78, 102, 81, 35, 21, 81, 86, 18, 74, 17, 3, 47, 51, 60, 53, 40, 26, 63, 10, 38, 69, 3, 7, 6, 98, 52, 73, 113, 21, 117, 77, 65, 107, 79, 37, 30, 79, 113, 99, 20, 1, 63, 10, 8, 42, 85, 44, 100, 114, 88, 119, 82, 7, 8, 82, 9, 116, 94, 29, 99, 103, 69, 102], [103, 95, 35, 87, 59, 49, 38, 47, 7, 89, 121, 16, 121, 105, 21, 125, 49, 125, 57, 32, 60, 63, 14, 25, 126, 105, 92, 20, 105, 82, 107, 59, 106, 3, 58, 24, 124, 49, 32, 97, 43, 28, 70, 81, 22, 109, 103, 35, 13, 25, 116, 112, 47, 62, 81, 84, 123, 84, 90, 111, 8, 119, 9, 94], [127, 104, 120, 96, 114, 17, 121, 24, 35, 100, 103, 72, 17, 23, 123, 47, 62, 97, 113, 48, 13, 11, 16, 57, 118, 18, 82, 22, 28, 76, 121, 52, 122, 50, 97, 23, 58, 18, 117, 122, 22, 0, 82, 85, 61, 117, 91, 14, 36, 112, 84, 60, 41, 126, 69, 64, 119, 97, 2, 20, 34, 120, 43, 84], [9, 117, 119, 8, 6, 92, 104, 113, 113, 35, 55, 25, 21, 85, 120, 4, 81, 57, 28, 118, 25, 89, 87, 86, 61, 3, 88, 126, 46, 81, 113, 9, 107, 46, 54, 20, 97, 99, 55, 92, 39, 60, 5, 71, 54, 82, 117, 52, 116, 11, 63, 90, 45, 37, 24, 47, 82, 7, 3, 119, 115, 84, 2, 21], [18, 43, 98, 1, 32, 69, 18, 36, 6, 116, 21, 12, 75, 37, 124, 26, 50, 87, 22, 1, 7, 28, 16, 85, 43, 104, 121, 55, 9, 29, 110, 76, 46, 2, 82, 93, 29, 72, 21, 100, 72, 118, 46, 108, 87, 69, 27, 50, 76, 58, 8, 2, 52, 65, 41, 52, 33, 6, 80, 26, 78, 57, 25, 35], [116, 9, 71, 44, 90, 42, 51, 78, 74, 84, 76, 105, 112, 38, 98, 108, 24, 53, 113, 51, 39, 101, 23, 87, 0, 20, 21, 98, 102, 68, 80, 31, 58, 78, 4, 86, 2, 115, 19, 55, 87, 109, 80, 110, 103, 121, 105, 118, 63, 71, 70, 31, 40, 82, 42, 50, 118, 36, 7, 69, 15, 18, 64, 117], [45, 25, 27, 113, 115, 66, 63, 44, 1, 2, 101, 76, 99, 35, 45, 42, 19, 32, 67, 38, 84, 103, 18, 24, 116, 10, 25, 3, 13, 33, 31, 79, 11, 98, 72, 102, 64, 49, 62, 6, 24, 68, 69, 70, 6, 115, 61, 80, 81, 46, 99, 86, 16, 122, 28, 113, 126, 4, 38, 36, 3, 10, 69, 84], [107, 79, 11, 118, 6, 18, 57, 50, 21, 6, 8, 7, 117, 42, 84, 114, 127, 126, 95, 94, 34, 119, 40, 83, 84, 48, 109, 126, 54, 75, 95, 92, 51, 76, 51, 31, 22, 93, 72, 11, 79, 45, 83, 85, 6, 116, 98, 61, 110, 84, 76, 118, 52, 42, 90, 24, 69, 112, 99, 85, 103, 69, 7, 17], [122, 79, 56, 17, 51, 92, 106, 60, 100, 63, 112, 99, 104, 125, 33, 52, 80, 33, 32, 18, 98, 48, 89, 63, 122, 46, 108, 54, 26, 39, 5, 18, 42, 48, 72, 88, 49, 108, 82, 97, 54, 40, 35, 99, 98, 83, 103, 32, 71, 56, 29, 105, 112, 52, 23, 100, 50, 23, 25, 10, 18, 65, 31, 107], [10, 2, 12, 91, 122, 28, 0, 119, 93, 31, 78, 24, 10, 65, 55, 108, 25, 116, 99, 74, 14, 12, 115, 70, 76, 39, 48, 84, 7, 93, 60, 55, 80, 14, 76, 7, 48, 14, 35, 29, 34, 40, 48, 15, 17, 123, 100, 38, 125, 77, 36, 94, 45, 81, 65, 55, 114, 40, 20, 84, 40, 21, 35, 23], [2, 73, 14, 117, 41, 1, 39, 12, 70, 14, 34, 15, 60, 101, 5, 35, 6, 84, 15, 101, 124, 13, 50, 42, 49, 82, 98, 39, 95, 21, 31, 46, 105, 17, 11, 48, 1, 36, 69, 62, 110, 85, 124, 105, 71, 3, 14, 98, 87, 35, 45, 40, 124, 19, 104, 72, 118, 95, 104, 116, 105, 96, 101, 37], [55, 86, 100, 66, 5, 10, 127, 110, 19, 100, 109, 51, 67, 111, 124, 18, 31, 61, 59, 78, 52, 98, 67, 54, 125, 85, 106, 119, 56, 50, 96, 96, 52, 94, 57, 116, 37, 14, 4, 74, 59, 114, 17, 80, 76, 68, 29, 126, 69, 82, 15, 4, 84, 45, 74, 72, 68, 103, 66, 78, 71, 39, 100, 55], [123, 126, 98, 59, 50, 108, 89, 50, 72, 98, 110, 124, 5, 60, 29, 2, 51, 58, 112, 72, 106, 1, 110, 120, 126, 32, 50, 80, 106, 117, 67, 37, 38, 98, 63, 107, 70, 126, 38, 105, 92, 94, 0, 114, 3, 63, 120, 0, 104, 37, 5, 99, 4, 115, 75, 101, 110, 4, 19, 96, 116, 49, 121, 101], [95, 0, 12, 93, 115, 80, 94, 25, 52, 111, 32, 22, 40, 13, 22, 45, 121, 118, 16, 121, 43, 64, 42, 119, 7, 43, 113, 59, 125, 0, 105, 82, 96, 103, 96, 86, 111, 82, 124, 87, 51, 119, 98, 101, 64, 71, 107, 4, 21, 54, 4, 55, 91, 113, 25, 43, 36, 49, 38, 51, 56, 16, 91, 126], [81, 7, 36, 99, 14, 100, 88, 10, 17, 58, 5, 66, 108, 73, 3, 49, 108, 40, 123, 36, 16, 39, 125, 63, 92, 68, 55, 89, 75, 109, 25, 95, 102, 118, 23, 104, 24, 45, 114, 108, 51, 67, 29, 53, 122, 92, 74, 41, 87, 5, 103, 61, 10, 94, 45, 87, 111, 72, 124, 11, 4, 109, 80, 92], [79, 102, 121, 98, 85, 11, 46, 89, 111, 92, 90, 66, 73, 17, 4, 113, 75, 82, 80, 4, 61, 8, 51, 96, 52, 121, 99, 89, 8, 24, 97, 115, 43, 86, 65, 112, 14, 110, 56, 64, 82, 123, 24, 32, 71, 73, 100, 79, 1, 107, 27, 103, 75, 91, 100, 41, 126, 29, 83, 24, 111, 24, 20, 4], [122, 67, 12, 75, 111, 9, 70, 101, 118, 104, 41, 37, 112, 66, 74, 99, 12, 78, 60, 88, 93, 111, 3, 75, 81, 62, 118, 77, 107, 67, 24, 19, 76, 82, 126, 115, 126, 75, 112, 8, 108, 114, 63, 79, 124, 103, 83, 81, 96, 72, 77, 127, 123, 125, 86, 107, 96, 93, 24, 3, 63, 98, 99, 26], [104, 82, 11, 15, 80, 88, 101, 35, 43, 65, 27, 34, 29, 89, 70, 81, 34, 31, 17, 34, 101, 76, 122, 45, 126, 71, 90, 48, 53, 118, 63, 22, 99, 0, 49, 53, 56, 58, 3, 26, 14, 29, 69, 72, 124, 75, 108, 123, 20, 116, 17, 77, 79, 31, 15, 53, 7, 126, 66, 44, 125, 69, 25, 94], [85, 29, 39, 98, 72, 80, 62, 122, 121, 119, 14, 57, 84, 62, 82, 19, 50, 16, 106, 106, 105, 113, 76, 24, 87, 32, 18, 54, 108, 43, 61, 101, 81, 112, 111, 0, 46, 7, 104, 37, 68, 12, 34, 88, 83, 87, 25, 33, 26, 80, 126, 123, 68, 6, 21, 123, 51, 30, 127, 85, 85, 27, 26, 17], [100, 22, 117, 84, 116, 118, 0, 105, 52, 82, 55, 120, 99, 91, 120, 45, 64, 10, 123, 90, 56, 36, 38, 111, 89, 63, 45, 113, 58, 61, 102, 26, 19, 2, 53, 57, 81, 52, 102, 1, 76, 56, 107, 5, 60, 54, 93, 71, 54, 44, 43, 51, 6, 92, 6, 47, 32, 95, 104, 47, 99, 7, 45, 120], [83, 20, 49, 60, 95, 120, 111, 19, 65, 81, 69, 2, 53, 99, 70, 23, 126, 41, 122, 81, 79, 2, 102, 72, 29, 42, 1, 38, 50, 65, 46, 47, 88, 27, 53, 109, 80, 33, 111, 106, 30, 94, 66, 6, 115, 105, 41, 33, 2, 96, 2, 17, 123, 32, 126, 75, 7, 83, 18, 79, 70, 16, 109, 82], [66, 90, 127, 71, 91, 121, 36, 23, 13, 79, 54, 56, 30, 48, 126, 61, 20, 89, 47, 27, 44, 40, 53, 44, 63, 87, 105, 85, 14, 38, 5, 7, 120, 88, 25, 95, 101, 35, 109, 105, 82, 79, 102, 120, 5, 24, 126, 60, 23, 44, 22, 63, 79, 84, 27, 115, 78, 119, 21, 96, 6, 60, 123, 4], [82, 113, 69, 89, 34, 46, 16, 6, 33, 32, 5, 91, 82, 79, 73, 94, 25, 36, 119, 19, 99, 123, 34, 27, 0, 22, 119, 65, 26, 125, 98, 31, 74, 5, 15, 68, 27, 67, 8, 35, 19, 62, 101, 101, 112, 101, 8, 90, 119, 70, 110, 89, 11, 96, 49, 85, 25, 19, 53, 37, 117, 126, 72, 8], [124, 6, 95, 72, 30, 74, 121, 56, 50, 4, 43, 54, 93, 89, 19, 48, 64, 125, 69, 117, 127, 64, 114, 15, 71, 104, 127, 67, 48, 40, 94, 124, 52, 63, 54, 88, 32, 44, 85, 108, 63, 42, 98, 36, 18, 107, 13, 45, 93, 59, 91, 122, 78, 42, 116, 84, 26, 16, 23, 91, 33, 110, 12, 127], [31, 110, 34, 53, 77, 93, 89, 38, 21, 28, 12, 57, 41, 76, 105, 17, 111, 9, 109, 96, 88, 49, 55, 101, 32, 26, 115, 102, 75, 104, 10, 121, 107, 116, 110, 92, 63, 21, 46, 78, 13, 127, 79, 29, 102, 0, 56, 71, 17, 96, 124, 43, 0, 2, 3, 28, 35, 23, 107, 82, 113, 20, 95, 54], [111, 71, 15, 62, 108, 34, 34, 67, 104, 28, 105, 54, 22, 10, 64, 10, 39, 23, 55, 25, 14, 40, 45, 97, 117, 89, 63, 54, 117, 118, 50, 27, 111, 84, 67, 81, 75, 10, 49, 45, 127, 76, 81, 76, 125, 6, 117, 76, 59, 37, 87, 8, 96, 110, 89, 99, 107, 81, 32, 60, 43, 105, 78, 97], [14, 123, 2, 37, 68, 79, 112, 26, 76, 73, 9, 116, 34, 33, 56, 86, 26, 80, 55, 34, 11, 23, 16, 71, 80, 50, 69, 60, 11, 114, 61, 47, 55, 13, 41, 21, 104, 39, 92, 123, 62, 91, 15, 8, 120, 39, 44, 89, 101, 67, 91, 120, 50, 4, 67, 86, 104, 74, 65, 1, 30, 35, 106, 8], [1, 102, 123, 22, 46, 103, 15, 48, 93, 8, 109, 58, 22, 119, 63, 32, 21, 50, 117, 22, 54, 33, 57, 42, 10, 23, 37, 10, 108, 9, 18, 86, 103, 6, 81, 46, 35, 70, 88, 124, 21, 4, 115, 53, 26, 95, 102, 43, 4, 36, 93, 99, 102, 23, 86, 62, 118, 74, 96, 10, 125, 114, 123, 53], [34, 69, 126, 8, 62, 96, 18, 40, 7, 78, 51, 99, 99, 56, 76, 87, 0, 108, 45, 107, 9, 112, 70, 0, 56, 31, 98, 59, 44, 36, 85, 38, 49, 47, 51, 14, 66, 54, 126, 84, 60, 45, 88, 0, 124, 16, 104, 59, 11, 103, 117, 103, 18, 81, 24, 78, 80, 47, 33, 72, 56, 88, 74, 14], [62, 122, 16, 72, 68, 70, 30, 18, 23, 59, 47, 102, 100, 106, 6, 10, 64, 20, 98, 119, 77, 119, 6, 109, 116, 0, 80, 112, 92, 66, 120, 69, 13, 53, 65, 112, 116, 105, 12, 21, 39, 74, 47, 73, 12, 44, 27, 38, 31, 103, 113, 37, 111, 78, 59, 41, 46, 67, 8, 51, 5, 32, 86, 14], [117, 57, 26, 121, 76, 29, 41, 50, 42, 87, 81, 27, 108, 35, 44, 88, 44, 99, 127, 35, 110, 19, 58, 97, 104, 122, 31, 27, 50, 11, 101, 52, 31, 66, 75, 13, 113, 51, 44, 33, 60, 48, 95, 41, 44, 59, 39, 83, 68, 33, 83, 72, 127, 52, 8, 54, 34, 87, 106, 111, 49, 17, 66, 16], [116, 46, 22, 124, 67, 48, 30, 91, 43, 80, 88, 112, 125, 1, 36, 15, 121, 53, 44, 94, 25, 125, 7, 80, 73, 122, 96, 24, 48, 106, 114, 1, 90, 36, 101, 117, 95, 40, 66, 110, 39, 87, 34, 57, 48, 24, 79, 74, 46, 10, 0, 41, 9, 40, 4, 90, 36, 98, 30, 79, 49, 94, 100, 105], [72, 13, 73, 3, 21, 127, 123, 43, 23, 20, 83, 100, 22, 116, 19, 18, 61, 22, 70, 100, 60, 19, 30, 121, 0, 82, 76, 29, 83, 46, 116, 35, 9, 53, 95, 15, 66, 15, 127, 114, 49, 65, 79, 30, 125, 41, 114, 9, 112, 73, 102, 5, 47, 34, 101, 38, 45, 71, 69, 107, 113, 8, 30, 89], [70, 54, 103, 89, 114, 32, 57, 92, 50, 80, 3, 49, 105, 87, 123, 62, 10, 41, 95, 1, 50, 47, 75, 85, 78, 29, 31, 22, 114, 66, 125, 93, 87, 99, 90, 1, 36, 57, 103, 107, 118, 10, 16, 85, 36, 53, 120, 42, 112, 85, 89, 66, 32, 79, 118, 84, 44, 2, 37, 119, 5, 104, 53, 11], [65, 42, 85, 25, 64, 28, 86, 120, 65, 1, 46, 43, 81, 34, 98, 18, 106, 83, 35, 109, 116, 59, 16, 17, 125, 36, 32, 31, 28, 37, 81, 26, 9, 91, 122, 34, 108, 23, 107, 55, 27, 107, 34, 75, 49, 59, 45, 90, 78, 102, 40, 62, 85, 115, 70, 28, 9, 83, 92, 118, 0, 114, 8, 58], [36, 31, 26, 62, 62, 93, 4, 120, 3, 33, 28, 48, 94, 62, 96, 123, 126, 78, 5, 76, 53, 117, 63, 34, 21, 10, 101, 84, 36, 66, 77, 80, 102, 16, 26, 30, 113, 62, 45, 61, 96, 64, 44, 34, 25, 47, 96, 49, 31, 57, 3, 24, 121, 114, 92, 124, 32, 100, 115, 126, 29, 1, 83, 87], [2, 4, 48, 97, 120, 66, 52, 18, 65, 108, 91, 13, 56, 88, 15, 60, 19, 37, 8, 47, 35, 64, 54, 67, 32, 72, 121, 83, 9, 3, 14, 49, 37, 84, 21, 91, 12, 4, 83, 37, 33, 88, 36, 67, 122, 59, 25, 60, 61, 86, 59, 42, 93, 8, 77, 99, 16, 62, 78, 16, 49, 58, 77, 116], [86, 0, 61, 49, 51, 49, 82, 52, 100, 15, 14, 34, 18, 42, 68, 93, 53, 101, 91, 16, 12, 89, 82, 33, 30, 95, 123, 50, 10, 23, 125, 13, 42, 108, 32, 91, 98, 28, 38, 88, 123, 119, 104, 119, 66, 119, 72, 80, 72, 14, 68, 86, 21, 47, 13, 15, 54, 45, 105, 31, 41, 72, 76, 76], [65, 48, 67, 51, 109, 90, 17, 82, 94, 5, 96, 22, 48, 68, 49, 14, 88, 127, 62, 72, 49, 99, 17, 94, 31, 86, 105, 70, 25, 71, 53, 125, 25, 62, 15, 30, 98, 6, 50, 65, 17, 61, 64, 123, 63, 75, 112, 69, 110, 121, 121, 118, 79, 90, 69, 88, 2, 127, 99, 34, 30, 110, 29, 63], [111, 93, 55, 38, 59, 108, 53, 108, 36, 118, 99, 89, 16, 60, 99, 73, 25, 11, 106, 70, 55, 3, 93, 105, 48, 108, 121, 122, 37, 73, 118, 112, 43, 48, 32, 61, 66, 103, 3, 3, 75, 76, 49, 96, 113, 42, 75, 68, 115, 56, 68, 47, 1, 123, 16, 104, 104, 53, 40, 31, 99, 113, 98, 5], [75, 110, 29, 118, 61, 101, 52, 44, 40, 27, 97, 85, 28, 111, 39, 104, 6, 23, 50, 29, 40, 119, 58, 115, 113, 74, 78, 95, 127, 109, 32, 11, 120, 74, 114, 18, 11, 63, 76, 52, 83, 64, 52, 91, 51, 9, 69, 11, 122, 83, 88, 9, 85, 8, 91, 49, 94, 125, 100, 115, 35, 93, 83, 66], [108, 127, 127, 62, 22, 68, 62, 111, 24, 23, 14, 69, 17, 15, 13, 53, 16, 52, 117, 119, 25, 68, 14, 34, 6, 49, 3, 17, 82, 13, 91, 90, 86, 100, 122, 122, 89, 54, 119, 62, 37, 125, 113, 35, 27, 44, 68, 93, 91, 15, 49, 104, 116, 76, 44, 6, 22, 18, 7, 61, 90, 125, 48, 5], [24, 67, 62, 14, 30, 71, 45, 81, 77, 91, 102, 25, 123, 12, 6, 94, 19, 5, 92, 18, 97, 59, 17, 46, 1, 36, 5, 106, 38, 1, 11, 14, 119, 1, 53, 58, 51, 85, 57, 28, 17, 98, 96, 87, 81, 75, 9, 77, 67, 106, 113, 10, 112, 87, 118, 0, 60, 121, 28, 17, 91, 50, 25, 16], [120, 19, 85, 109, 79, 112, 47, 71, 16, 56, 45, 29, 70, 84, 90, 0, 69, 98, 54, 16, 127, 28, 65, 66, 121, 82, 110, 110, 78, 81, 105, 7, 23, 37, 96, 58, 81, 46, 44, 50, 18, 51, 22, 37, 58, 62, 59, 32, 66, 82, 111, 121, 56, 73, 79, 102, 50, 77, 95, 91, 96, 117, 123, 33], [75, 92, 17, 111, 106, 48, 20, 61, 5, 114, 117, 72, 104, 67, 99, 101, 124, 48, 65, 125, 86, 70, 12, 63, 69, 16, 70, 90, 74, 31, 111, 38, 59, 73, 27, 91, 42, 84, 104, 47, 39, 42, 11, 89, 29, 71, 75, 83, 121, 110, 126, 35, 126, 49, 91, 74, 14, 93, 52, 100, 21, 107, 17, 12], [120, 95, 30, 17, 78, 23, 106, 126, 98, 19, 101, 100, 121, 54, 81, 9, 49, 97, 40, 94, 96, 47, 61, 38, 82, 112, 29, 111, 112, 80, 39, 55, 29, 116, 79, 40, 6, 84, 52, 17, 122, 22, 108, 12, 102, | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/crypto/accountleak/server.py | ctfs/TJCTF/2024/crypto/accountleak/server.py | #!/usr/local/bin/python3.10 -u
import time
from Crypto.Util.number import getPrime, getRandomInteger, getRandomNBitInteger
flag = open("flag.txt").read().strip()
p = getPrime(512)
q = getPrime(512)
sub = getRandomInteger(20)
# hehe u cant guess it since its random :P
my_password = getRandomNBitInteger(256)
n = p*q
c = pow(my_password, 65537, n)
dont_leak_this = (p-sub)*(q-sub)
def gamechat():
print("<Bobby> i have an uncrackable password maybe")
print(f"<Bobby> i'll give you the powerful numbers, {c} and {n}")
print("<Bobby> gl hacking into my account")
print("<Bobby> btw do you want to get my diamond stash")
resp = input("<You> ")
if (resp.strip() == "yea"):
print("<Bobby> i'll send coords")
print(f"<Bobby> {dont_leak_this}")
print("<Bobby> oop wasnt supposed to copypaste that")
print("<Bobby> you cant crack my account tho >:)")
tic = time.time()
resp = input("<You> ")
toc = time.time()
if (toc-tic >= 2.5):
print("<Bobby> you know I can reset my password faster than that lol")
elif (resp.strip() != str(my_password)):
print("<Bobby> lol nice try won't give password that easily")
else:
print("<Bobby> NANI?? Impossible?!?")
print("<Bobby> I might as wel give you the flag")
print(f"<Bobby> {flag}")
else:
print("<Bobby> bro what, who denies free diamonds?")
print("Bobby has left the game")
gamechat()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/crypto/iodomethane/main.py | ctfs/TJCTF/2024/crypto/iodomethane/main.py | import secrets
flag = open("flag.txt", "r").read().strip()
print(flag)
matrix = [[],[],[]]
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0192834756{}_!@#$%^&*()"
modulus = 15106021798142166691 #len(alphabet)
flag = [alphabet.index(a) for a in flag]
while len(flag) % 3 != 0:
flag.append(secrets.randbelow(modulus))
def det(matrix):
a = matrix[0][0]
b = matrix[0][1]
c = matrix[0][2]
d = matrix[1][0]
e = matrix[1][1]
f = matrix[1][2]
g = matrix[2][0]
h = matrix[2][1]
i = matrix[2][2]
return ((a * e * i - a * f * h) + (b * f * g - b * d * i) + (c * d * h - c * e * g)) % modulus
def randkey():
test = [[secrets.randbelow(modulus) for i in range(3)] for J in range(3)]
while (not det(test)):
test = [[secrets.randbelow(modulus) for i in range(3)] for J in range(3)]
return test
def dot(a,b):
return sum([a[i] * b[i] for i in range(len(a))]) % modulus
def mult(key, row):
return [dot(key[i], row) for i in range(len(key))]
rows = list(zip(flag[::3], flag[1::3], flag[2::3]))
key = randkey()
print(key, det(key), modulus)
enc = sum([mult(key, snip) for snip in rows], start = [])
print(enc)
open("out.txt", "w+").write(str(enc))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/crypto/lightweight_crypto_guard_system/encode.py | ctfs/TJCTF/2024/crypto/lightweight_crypto_guard_system/encode.py | #!/usr/local/bin/python3.10 -u
from Crypto.Util.number import *
import random
a = getRandomNBitInteger(30)
c = getRandomNBitInteger(15)
m = getPrime(32)
x0 = getRandomNBitInteger(30)
n = random.randint(2**8, 2**10)
flag = open("flag.txt").read().strip()
class Random():
global m, a, c
def __init__(self, x0):
self.x0 = x0
def random(self):
self.x0 = (a*self.x0+c) % m
return self.x0
encryptor = Random(x0)
assert m < 2**32
assert isPrime(m)
x = [ord(i) for i in flag]
with open("out.txt", "w") as wfile:
for ind in range(len(x)):
next = encryptor.random()
if ind < 6:
print(str(next))
wfile.write(str(next) + "\n")
for __ in range(n-1):
x[ind] ^= encryptor.random()
print(f"n = {n}")
print(" ".join([str(i) for i in x]))
wfile.write("n = " + str(n) + "\n")
wfile.write(" ".join([str(i) for i in x]) + "\n")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/crypto/tetraethyllead/server.py | ctfs/TJCTF/2024/crypto/tetraethyllead/server.py | #!/usr/local/bin/python3 -u
import secrets
import hashlib
from Crypto.Util.number import bytes_to_long, long_to_bytes
def rrot(word, i):
i %= 32
word = word & ((1 << 32) - 1)
return ((word >> i) | (word << (32 - i))) & ((1 << 32) - 1)
def lrot(word, i):
i %= 32
word = word & ((1 << 32) - 1)
return ((word << i) | (word >> (32 - i))) & ((1 << 32) - 1)
def get_sbox(word):
Sbox = [17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 31, 30, 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 49, 48, 51, 50, 53, 52, 55, 54, 57, 56, 59, 58, 61, 60, 63, 62, 33, 32, 35, 34, 37, 36, 39, 38, 41, 40, 43, 42, 45, 44, 47, 46, 81, 80, 83, 82, 85, 84, 87, 86, 89, 88, 91, 90, 93, 92, 95, 94, 65, 64, 67, 66, 69, 68, 71, 70, 73, 72, 75, 74, 77, 76, 79, 78, 113, 112, 115, 114, 117, 116, 119, 118, 121, 120, 123, 122, 125, 124, 127, 126, 97, 96, 99, 98, 101, 100, 103, 102, 105, 104, 107, 106, 109, 108, 111, 110, 145, 144, 147, 146, 149, 148, 151, 150, 153, 152, 155, 154, 157, 156, 159, 158, 129, 128, 131, 130, 133, 132, 135, 134, 137, 136, 139, 138, 141, 140, 143, 142, 177, 176, 179, 178, 181, 180, 183, 182, 185, 184, 187, 186, 189, 188, 191, 190, 161, 160, 163, 162, 165, 164, 167, 166, 169, 168, 171, 170, 173, 172, 175, 174, 209, 208, 211, 210, 213, 212, 215, 214, 217, 216, 219, 218, 221, 220, 223, 222, 193, 192, 195, 194, 197, 196, 199, 198, 201, 200, 203, 202, 205, 204, 207, 206, 241, 240, 243, 242, 245, 244, 247, 246, 249, 248, 251, 250, 253, 252, 255, 254, 225, 224, 227, 226, 229, 228, 231, 230, 233, 232, 235, 234, 237, 236, 239, 238]
words = [hashlib.sha256(word).digest()]
for i in range(7):
words.append(hashlib.sha256(words[i]).digest())
words = b"".join(words)
for idx in range(0, len(words), 2):
a = words[idx]
b = words[idx + 1]
old = Sbox[a]
Sbox[a] = Sbox[b]
Sbox[b] = old
return Sbox
def getbit(byte, i):
return (byte >> i) & 1
def setbit(v, i):
return v << i
def pbox(byte):
out = 0
pos_subs = [4, 1, 0, 6, 3, 5, 7, 2]
for pos_in in range(8):
out |= setbit(getbit(byte, pos_in), pos_subs[pos_in])
return out
def pad1(b):
while len(b) != 1:
b = b"\x00" + b
return b
def r1(i, box):
out = []
i = long_to_bytes(i)
for byte in i:
out.append(box[byte])
for idx in range(1, len(out)):
out[idx] ^= out[idx - 1]
return bytes_to_long(b"".join([pad1(long_to_bytes(l)) for l in out]))
def r2(i, box):
out = []
i = long_to_bytes(i)
for byte in i:
out.append(box[byte])
for idx in range(len(out) - 2, -1, -1):
out[idx] ^= out[idx + 1]
return bytes_to_long(b"".join([long_to_bytes(l) for l in out]))
def zpad(i):
while len(i) != 4:
i = b"\x00" + i
return i
def zpad8(i):
while len(i) < 8:
i = b"\x00" + i
return i
def r345(word, k, rnum):
word ^= rrot(word, -463 + 439 * rnum + -144 * rnum**2 + 20 * rnum**3 - rnum**4) ^ lrot(word, 63 + -43 * rnum + 12 * rnum**2 + -rnum**3)
word = (4124669716 + word * bytes_to_long(k))**3
word ^= word << 5
word ^= word << 5
word ^= rrot(word, -463 + 439 * rnum + -144 * rnum**2 + 20 * rnum**3 - rnum**4) ^ lrot(word, 63 + -43 * rnum + 12 * rnum**2 + -rnum**3)
return rrot(word, -504 + 418 * rnum -499 * rnum**2 + -511 * rnum**3 + 98 * rnum**4) & 0xffffffff
def swap(l, r):
return r, l
def encrypt(i, k, p = False):
k1 = k[:4]
k2 = k[4:]
assert len(k) == 8
assert len(i) == 8
m_sbox_1 = get_sbox(k1)
m_sbox_2 = get_sbox(k2)
l = bytes_to_long(i[:4])
r = bytes_to_long(i[4:])
if (p):
print("R0:",l, r)
#round 1
l ^= r2(r, m_sbox_2)
l, r = swap(l,r)
if (p):
print("R1:",l, r)
#round 2
l ^= r1(r, m_sbox_1)
l, r = swap(l,r)
if (p):
print("R2:",l, r)
#round 3
l ^= r345(r, k1, 3)
l, r = swap(l,r)
if (p):
print("R3:",l, r)
#round 4
l ^= r345(r, k2, 4)
l, r = swap(l,r)
if (p):
print("R4:",l, r)
#round 5
l ^= r345(r, long_to_bytes(bytes_to_long(k2) ^ bytes_to_long(k1)), 5)
l, r = swap(l,r)
if (p):
print("R5:",l, r)
#round 6
l ^= r345(r, k1, 6)
l, r = swap(l,r)
if (p):
print("R6:",l, r)
#round 7
l ^= r345(r, k2, 7)
r ^= l
if (p):
print("R7:",l, r)
return long_to_bytes((l << 32) | r)
# I want you to be happy
seecrit = b"\x00" + secrets.token_bytes(7)
for i in range(1024):
p = int(input("p: "))
print(bytes_to_long(encrypt(zpad8(long_to_bytes(p)), seecrit)))
guess = int(input("k: "))
if (guess == bytes_to_long(seecrit)):
print(open("flag.txt","r").read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/web/topplecontainer/app.py | ctfs/TJCTF/2024/web/topplecontainer/app.py | from flask import Flask, request, render_template, redirect, make_response, send_file
import uuid
import jwt
from functools import wraps
from datetime import datetime
import os
import json
MAX_SIZE_MB = 0.5
KID = "8c2088dfb37658e01b35aec916b3b085c3cafd5fbf03bbb2735d3f8e63defd6b"
app = Flask(__name__)
app.static_folder = "static"
app.config["MAX_CONTENT_LENGTH"] = int(MAX_SIZE_MB * 1024 * 1024)
flag = open("flag.txt", "r").read()
private_key = open("private.ec.key", "rb").read()
public_key = open("static/public_key.pem", "rb").read()
id_to_username = {}
user_files = {}
class File:
def __init__(self, file_id, name, mime):
self.file_id = file_id
self.name = name
self.mime = mime
self.time = datetime.strftime(datetime.now(), "%a %b %d %H:%M:%S")
def login_required():
def _login_required(f):
@wraps(f)
def __login_required(*args, **kwargs):
token = request.cookies.get("token")
if not token:
return redirect("/register")
user = verify_token(token)
if user is None:
return redirect("/register")
return f(*args, **kwargs, user=user)
return __login_required
return _login_required
def generate_token(user_id):
return jwt.encode(
{"id": user_id},
private_key,
algorithm="ES256",
headers={"kid": KID, "jku": "jwks.json"},
)
def verify_token(token):
try:
header = jwt.get_unverified_header(token)
jku = header["jku"]
with open(f"static/{jku}", "r") as f:
keys = json.load(f)["keys"]
kid = header["kid"]
for key in keys:
if key["kid"] == kid:
public_key = jwt.algorithms.ECAlgorithm.from_jwk(key)
payload = jwt.decode(token.encode(), public_key, algorithms=["ES256"])
return payload
except Exception:
pass
return None
@app.route("/static/<path:path>")
def static_file(filename):
return app.send_static_file(filename)
@app.route("/")
@login_required()
def index(user):
return render_template(
"index.html",
user_id=user["id"],
files=user_files.get(user["id"], {}).values(),
)
@app.route("/register", methods=["GET"])
def get_register():
return render_template("register.html")
@app.route("/register", methods=["POST"])
def post_register():
if "username" not in request.form:
return redirect("/register?err=No+username+provided")
username = request.form["username"]
user_id = str(uuid.uuid4())
user_files[user_id] = {}
id_to_username[user_id] = username
res = make_response(redirect("/"))
res.set_cookie("token", generate_token(user_id))
return res
@app.route("/upload", methods=["POST"])
@login_required()
def post_upload(user):
if "file" not in request.files:
return redirect(request.url + "?err=No+file+provided")
file = request.files["file"]
if file.filename == "":
return redirect("/?err=Attached+file+has+no+name")
if file:
uid = user["id"]
fid = str(uuid.uuid4())
folder = os.path.join(os.getcwd(), f"uploads/{uid}")
os.makedirs(folder, exist_ok=True)
file.save(os.path.join(folder, fid))
f = File(fid, file.filename, file.mimetype)
if uid not in user_files:
user_files[uid] = {}
user_files[uid][fid] = f
return redirect(f"/?success=Successfully+uploaded+file&path={uid}/{fid}")
@app.route("/view/<uuid:user_id>/<uuid:file_id>")
def view_file(user_id, file_id):
user_id, file_id = str(user_id), str(file_id)
try:
f = user_files[user_id][file_id]
return render_template(
"view_file.html",
username=id_to_username[user_id],
filename=f.name,
user_id=user_id,
file_id=file_id,
time=f.time,
)
except (FileNotFoundError, KeyError):
return "File not found", 404
return "Internal server error", 500
@app.route("/download/<uuid:user_id>/<uuid:file_id>")
def download_file(user_id, file_id):
user_id, file_id = str(user_id), str(file_id)
try:
f = user_files[user_id][file_id]
return send_file(
open(os.path.join(os.getcwd(), f"uploads/{user_id}/{file_id}"), "rb"),
mimetype=f.mime,
)
except (FileNotFoundError, KeyError):
return "File not found", 404
return "Internal server error", 500
@app.route("/flag")
@login_required()
def get_flag(user):
if user["id"] == "admin":
return flag
else:
return "admins only! shoo!"
if __name__ == "__main__":
app.run(port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2024/web/templater/app.py | ctfs/TJCTF/2024/web/templater/app.py | from flask import Flask, request, redirect
import re
app = Flask(__name__)
flag = open('flag.txt').read().strip()
template_keys = {
'flag': flag,
'title': 'my website',
'content': 'Hello, {{name}}!',
'name': 'player'
}
index_page = open('index.html').read()
@app.route('/')
def index_route():
return index_page
@app.route('/add', methods=['POST'])
def add_template_key():
key = request.form['key']
value = request.form['value']
template_keys[key] = value
return redirect('/?msg=Key+added!')
@app.route('/template', methods=['POST'])
def template_route():
s = request.form['template']
s = template(s)
if flag in s[0]:
return 'No flag for you!', 403
else:
return s
def template(s):
while True:
m = re.match(r'.*({{.+?}}).*', s, re.DOTALL)
if not m:
break
key = m.group(1)[2:-2]
if key not in template_keys:
return f'Key {key} not found!', 500
s = s.replace(m.group(1), str(template_keys[key]))
return s, 200
if __name__ == '__main__':
app.run(port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/pwn/painter/app.py | ctfs/TJCTF/2023/pwn/painter/app.py | from flask import Flask, render_template, redirect, request
from uuid import uuid4
app = Flask(__name__)
images = {}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/save', methods=['POST'])
def post_image():
img, name = request.json['img'], request.json['name']
id = uuid4()
images[id] = {
'img': img,
'name': name
}
return redirect('/img/' + str(id))
@app.route('/img/<uuid:id>')
def image_id(id):
if id not in images:
return redirect('/')
img = images[id]['img']
name = images[id]['name']
return render_template('index.html', px=img, name=name, saved=True)
if __name__ == '__main__':
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/rev/save-trees/server.py | ctfs/TJCTF/2023/rev/save-trees/server.py | #!/usr/local/bin/python3.10 -u
import ast
import sys
import select
from Crypto.Util.number import bytes_to_long
import hashlib
import random
def set_globals():
global edge_lst, cnt, threshold, vals, key, lvs
edge_lst = []
cnt, threshold = 0, 128
vals = [0 for _ in range(threshold*16)]
key = (bytes_to_long(bytes('save thr trees!!', 'utf-8'))
<< 16) + random.randint((1 << 15), (1 << 16))
lvs = []
with open('flag.txt', 'r') as f:
flag = f.readline()
def ear3mt3sdk(nd):
global cnt, threshold, edge_lst, lvs, key
if nd > threshold:
lvs.append(nd)
return
if nd > threshold // 2:
if random.randint(1, 4) == 1:
lvs.append(nd)
return
edge_lst.append((nd, cnt+1))
edge_lst.append((nd, cnt+2))
old_cnt = cnt
vals[cnt+1] = (vals[nd] >> 16) ^ key
vals[cnt+2] = (vals[nd] & ((1 << 16) - 1)) ^ key
cnt += 2
ear3mt3sdk(old_cnt+1)
ear3mt3sdk(old_cnt+2)
set_globals()
hsh = int('0x10000000' + str(hashlib.sha256(flag.encode('utf-8')).hexdigest()), 16)
vals[0] = hsh
ear3mt3sdk(0)
print('you have 5s to help treeelon musk save the trees!!')
print(edge_lst)
print([(nd, vals[nd]) for nd in lvs])
def input_with_timeout(prompt, timeout):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
return sys.stdin.readline().rstrip('\n')
raise Exception
try:
answer = input_with_timeout('', 5)
except:
print("\nyou let treeelon down :((")
exit(0)
try:
answer = ast.literal_eval(answer)
except:
print("treeelon is very upset")
exit(0)
if hsh == answer:
print('good job treeelon is proud of you <3<3')
print(flag)
else:
print("treeelon is upset")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/rev/scramble/chal.py | ctfs/TJCTF/2023/rev/scramble/chal.py | #first 3 lines are given
import random
seed = 1000
random.seed(seed)
#unscramble the rest
def recur(lst):
l2[i] = (l[i]*5+(l2[i]+n)*l[i])%l[i]
l2[i] += inp[i]
flag = ""
flag+=chr((l4[i]^l3[i]))
return flag
l.append(random.randint(6, 420))
l3[0] = l2[0]%mod
for i in range(1, n):
def decrypt(inp):
for i in range(n):
assert(len(l)==n)
return lst[0]
l = []
main()
def main():
l4 = [70, 123, 100, 53, 123, 58, 105, 109, 2, 108, 116, 21, 67, 69, 238, 47, 102, 110, 114, 84, 83, 68, 113, 72, 112, 54, 121, 104, 103, 41, 124]
l3[i] = (l2[i]^((l[i]&l3[i-1]+(l3[i-1]*l[i])%mod)//2))%mod
if(len(lst)==1):
assert(lst[0]>0)
for i in range(1, n):
for i in range(n):
return recur(lst[::2])/recur(lst[1::2])
print("flag is:", decrypt(inp))
l2[0] +=int(recur(l2[1:])*50)
l2 = [0]*n
flag_length = 31
mod = 256
print(l2)
n = len(inp)
inp = [1]*flag_length
l3 =[0]*n
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/rev/div3rev/chal.py | ctfs/TJCTF/2023/rev/div3rev/chal.py | def op1(b):
for i in range(len(b)):
b[i] += 8*(((b[i] % 10)*b[i]+75) & 1)
cur = 1
for j in range(420):
cur *= (b[i]+j) % 420
return b
def op2(b):
for i in range(len(b)):
for j in range(100):
b[i] = b[i] ^ 69
b[i] += 12
return b
def op3(b):
for i in range(len(b)):
b[i] = ((b[i] % 2) << 7)+(b[i]//2)
return b
def recur(b):
if len(b) == 1:
return b
assert len(b) % 3 == 0
a = len(b)
return op1(recur(b[0:a//3]))+op2(recur(b[a//3:2*a//3]))+op3(recur(b[2*a//3:]))
flag = open("flag.txt", "r").read()
flag = flag[:-1]
b = bytearray()
b.extend(map(ord, flag))
res = recur(b)
if res == b'\x8c\x86\xb1\x90\x86\xc9=\xbe\x9b\x80\x87\xca\x86\x8dKJ\xc4e?\xbc\xdbC\xbe!Y \xaf':
print("correct")
else:
print("oopsies")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/crypto/merky-hell/merky-hell.py | ctfs/TJCTF/2023/crypto/merky-hell/merky-hell.py | from math import gcd
import secrets
from Crypto.Util.number import *
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
n = 48
with open('flag.txt', 'rb') as f:
flag = f.read()
def randint(a, b):
return int(secrets.randbelow(int(b-a + 1)) + a)
def makeKey():
W = []
s = 0
for i in range(n):
curr = 0
if i != 0:
curr = randint((2**i - 1) * 2**n + 1, 2**(i+n))
else:
curr = randint(1, 2**n)
assert s < curr
s += curr
W.append(curr)
q = randint((1 << (2 * n + 1)) + 1, (1 << (2 * n + 2)) - 1)
r = randint(2, q - 2)
r //= gcd(r, q)
B = []
for w in W:
B.append((r * w) % q)
return B, (W, q, r)
def encrypt(public, m):
return sum([public[i] * ((m >> (n - i - 1)) & 1) for i in range(n)])
pub, _ = makeKey()
sup_sec_num = secrets.randbits(n)
msg = encrypt(pub, sup_sec_num)
iv = secrets.token_bytes(16)
key = pad(long_to_bytes(sup_sec_num), 16)
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
ct = cipher.encrypt(pad(flag, 16))
print('B =', pub)
print('msg =', msg)
print('iv =', iv.hex())
print('ct =', ct.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/crypto/iheartrsa/iheartrsa.py | ctfs/TJCTF/2023/crypto/iheartrsa/iheartrsa.py | #!/usr/local/bin/python3.10 -u
import ast
import sys
import select
from Crypto.Util import number
import hashlib
with open('flag.txt') as f:
flag = f.readline()
raw_bin = str(
bin(int('0x'+str(hashlib.sha256(flag.encode('utf-8')).hexdigest()), 16))[2:])
hsh = int('0b1' + '0' * (256 - len(raw_bin)) + raw_bin, 2)
p = number.getPrime(1024)
q = number.getPrime(1024)
n = p * q
e = 0
for i in range(0, 100):
if pow(hsh, i) >= n:
e = i
break
m = pow(hsh, e, n)
print(f'm: {m}')
print(f'n: {n}')
def input_with_timeout(prompt, timeout):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
return sys.stdin.readline().rstrip('\n')
raise Exception
try:
answer = input_with_timeout('', 20)
try:
answer = ast.literal_eval(answer)
if hsh == answer:
print('you love rsa so i <3 you :DD')
print(flag)
else:
print("im upset")
except Exception as e:
print("im very upset")
except Exception as e:
print("\nyou've let me down :(")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/crypto/keysmith/server.py | ctfs/TJCTF/2023/crypto/keysmith/server.py | #!/usr/local/bin/python3.10 -u
from Crypto.Util.number import getPrime
flag = open("flag.txt", "r").read()
po = getPrime(512)
qo = getPrime(512)
no = po * qo
eo = 65537
msg = 762408622718930247757588326597223097891551978575999925580833
s = pow(msg,eo,no)
print(msg,"\n",s)
try:
p = int(input("P:"))
q = int(input("Q:"))
e = int(input("E:"))
except:
print("Sorry! That's incorrect!")
exit(0)
n = p * q
d = pow(e, -1, (p-1)*(q-1))
enc = pow(msg, e, n)
dec = pow(s, d, n)
if enc == s and dec == msg:
print(flag)
else:
print("Not my keys :(")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/crypto/squishy/rsa.py | ctfs/TJCTF/2023/crypto/squishy/rsa.py | #!/usr/local/bin/python3.10 -u
import sys
import select
from Crypto.Util.number import bytes_to_long, getPrime
def input_with_timeout(prompt, timeout=10):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
return sys.stdin.buffer.readline().rstrip(b'\n')
raise Exception
def sign(a):
return pow(bytes_to_long(a), d, n)
def check(a, s):
return bytes_to_long(a) == pow(s, e, n)
e = 65537
users = {b"admin"}
p = getPrime(1000)
q = getPrime(1000)
n = p * q
d = pow(e, -1, (p - 1) * (q - 1))
print(n)
while True:
cmd = input("Cmd: ")
if cmd == "new":
name = input_with_timeout("Name: ")
if name not in users:
users.add(name)
print(name, sign(name))
else:
print("Name taken...")
elif cmd == "login":
name = input_with_timeout("Name: ")
sig = int(input_with_timeout("Sign: ").decode())
if check(name, sig) and name in users:
if name == b"admin":
print("Hey how'd that happen...")
print(open("flag.txt", "r").read())
else:
print("No admin, no flag")
else:
print("Invalid login.")
else:
print("Command not recognized...")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/crypto/drm-1/app.py | ctfs/TJCTF/2023/crypto/drm-1/app.py | from flask import Flask
import time
from Crypto.Hash import SHA256
app = Flask(__name__)
hash_key = open("hash_key", "rb").read()[:32]
flag = open("flag.txt", "r").read().strip()
@app.route('/buy/<user>')
def buy(user):
return "No"
@app.route('/song/<user>')
def song(user):
return open("user/"+user+".drmsong", "rb").read().hex()
@app.route('/unlock/<meta>/<hmac>')
def unlock(meta, hmac):
meta = bytes.fromhex(meta)
user = None
t = None
for word in meta.split(b","):
if b"user" in word:
user = str(word[word.index(b":")+1:])[2:-1]
if b"made" in word:
t = float(str(word[word.index(b":")+1:])[2:-1])
h = SHA256.new()
h.update(hash_key)
h.update(meta)
if h.hexdigest() == hmac:
if time.time() - t < 1000:
drm_key = open("user/"+user+".drmkey", "rb").read().hex()
drm_n = open("user/"+user+".drmnonce", "rb").read().hex()
return drm_key + " " + drm_n + " " + flag
else:
return "Expired :(... pay us again"
else:
return "Bad Hash"
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/TJCTF/2023/web/back-to-the-past/jwt.py | ctfs/TJCTF/2023/web/back-to-the-past/jwt.py | import base64
import json
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes, hmac
from cryptography.hazmat.primitives.asymmetric import padding
possible_algorithms = ["HS256", "RS256"]
def base64url_encode(value):
return base64.urlsafe_b64encode(value).rstrip(b"=")
def base64url_decode(value):
value += b"=" * (4 - len(value) % 4)
return base64.urlsafe_b64decode(value)
def encode(payload, secret, algorithm=None):
if not algorithm or algorithm not in possible_algorithms:
raise ValueError("invalid algorithm")
header = {"typ": "JWT", "alg": algorithm}
b64header = base64url_encode(json.dumps(header).encode())
b64payload = base64url_encode(json.dumps(payload).encode())
if algorithm == "HS256":
h = hmac.HMAC(secret, hashes.SHA256())
h.update(b".".join([b64header, b64payload]))
signature = h.finalize()
elif algorithm == "RS256":
priv = serialization.load_pem_private_key(
secret, password=None, backend=default_backend()
)
signature = priv.sign(
b".".join([b64header, b64payload]),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256(),
)
return b".".join([b64header, b64payload, base64url_encode(signature)])
def decode(token, secret, algorithms=None):
if not algorithms or any(alg not in possible_algorithms for alg in algorithms):
return None
if token.count(b".") != 2:
return None
header, payload, signature = token.split(b".")
if not header or not payload or not signature:
return None
try:
json_header = json.loads(base64url_decode(header))
json_payload = json.loads(base64url_decode(payload))
decoded_signature = base64url_decode(signature)
alg_to_use = json_header["alg"]
if alg_to_use == "HS256":
h = hmac.HMAC(secret, hashes.SHA256())
h.update(b".".join([header, payload]))
h.verify(decoded_signature)
elif alg_to_use == "RS256":
pub = serialization.load_pem_public_key(secret)
pub.verify(
decoded_signature,
b".".join([header, payload]),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA256(),
)
return json_payload
except Exception as e:
print(e)
return None
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/web/back-to-the-past/app.py | ctfs/TJCTF/2023/web/back-to-the-past/app.py | from flask import Flask, request, render_template, redirect, make_response
import uuid
import random
import jwt
import secrets
from functools import wraps
u2id = {}
u2year = {}
app = Flask(__name__)
app.static_folder = "static"
flag = open("flag.txt", "r").read()
def login_required():
def _login_required(f):
@wraps(f)
def __login_required(*args, **kwargs):
token = request.cookies.get("token")
if not token:
return redirect("/login")
user = verify_token(token)
if user is None:
return redirect("/login")
return f(*args, **kwargs, user=user)
return __login_required
return _login_required
private_key = open("private.key", "rb").read()
public_key = open("static/public_key.pem", "rb").read()
def generate_token(id, username, year):
return jwt.encode(
{"id": id, "username": username, "year": year}, private_key, algorithm="RS256"
)
def verify_token(token):
try:
return jwt.decode(token.encode(), public_key, algorithms=["HS256", "RS256"])
except:
return None
@app.route("/static/<path:path>")
def static_file(filename):
return app.send_static_file(filename)
@app.route("/")
@login_required()
def index(user):
return render_template("index.html", year=int(user["year"]))
@app.route("/retro")
@login_required()
def retro(user):
if int(user["year"]) > 1970:
return render_template("retro.html", flag="you aren't *retro* enough")
else:
return render_template("retro.html", flag=flag)
@app.route("/login", methods=["GET"])
def get_login():
return render_template("login.html")
@app.route("/login", methods=["POST"])
def post_login():
username = request.form["username"]
if not username:
return redirect("/login?msg=No+username+provided")
if username in u2id:
resp = make_response(redirect("/"))
resp.set_cookie(
"token", generate_token(u2id[username], username, u2year[username])
)
return resp
else:
return redirect("/login?msg=Username+not+found")
@app.route("/register", methods=["GET"])
def get_register():
return render_template("register.html")
@app.route("/register", methods=["POST"])
def post_register():
username = request.form["username"]
year = request.form["year"]
if username in u2id:
return redirect("/register?msg=So+unoriginal")
if not username:
return redirect("/register?msg=No+username+provided")
if not year.isnumeric() or not 1970 < int(year) < 2024:
return redirect("/register?msg=Invalid+year")
id = str(uuid.uuid4())
u2id[username] = id
u2year[username] = year
res = make_response(redirect("/"))
res.set_cookie("token", generate_token(id, username, year))
return res
if __name__ == "__main__":
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/web/swill-squill/app.py | ctfs/TJCTF/2023/web/swill-squill/app.py | import html
from flask import Flask, request, render_template, redirect, make_response
import sqlite3
import jwt
import secrets
from functools import wraps
app = Flask(__name__)
app.static_folder = 'static'
flag = open('flag.txt', 'r').read()
def login_required():
def _login_required(f):
@wraps(f)
def __login_required(*args, **kwargs):
token = request.cookies.get('token')
if not token:
return redirect('/login')
user = load_token(token)
if not user:
return redirect('/login')
return f(*args, **kwargs, user=user)
return __login_required
return _login_required
def create_db():
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute(
'CREATE TABLE users (name text, grade text)')
c.execute(
'CREATE TABLE notes (description text, owner text)')
c.execute('INSERT INTO users VALUES (?, ?)',
('admin', '12'))
c.execute('INSERT INTO notes VALUES (?, ?)',
('My English class is soooooo hard...', 'admin'))
c.execute('INSERT INTO notes VALUES (?, ?)',
('C- in Calculus LOL', 'admin'))
c.execute('INSERT INTO notes VALUES (?, ?)',
("Saved this flag for safekeeping: "+flag, 'admin'))
conn.commit()
return conn
secret = secrets.token_urlsafe(32)
conn = create_db()
def generate_token(username):
return jwt.encode({'name': username}, secret, algorithm='HS256')
def load_token(token):
try:
return jwt.decode(token, secret, algorithms=['HS256'])
except:
return None
@app.route('/', methods=['GET'])
def get_register():
return render_template('register.jinja')
@app.route('/register', methods=['POST'])
def post_register():
name = request.form['name']
grade = request.form['grade']
if name == 'admin':
return make_response(redirect('/'))
res = make_response(redirect('/api'))
res.set_cookie("jwt_auth", generate_token(name))
c = conn.cursor()
c.execute("SELECT * FROM users WHERE name == '"+name+"';")
if c.fetchall():
return res
c = conn.cursor()
c.execute('INSERT INTO users VALUES (?, ?)',
(name, grade))
conn.commit()
return res
@app.route('/api', methods=['GET'])
def api():
name = load_token(request.cookies.get('jwt_auth'))['name']
c = conn.cursor()
string = "SELECT description FROM notes WHERE owner == '" + name + "';"
c.execute(string)
return render_template("notes.jinja", notes=[html.escape(a[0]) for a in c.fetchall()])
@app.route('/api', methods=['POST'])
def post_api():
note = request.form['note']
name = load_token(request.cookies.get('jwt_auth'))['name']
c = conn.cursor()
c.execute('INSERT INTO notes VALUES (?, ?)', (note, name))
conn.commit()
res = make_response(redirect('/api'))
return res
if __name__ == '__main__':
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/web/outdated/app.py | ctfs/TJCTF/2023/web/outdated/app.py | from flask import Flask, request, render_template, redirect
from ast import parse
import re
import subprocess
import uuid
app = Flask(__name__)
app.static_folder = 'static'
app.config['UPLOAD_FOLDER'] = './uploads'
@app.route('/')
def index():
return render_template('home.html')
@app.route('/upload')
def upload():
return render_template('index.html')
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if 'file' not in request.files:
return redirect('/')
f = request.files['file']
fname = f"uploads/{uuid.uuid4()}.py"
f.save(fname)
code_to_test = re.sub(r'\\\s*\n\s*', '', open(fname).read().strip())
if not code_to_test:
return redirect('/')
tested = test_code(code_to_test)
if tested[0]:
res = ''
try:
ps = subprocess.run(['python', fname], timeout=5, capture_output=True, text=True)
res = ps.stdout
except:
res = 'code timout'
return render_template('submit.html', code=code_to_test.split('\n'), text=res.strip().split('\n'))
else:
return render_template('submit.html', code=code_to_test.split('\n'), text=[tested[1]])
@app.route('/static/<path:path>')
def static_file(filename):
return app.send_static_file(filename)
def test_for_non_ascii(code):
return any(not (0 < ord(c) < 127) for c in code)
def test_for_imports(code):
cleaned = clean_comments_and_strings(code)
return 'import ' in cleaned
def test_for_invalid(code):
if len(code) > 1000:
return True
try:
parse(code)
except:
return True
return False
blocked = ["__import__", "globals", "locals", "__builtins__", "dir", "eval", "exec",
"breakpoint", "callable", "classmethod", "compile", "staticmethod", "sys",
"__importlib__", "delattr", "getattr", "setattr", "hasattr", "sys", "open"]
blocked_regex = re.compile(fr'({"|".join(blocked)})(?![a-zA-Z0-9_])')
def test_for_disallowed(code):
code = clean_comments_and_strings(code)
return blocked_regex.search(code) is not None
def test_code(code):
if test_for_non_ascii(code):
return (False, 'found a non-ascii character')
elif test_for_invalid(code):
return (False, 'code too long or not parseable')
elif test_for_imports(code):
return (False, 'found an import')
elif test_for_disallowed(code):
return (False, 'found an invalid keyword')
return (True, '')
def clean_comments_and_strings(code):
code = re.sub(r'[rfb]*("""|\'\'\').*?\1', '', code,
flags=re.S)
lines, res = code.split('\n'), ''
for line in lines:
line = re.sub(r'[rfb]*("|\')(.*?(?!\\).)?\1',
'', line)
if '#' in line:
line = line.split('#')[0]
if not re.fullmatch(r'\s*', line):
res += line + '\n'
return res.strip()
if __name__ == '__main__':
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2023/web/pay-to-win/app.py | ctfs/TJCTF/2023/web/pay-to-win/app.py | from flask import Flask, request, render_template, redirect, make_response
from base64 import b64encode, b64decode
import hashlib
import random
import json
app = Flask(__name__)
users = {}
def hash(data):
return hashlib.sha256(bytes(data, 'utf-8')).hexdigest()
@app.route('/')
def index():
if request.cookies.get('data') is None or request.cookies.get('hash') is None:
return redirect('/login')
data = request.cookies.get('data')
decoded = b64decode(data)
data_hash = request.cookies.get('hash')
payload = json.loads(decoded)
if payload['username'] not in users:
resp = make_response(redirect('/login'))
resp.set_cookie('data', '', expires=0)
resp.set_cookie('hash', '', expires=0)
return resp
actual_hash = hash(data + users[payload['username']])
if data_hash != actual_hash:
return redirect('/login')
if payload['user_type'] == 'premium':
theme_name = request.args.get('theme') or 'static/premium.css'
return render_template('premium.jinja', theme_to_use=open(theme_name).read())
else:
return render_template('basic.jinja')
@app.route('/login', methods=['GET'])
def get_login():
return render_template('login.jinja')
@app.route('/login', methods=['POST'])
def post_login():
username = request.form['username']
if username not in users:
users[username] = hex(random.getrandbits(24))[2:]
resp = make_response(redirect('/'))
data = {
"username": username,
"user_type": "basic"
}
b64data = b64encode(json.dumps(data).encode())
data_hash = hash(b64data.decode() + users[username])
resp.set_cookie('data', b64data)
resp.set_cookie('hash', data_hash)
return resp
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/TJCTF/2025/misc/guess_my_number/chall.py | ctfs/TJCTF/2025/misc/guess_my_number/chall.py | #!/usr/local/bin/python
import random
flag = open("flag.txt").read().strip()
r = random.randint(1, 1000)
guessed = False
for i in range(10):
guess = int(input("Guess a number from 1 to 1000: "))
if guess > r:
print("Too high")
elif guess < r:
print("Too low")
else:
guessed = True
break
if guessed == True:
print(f"You won, the flag is {flag}")
else:
print(f"You lost, the number was {r}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/misc/golf_hardester/golf.py | ctfs/TJCTF/2025/misc/golf_hardester/golf.py | #!/usr/local/bin/python3.11
import regex # le duh
import os
import tomllib
from tabulate import tabulate
from importlib import import_module
from itertools import zip_longest as zp
def check_regex(pattern, matches, nonmatches):
try:
re = regex.compile(pattern, flags=regex.V1)
except:
print("nope")
return False
for text in matches:
if not re.search(text):
print(f"whoops, didn't match on {text}")
return False
for text in nonmatches:
if re.search(text):
print(f"whoops, matched on {text}")
return False
return True
def main():
for dir in sorted(os.listdir("challenges")):
tomlpath = os.sep.join(["challenges", dir, "info.toml"])
with open(tomlpath, "rb") as f:
info = tomllib.load(f)
matches = info["matches"]
nonmatches = info["nonmatches"]
length = info["length"]
print(info["description"])
print(
tabulate(
zp(matches, nonmatches),
[
"Match on all of these:",
"But none of these: ",
],
disable_numparse=True,
tablefmt="simple",
)
)
print(f"\nMaximum allowable length is {length}\n")
# include some test cases that may be inconvenient to display
# only some challenges have extra tests
# fear not, the intended pattern will remain the same
ext = import_module(f"challenges.{dir}.extensions")
matches.extend(ext.more_matches())
nonmatches.extend(ext.more_nonmatches())
pattern = input("> ")
if len(pattern) > length:
print(f"whoops, too long")
return
if not check_regex(pattern, matches, nonmatches):
return
print(open("flag.txt").read())
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/TJCTF/2025/misc/make_groups/calc.py | ctfs/TJCTF/2025/misc/make_groups/calc.py | f = [x.strip() for x in open("chall.txt").read().split('\n')]
n = int(f[0])
a = list(map(int, f[1].split()))
m = 998244353
def factorial(n):
if n==0: return 1
if n==1: return 1
return n * factorial(n-1)
def choose(n, r):
return (factorial(n) // (factorial(r) * factorial(n-r))) % m
ans = 1
for x in a:
ans *= choose(n, x)
ans %= m
print(f"tjctf{{{ans}}}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/rev/rubix_cube/rubixcube.py | ctfs/TJCTF/2025/rev/rubix_cube/rubixcube.py | import copy
import random
import numpy as np
class RubiksCube:
def __init__(self):
self.faces = {
'U': [['⬜'] * 3 for _ in range(3)],
'L': [['🟧'] * 3 for _ in range(3)],
'F': [['🟩'] * 3 for _ in range(3)],
'R': [['🟥'] * 3 for _ in range(3)],
'B': [['🟦'] * 3 for _ in range(3)],
'D': [['🟨'] * 3 for _ in range(3)]
}
def _rotate_face_clockwise(self, face_name):
face = self.faces[face_name]
new_face = [[None] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
new_face[i][j] = face[2-j][i]
self.faces[face_name] = new_face
def _rotate_face_counter_clockwise(self, face_name):
face = self.faces[face_name]
new_face = [[None] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
new_face[i][j] = face[j][2-i]
self.faces[face_name] = new_face
def display(self):
for i in range(3):
print(" " + " ".join(self.faces['U'][i]))
for i in range(3):
print(" ".join(self.faces['L'][i]) + " " +
" ".join(self.faces['F'][i]) + " " +
" ".join(self.faces['R'][i]) + " " +
" ".join(self.faces['B'][i]))
for i in range(3):
print(" " + " ".join(self.faces['D'][i]))
print("-" * 30)
def get_flat_cube_encoded(self):
return "".join([chr(ord(i) % 94 + 33) for i in str(list(np.array(self.faces).flatten())) if ord(i)>256])
def get_cube(self):
return self.faces
def U(self):
self._rotate_face_clockwise('U')
temp_row = copy.deepcopy(self.faces['F'][0])
self.faces['F'][0] = self.faces['R'][0]
self.faces['R'][0] = self.faces['B'][0]
self.faces['B'][0] = self.faces['L'][0]
self.faces['L'][0] = temp_row
def L(self):
self._rotate_face_clockwise('L')
temp_col = [self.faces['U'][i][0] for i in range(3)]
for i in range(3): self.faces['U'][i][0] = self.faces['B'][2-i][2]
for i in range(3): self.faces['B'][2-i][2] = self.faces['D'][i][0]
for i in range(3): self.faces['D'][i][0] = self.faces['F'][i][0]
for i in range(3): self.faces['F'][i][0] = temp_col[i]
def F(self):
self._rotate_face_clockwise('F')
temp_strip = copy.deepcopy(self.faces['U'][2])
for i in range(3): self.faces['U'][2][i] = self.faces['L'][2-i][2]
for i in range(3): self.faces['L'][i][2] = self.faces['D'][0][i]
for i in range(3): self.faces['D'][0][2-i] = self.faces['R'][i][0]
for i in range(3): self.faces['R'][i][0] = temp_strip[i]
def D_prime(self):
self._rotate_face_counter_clockwise('D')
temp_row = copy.deepcopy(self.faces['F'][2])
self.faces['F'][2] = self.faces['R'][2]
self.faces['R'][2] = self.faces['B'][2]
self.faces['B'][2] = self.faces['L'][2]
self.faces['L'][2] = temp_row
def R_prime(self):
self._rotate_face_counter_clockwise('R')
temp_col = [self.faces['U'][i][2] for i in range(3)]
for i in range(3): self.faces['U'][i][2] = self.faces['B'][2-i][0]
for i in range(3): self.faces['B'][2-i][0] = self.faces['D'][i][2]
for i in range(3): self.faces['D'][i][2] = self.faces['F'][i][2]
for i in range(3): self.faces['F'][i][2] = temp_col[i]
def B_prime(self):
self._rotate_face_counter_clockwise('B')
temp_strip = copy.deepcopy(self.faces['U'][0])
for i in range(3): self.faces['U'][0][i] = self.faces['L'][i][0]
for i in range(3): self.faces['L'][i][0] = self.faces['D'][2][2-i]
for i in range(3): self.faces['D'][2][i] = self.faces['R'][i][2]
for i in range(3): self.faces['R'][i][2] = temp_strip[2-i]
def apply_moves(self, moves_string):
moves = moves_string.split()
for move in moves:
if move == "U": self.U()
elif move == "D'": self.D_prime()
elif move == "L": self.L()
elif move == "R'": self.R_prime()
elif move == "F": self.F()
elif move == "B'": self.B_prime()
else:
print(f"Warning: Unknown move '{move}' ignored.")
moves = ["U", "L", "F", "B'", "D'", "R'"]
cube = RubiksCube()
#random scramble
for _ in range(1000):
cube.apply_moves(moves[random.randint(0,len(moves)-1)])
flag = "tjctf{" + cube.get_flat_cube_encoded() + "}"
first = cube.get_flat_cube_encoded()
with open("flag.txt", "w", encoding="utf-8") as f: f.write(flag)
random.seed(42)
for _ in range(20):
order = [random.randint(0,len(moves)-1) for _ in range(50)]
for i in range(len(order)):
cube.apply_moves(moves[order[i]])
with open("cube_scrambled.txt", "w", encoding="utf-8") as f: f.write(str(cube.get_cube()))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/rev/artifact/main.py | ctfs/TJCTF/2025/rev/artifact/main.py | import sys
from time import perf_counter
from math import pi,sqrt,asin,degrees,radians,sin
circ = 24901
diam = (circ / (2 * pi)) ** 2
rad = sqrt(diam)
spin = 1000
def add_spin(points,time):
ang = time / circ * 360
for i in range(len(points)):
nang = find_ang(points[i]) + ang
points[i] = sin(radians(nang)) * rad
def find_ang(point):
return degrees(asin(point / rad))
flag = b'tjctf{fake_flag}'
points = []
base = []
for i in flag:
base.append(sqrt(diam - (i * 31) ** 2))
st=perf_counter()
points.append(sqrt(diam - (i * 31) ** 2))
u = 0
while u < 1000000:
u += 1
en = perf_counter()
time = (en - st) * spin
print(int(time))
add_spin(points,time)
with open("points.txt",'w') as w:
w.write(str(points))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/crypto/seeds/main.py | ctfs/TJCTF/2025/crypto/seeds/main.py | #!/usr/local/bin/python3.10 -u
import time, sys, select
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
class RandomGenerator:
def __init__(self, seed = None, modulus = 2 ** 32, multiplier = 157, increment = 1):
if seed is None:
seed = time.asctime()
if type(seed) is int:
self.seed = seed
if type(seed) is str:
self.seed = int.from_bytes(seed.encode(), "big")
if type(seed) is bytes:
self.seed = int.from_bytes(seed, "big")
self.m = modulus
self.a = multiplier
self.c = increment
def randint(self, bits: int):
self.seed = (self.a * self.seed + self.c) % self.m
result = self.seed.to_bytes(4, "big")
while len(result) < bits // 8:
self.seed = (self.a * self.seed + self.c) % self.m
result += self.seed.to_bytes(4, "big")
return int.from_bytes(result, "big") % (2 ** bits)
def randbytes(self, len: int):
return self.randint(len * 8).to_bytes(len, "big")
def input_with_timeout(prompt, timeout=10):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
return sys.stdin.buffer.readline().rstrip(b'\n')
raise Exception
def main():
print("Welcome to the AES Oracle")
randgen = RandomGenerator()
cipher = AES.new(randgen.randbytes(32), AES.MODE_ECB)
flag = open("flag.txt", "rb").read()
ciphertext = cipher.encrypt(pad(flag, AES.block_size))
print(f'{ciphertext = }')
while True:
plaintext = input_with_timeout("What would you like to encrypt? (enter 'quit' to exit) ")
if plaintext == b"quit": break
cipher = AES.new(randgen.randbytes(32), AES.MODE_ECB)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
print(f"{ciphertext = }")
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/TJCTF/2025/crypto/theartofwar/main.py | ctfs/TJCTF/2025/crypto/theartofwar/main.py | from Crypto.Util.number import bytes_to_long, getPrime, long_to_bytes
import time
flag = open('flag.txt', 'rb').read()
m = bytes_to_long(flag)
e = getPrime(8)
print(f'e = {e}')
def generate_key():
p, q = getPrime(256), getPrime(256)
while (p - 1) % e == 0:
p = getPrime(256)
while (q - 1) % e == 0:
q = getPrime(256)
return p * q
for i in range(e):
n = generate_key()
c = pow(m, e, n)
print(f'n{i} = {n}')
print(f'c{i} = {c}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/crypto/pseudo_secure/server.py | ctfs/TJCTF/2025/crypto/pseudo_secure/server.py | #!/usr/local/bin/python
import random
import base64
import sys
import select
class User:
def __init__(self, username):
self.username = username
self.key = self.get_key()
self.message = None
def get_key(self):
username = self.username
num_bits = 8 * len(username)
rand = random.getrandbits(num_bits)
rand_bits = bin(rand)[2:].zfill(num_bits)
username_bits = ''.join([bin(ord(char))[2:].zfill(8) for char in username])
xor_bits = ''.join([str(int(rand_bits[i]) ^ int(username_bits[i])) for i in range(num_bits)])
xor_result = int(xor_bits, 2)
shifted = ((xor_result << 3) & (1 << (num_bits + 3)) - 1) ^ 0x5A
byte_data = shifted.to_bytes((shifted.bit_length() + 7) // 8, 'big')
key = base64.b64encode(byte_data).decode('utf-8')
return key
def set_message(self, message):
self.message = message
def input_with_timeout(prompt="", timeout=10):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
return sys.stdin.buffer.readline().rstrip(b'\n')
raise Exception
input = input_with_timeout
flag = open("flag.txt").read()
assert len(flag)%3 == 0
flag_part1 = flag[:len(flag)//3]
flag_part2 = flag[len(flag)//3:2*len(flag)//3]
flag_part3= flag[2*len(flag)//3:]
admin1 = User("Admin001")
admin2 = User("Admin002")
admin3 = User("Admin003")
admin1.set_message(flag_part1)
admin2.set_message(flag_part2)
admin3.set_message(flag_part3)
user_dict = {
"Admin001": admin1,
"Admin002": admin2,
"Admin003": admin3
}
print("Welcome!")
logged_in = None
user_count = 3
MAX_USERS = 200
while True:
if logged_in is None:
print("\n\n[1] Sign-In\n[2] Create Account\n[Q] Quit")
inp = input().decode('utf-8').strip().lower()
match inp:
case "1":
username = input("Enter your username: ").decode('utf-8')
if username in user_dict:
user = user_dict[username]
key = input("Enter your sign-in key: ").decode('utf-8')
if key == user.key:
logged_in = user
print(f"Logged in as {username}")
else:
print("Incorrect key. Please try again!")
else:
print("Username not found. Please try again or create an account.")
case "2":
if user_count >= MAX_USERS:
print("Max number of users reached. Cannot create new account.")
else:
username = input("Select username: ").decode('utf-8')
if username in user_dict:
print(f"Username '{username}' is already taken!")
else:
user_dict[username] = User(username)
user_count += 1
print(f"Account successfully created!\nYour sign-in key is: {user_dict[username].key}")
case "q":
sys.exit()
case _:
print("Invalid option. Please try again.")
else:
print(f"Welcome, {logged_in.username}!")
print("\n\n[1] View Message\n[2] Set Message\n[L] Logout")
inp = input().decode('utf-8').strip().lower()
match inp:
case "1":
print(f"Your message: {logged_in.message}")
case "2":
new_message = input("Enter your new message: ").decode('utf-8')
logged_in.set_message(new_message)
print("Message updated successfully.")
case "l":
print(f"Logged out from {logged_in.username}.")
logged_in = None
case _:
print("Invalid option. Please try again.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/crypto/bacon_bits/enc.py | ctfs/TJCTF/2025/crypto/bacon_bits/enc.py | with open('flag.txt') as f: flag = f.read().strip()
with open('text.txt') as t: text = t.read().strip()
baconian = {
'a': '00000', 'b': '00001',
'c': '00010', 'd': '00011',
'e': '00100', 'f': '00101',
'g': '00110', 'h': '00111',
'i': '01000', 'j': '01000',
'k': '01001', 'l': '01010',
'm': '01011', 'n': '01100',
'o': '01101', 'p': '01110',
'q': '01111', 'r': '10000',
's': '10001', 't': '10010',
'u': '10011', 'v': '10011',
'w': '10100', 'x': '10101',
'y': '10110', 'z': '10111'}
text = [*text]
ciphertext = ""
for i,l in enumerate(flag):
if not l.isalpha(): continue
change = baconian[l]
ciphertext += "".join([ts for ix, lt in enumerate(text[i*5:(i+1)*5]) if int(change[ix]) and (ts:=lt.upper()) or (ts:=lt.lower())]) #python lazy boolean evaluation + walrus operator
with open('out.txt', 'w') as e:
e.write(''.join([chr(ord(i)-13) for i in ciphertext])) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/crypto/double_trouble/enc.py | ctfs/TJCTF/2025/crypto/double_trouble/enc.py | from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import random
def gen():
myrandom = random.Random(42)
k1 = myrandom.randbytes(8)
choices = list(myrandom.randbytes(6))
k2 = b''
for _ in range(8):
k2 += bytes([choices[random.randint(0, 3)]])
return k1, k2
def enc(data, k1, k2, k3, k4):
key1 = k1+k2
cipher = AES.new(key1, mode=AES.MODE_ECB)
ct1 = cipher.encrypt(pad(data, 16))
key2 = k4+k3
cipher = AES.new(key2, mode=AES.MODE_ECB)
ct2 = cipher.encrypt(ct1)
return ct2
k1, k2 = gen()
k3, k4 = gen()
pt = b"example"
with open('flag.txt') as f:
flag = f.read().encode()
with open('out.txt', "w") as f:
f.write(enc(pt, k1, k2, k3, k4).hex())
f.write("\n")
f.write(enc(flag, k1, k2, k3, k4).hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/crypto/close_secrets/encrypt.py | ctfs/TJCTF/2025/crypto/close_secrets/encrypt.py | import random
from random import randint
import sys
from Crypto.Util import number
import hashlib
def encrypt_outer(plaintext_ords, key):
cipher = []
key_offset = key % 256
for val in plaintext_ords:
if not isinstance(val, int):
raise TypeError
cipher.append((val + key_offset) * key)
return cipher
def dynamic_xor_encrypt(plaintext_bytes, text_key_bytes):
encrypted_ords = []
key_length = len(text_key_bytes)
if not isinstance(plaintext_bytes, bytes):
raise TypeError
for i, byte_val in enumerate(plaintext_bytes[::-1]):
key_byte = text_key_bytes[i % key_length]
encrypted_ords.append(byte_val ^ key_byte)
return encrypted_ords
def generate_dh_key():
p = number.getPrime(1024)
g = number.getPrime(1024)
a = randint(p - 10, p)
b = randint(g - 10, g)
u = pow(g, a, p)
v = pow(g, b, p)
key = pow(v, a, p)
b_key = pow(u, b, p)
if key != b_key:
sys.exit(1)
return p, g, u, v, key
def generate_challenge_files(flag_file="flag.txt", params_out="params.txt", enc_flag_out="enc_flag"):
try:
with open(flag_file, "r") as f:
flag_plaintext = f.read().strip()
except FileNotFoundError:
sys.exit(1)
flag_bytes = flag_plaintext.encode('utf-8')
p, g, u, v, shared_key = generate_dh_key()
xor_key_str = hashlib.sha256(str(shared_key).encode()).hexdigest()
xor_key_bytes = xor_key_str.encode('utf-8')
intermediate_ords = dynamic_xor_encrypt(flag_bytes, xor_key_bytes)
final_cipher = encrypt_outer(intermediate_ords, shared_key)
with open(params_out, "w") as f:
f.write(f"p = {p}\n")
f.write(f"g = {g}\n")
f.write(f"u = {u}\n")
f.write(f"v = {v}\n")
with open(enc_flag_out, "w") as f:
f.write(str(final_cipher))
if __name__ == "__main__":
try:
with open("flag.txt", "x") as f:
f.write("tjctf{d3f4ult_fl4g_f0r_t3st1ng}")
except FileExistsError:
pass
generate_challenge_files()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/crypto/dotdotdotv2/encode.py | ctfs/TJCTF/2025/crypto/dotdotdotv2/encode.py | import numpy as np
import random
import sys
sys.stdin = open("flag.txt", "r")
sys.stdout = open("encoded.txt", "w")
n = 64
filler = "In cybersecurity, a CTF (Capture The Flag) challenge is a competitive, gamified event where participants, either individually or in teams, are tasked with finding and exploiting vulnerabilities in systems to capture hidden information known as flags. These flags are typically used to score points. CTFs test skills in areas like cryptography, web security, reverse engineering, and forensics, offering an exciting way to learn, practice, and showcase cybersecurity expertise. This flag is for you: "
flag = input()
flag = filler+flag
flag = "".join([bin(ord(i))[2:].zfill(8) for i in flag])
flag = flag + "0"*(n-len(flag)%n)
flag = np.array([list(map(int,list(flag[i:i+n]))) for i in range(0, len(flag), n)])
key = np.array([[random.randint(0,0xdeadbeef) for _ in range(n)] for _ in range(n)])
for i in flag: print(*list(np.dot(i,key))) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/crypto/alchemist_recipe/chall.py | ctfs/TJCTF/2025/crypto/alchemist_recipe/chall.py | import hashlib
SNEEZE_FORK = "AurumPotabileEtChymicumSecretum"
WUMBLE_BAG = 8
def glorbulate_sprockets_for_bamboozle(blorbo):
zing = {}
yarp = hashlib.sha256(blorbo.encode()).digest()
zing['flibber'] = list(yarp[:WUMBLE_BAG])
zing['twizzle'] = list(yarp[WUMBLE_BAG:WUMBLE_BAG+16])
glimbo = list(yarp[WUMBLE_BAG+16:])
snorb = list(range(256))
sploop = 0
for _ in range(256):
for z in glimbo:
wob = (sploop + z) % 256
snorb[sploop], snorb[wob] = snorb[wob], snorb[sploop]
sploop = (sploop + 1) % 256
zing['drizzle'] = snorb
return zing
def scrungle_crank(dingus, sprockets):
if len(dingus) != WUMBLE_BAG:
raise ValueError(f"Must be {WUMBLE_BAG} wumps for crankshaft.")
zonked = bytes([sprockets['drizzle'][x] for x in dingus])
quix = sprockets['twizzle']
splatted = bytes([zonked[i] ^ quix[i % len(quix)] for i in range(WUMBLE_BAG)])
wiggle = sprockets['flibber']
waggly = sorted([(wiggle[i], i) for i in range(WUMBLE_BAG)])
zort = [oof for _, oof in waggly]
plunk = [0] * WUMBLE_BAG
for y in range(WUMBLE_BAG):
x = zort[y]
plunk[y] = splatted[x]
return bytes(plunk)
def snizzle_bytegum(bubbles, jellybean):
fuzz = WUMBLE_BAG - (len(bubbles) % WUMBLE_BAG)
if fuzz == 0:
fuzz = WUMBLE_BAG
bubbles += bytes([fuzz] * fuzz)
glomp = b""
for b in range(0, len(bubbles), WUMBLE_BAG):
splinter = bubbles[b:b+WUMBLE_BAG]
zap = scrungle_crank(splinter, jellybean)
glomp += zap
return glomp
def main():
try:
with open("flag.txt", "rb") as f:
flag_content = f.read().strip()
except FileNotFoundError:
print("Error: flag.txt not found. Create it with the flag content.")
return
if not flag_content:
print("Error: flag.txt is empty.")
return
print(f"Original Recipe (for generation only): {flag_content.decode(errors='ignore')}")
jellybean = glorbulate_sprockets_for_bamboozle(SNEEZE_FORK)
encrypted_recipe = snizzle_bytegum(flag_content, jellybean)
with open("encrypted.txt", "w") as f_out:
f_out.write(encrypted_recipe.hex())
print(f"\nEncrypted recipe written to encrypted.txt:")
print(encrypted_recipe.hex())
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/TJCTF/2025/forensic/album_cover/enc.py | ctfs/TJCTF/2025/forensic/album_cover/enc.py | import wave
from PIL import Image
import numpy as np
#sample_rate = 44100
with wave.open('flag.wav', 'rb') as w:
frames = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16)
print(w.getnframes())
sampwidth = w.getsampwidth() # 2
nchannels = w.getnchannels() # 1
w.close()
arr = np.array(frames)
img = arr.reshape((441, 444))
img = (img + 32767) / 65535 * 255
img = img.astype(np.uint8)
img = Image.fromarray(img)
img = img.convert('L')
img.save('albumcover.png') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2025/web/double_nested/app.py | ctfs/TJCTF/2025/web/double_nested/app.py | from flask import Flask, render_template, request
import re
app = Flask(__name__)
@app.route('/')
def index():
i=request.args.get("i", "double-nested")
return render_template("index.html", i=sanitize(i))
def sanitize(input):
input = re.sub(r"^(.*?=){,3}", "", input)
forbidden = ["script", "http://", "&", "document", '"']
if any([i in input.lower() for i in forbidden]) or len([i for i in range(len(input)) if input[i:i+2].lower()=="on"])!=len([i for i in range(len(input)) if input[i:i+8].lower()=="location"]): return 'Forbidden!'
return input
@app.route('/gen')
def gen():
query = sanitize(request.args.get("query", ""))
return query, 200, {'Content-Type': 'application/javascript'}
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/TJCTF/2022/crypto/cipher-master/cipher.py | ctfs/TJCTF/2022/crypto/cipher-master/cipher.py | from typing import List
import os
sbox1 = [37, 9, 32, 12, 17, 41, 57, 47, 24, 36, 10, 44, 29, 18, 53, 38, 23, 14, 3, 61, 45, 62, 13, 46, 8, 5, 52, 63, 30, 4, 55, 28, 31, 11, 25, 0, 16, 35, 19, 22, 54, 59, 40, 42, 43, 6, 15, 33, 20, 50, 56, 26, 51, 34, 48, 49, 39, 27, 7, 1, 58, 60, 2, 21]
sbox2 = [4, 1, 51, 27, 53, 10, 57, 42, 55, 33, 41, 29, 52, 28, 24, 6, 40, 23, 36, 62, 3, 5, 16, 47, 63, 48, 58, 13, 31, 43, 39, 14, 56, 60, 2, 0, 26, 50, 38, 59, 21, 9, 35, 46, 8, 45, 54, 32, 18, 17, 15, 25, 11, 7, 12, 37, 20, 19, 34, 49, 44, 22, 30, 61]
sbox3 = [44, 13, 32, 0, 28, 61, 62, 48, 53, 60, 56, 18, 5, 36, 8, 41, 42, 22, 40, 35, 26, 59, 27, 54, 25, 37, 17, 31, 14, 34, 39, 47, 46, 15, 6, 2, 30, 63, 19, 52, 55, 11, 58, 50, 7, 38, 10, 43, 3, 9, 51, 4, 24, 57, 29, 23, 49, 16, 20, 21, 1, 33, 12, 45]
sbox4 = [57, 49, 51, 23, 53, 35, 39, 16, 17, 32, 50, 63, 8, 22, 19, 29, 59, 5, 31, 48, 44, 21, 28, 47, 25, 58, 61, 55, 20, 6, 62, 14, 54, 9, 37, 7, 11, 34, 43, 46, 3, 42, 2, 13, 10, 18, 45, 52, 0, 56, 41, 38, 26, 33, 30, 60, 36, 1, 12, 27, 40, 15, 24, 4]
pbox = [0, 12, 24, 30, 36, 42, 1, 6, 13, 18, 25, 37, 2, 7, 14, 26, 38, 43, 3, 15, 19, 27, 31, 39, 4, 8, 16, 20, 32, 44, 9, 17, 21, 28, 33, 45, 5, 10, 22, 34, 40, 46, 11, 23, 29, 35, 41, 47]
def invert_box(box):
inv = [0 for _ in range(len(box))]
for i in range(len(box)):
inv[box[i]] = i
return inv
def subs(values: List[int], sbox) -> List[int]:
return [sbox[value] for value in values]
def subs2(values: List[int], sboxes) -> List[int]:
return [(sboxes[i % len(sboxes)])[value] for i, value in enumerate(values)]
def permute(values: List[int], perm) -> List[int]:
r = 0
for v in values:
r = (r << 6) | v
p = 0
for i in range(48):
p |= ((r >> i) & 1) << perm[i]
result = []
for j in range(8):
result.append(p & 0x3F)
p >>= 6
return result[::-1]
def xor(a: List[int], b: List[int]) -> List[int]:
return [ai ^ bi for ai, bi in zip(a, b)]
def xorb(a : bytes, b : bytes) -> bytes:
return bytes(xor(a, b))
def rotate(value : List[int]) -> List[int]:
return value[2:] + value[:2]
def to_blocks(value: bytes) -> List[int]:
value = int.from_bytes(value, "big")
result = []
for _ in range(8):
result.append(value & 0x3F)
value >>= 6
return result[::-1]
def from_blocks(values: List[int]) -> bytes:
r = 0
for v in values:
r = (r << 6) | v
return r.to_bytes(6, "big")
def expand_key(key : bytes):
W0 = to_blocks(key[:6])
W1 = to_blocks(key[6:])
W2 = xor(W0, subs(rotate(W1), sbox1))
W3 = xor(W1, W2)
W4 = xor(W2, subs(rotate(W3), sbox1))
return W0, W1, W2, W3, W4
class LNRCipher:
"""LNR cipher object. Implements the LNR cipher, along with basic padding,
ECB, and CBC encryption modes.
LNR is a SPN-based block cipher that operates on 6-byte blocks. Despite the
low number of rounds, our empirical tests show that LNR has security levels
second-to-none, for more details see the whitepaper at: (TODO: Neil write
this!)
"""
def __init__(self, key):
"""Initializes a new cipher object with the given key.
Parameters
----------
key : bytes
The 96-bit (12 byte) key used for this cipher object
"""
round_keys = W0, W1, W2, W3, W4 = expand_key(key)
sboxes = [sbox1, sbox2, sbox3, sbox4]
self.enc_func = self._get_spn(sboxes=sboxes, pbox=pbox, round_keys=round_keys)
ipbox = invert_box(pbox)
self.dec_func = self._get_spn(sboxes=[invert_box(sbox) for sbox in sboxes], pbox=ipbox,
round_keys=(W4, permute(W3, ipbox), permute(W2, ipbox), permute(W1, ipbox), W0))
def pad_message(self, message_bytes):
"""Pads the given message (bytes) to a multiple of 6 bytes long."""
pad_value = 6 - (len(message_bytes) % 6)
return message_bytes + pad_value * chr(pad_value).encode()
def unpad_message(self, message_bytes):
"""Unpads the given message (bytes)."""
assert len(message_bytes) >= 6
pad_value = message_bytes[-1]
assert 1 <= pad_value <= 6
return message_bytes[:-pad_value]
def encrypt_cbc(self, message_bytes):
"""Encrypts using the CBC mode of operation. IV is chosen randomly and
prepended to the resulting ciphertext."""
ciphertext_blocks = [os.urandom(6)] # initialize with IV
for i in range(0, len(message_bytes), 6):
message_block = message_bytes[i:i+6]
ciphertext_blocks.append(self._encrypt_block(
xorb(message_block, ciphertext_blocks[-1])))
return b"".join(ciphertext_blocks)
def decrypt_cbc(self, ciphertext_bytes):
"""Decrypts using the CBC mode of operation. Expects IV to be prepended
to the ciphertext."""
message_blocks = []
for i in range(6, len(ciphertext_bytes), 6):
last_ciphertext_block = ciphertext_bytes[i-6:i]
ciphertext_block = ciphertext_bytes[i:i+6]
message_blocks.append(xorb(self._decrypt_block(ciphertext_block),
last_ciphertext_block))
return b"".join(message_blocks)
def encrypt_ecb(self, message_bytes):
"""Encrypts using the ECB mode of operation. This mode is not considered
secure, and is only included for testing purposes."""
return b''.join(self._encrypt_block(message_bytes[i:i+6]) for i in range(0,len(message_bytes),6))
def decrypt_ecb(self, ciphertext_bytes):
"""Decrypts using the ECB mode of operation. This mode is not considered
secure, and is only included for testing purposes."""
return b''.join(self._decrypt_block(ciphertext_bytes[i:i+6]) for i in range(0,len(ciphertext_bytes),6))
def _encrypt_block(self, byte_block):
assert len(byte_block) == 6
block = to_blocks(byte_block)
block = self.enc_func(block)
return from_blocks(block)
def _decrypt_block(self, byte_block):
assert len(byte_block) == 6
block = to_blocks(byte_block)
block = self.dec_func(block)
return from_blocks(block)
def _get_spn(self, sboxes, pbox, round_keys):
K0, K1, K2, K3, K4 = round_keys
def cipher(block):
state = block
state = xor(state, K0)
state = subs2(state, sboxes)
state = permute(state, pbox)
state = xor(state, K1)
state = subs2(state, sboxes)
state = permute(state, pbox)
state = xor(state, K2)
state = subs2(state, sboxes)
state = permute(state, pbox)
state = xor(state, K3)
state = subs2(state, sboxes)
state = xor(state, K4)
return state
return cipher
if __name__ == "__main__":
key = os.urandom(12)
cipher = LNRCipher(key)
def encrypt_file(filename):
with open(filename, "rb") as f:
file_bytes = f.read()
encrypted_file_bytes = cipher.encrypt_cbc(cipher.pad_message(file_bytes))
with open(filename + ".enc", "wb") as f:
f.write(encrypted_file_bytes)
encrypt_file("lol.bmp")
encrypt_file("flag.txt")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/crypto/mac-master/server.py | ctfs/TJCTF/2022/crypto/mac-master/server.py | #!/usr/local/bin/python -u
import hashlib
import os
with open("flag.txt") as f:
FLAG = f.read()
QUERIED = set()
KEY = os.urandom(16)
print("Introducing Neil-MAC (NMAC), the future of hash-based message")
print("authentication codes!")
print()
print("No longer susceptible to those pesky length extension attacks!")
print()
def nmac(message):
return hashlib.md5(message + KEY).hexdigest()
def query():
print("What message would you like to query a tag for?")
print("Enter message hex-encoded:")
hex_message = input()
message = bytes.fromhex(hex_message)
QUERIED.add(message)
print("Tag:", nmac(message))
def challenge():
print("Challenge time!")
print("Enter message hex-encoded:")
hex_message = input()
tag = input("Tag: ")
message = bytes.fromhex(hex_message)
if message in QUERIED:
print("You already queried that message!")
elif nmac(message) == tag:
print("Nice job!")
print("Flag:", FLAG)
while True:
print("What do you want to do?")
print("1) Query a message")
print("2) Challenge")
match input():
case "1":
query()
case "2":
challenge()
break
case _:
print("???")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/crypto/merkle-master/server.py | ctfs/TJCTF/2022/crypto/merkle-master/server.py | #!/usr/local/bin/python -u
import hashlib
import json
import random
import string
import sys
import os
with open("flag.txt") as f:
FLAG = f.read()
N = 50
M = 1000
print("It's time for a challenge!")
print()
print("I want you to produce a sorted Merkle tree commitment for me: however,")
print("there's a catch. This needs to be a QUANTUM commitment, meaning you can")
print("prove existence or non-existence of arbitrary elements.")
print()
print("I'll also be querying random indices to make sure your tree is sorted!")
print("Don't try to pull any tricks on me!")
print()
print("Use SHA-256 and make sure your tree is a perfect tree.")
print()
print("Here's the data I care about:")
print()
required_data = []
for _ in range(N):
data = "".join(random.choice(string.ascii_letters + string.digits) \
for _ in range(12))
required_data.append(data)
print(data)
random.shuffle(required_data)
print()
root = bytes.fromhex(input("Commitment hash: "))
depth = int(input("Tree depth: "))
seen_data_indices = {}
def prove_existence(root_hash, tree_depth, data):
print("Give the path from root to data, with sibling hashes:")
proof = json.loads(input())
if len(proof) != tree_depth:
print("Proof is wrong length!")
return False, -1
cur_hash = hashlib.sha256(data.encode()).digest()
for direction, sibling_hash in proof[::-1]:
sibling_hash = bytes.fromhex(sibling_hash)
if len(sibling_hash) != 32:
print("Sibling hash is wrong length!")
return False, -1
if direction == "L":
cur_hash = hashlib.sha256(cur_hash + sibling_hash).digest()
elif direction == "R":
cur_hash = hashlib.sha256(sibling_hash + cur_hash).digest()
else:
print("Direction isn't L or R!")
return False, -1
idx = 0
for direction, _ in proof:
if direction == "L":
idx = 2 * idx
else:
idx = 2 * idx + 1
seen_data_indices[idx] = data
if cur_hash != root_hash:
print("Resulting hash doesn't match commitment!")
return False, -1
return True, idx
def prove_nonexistence(root, tree_depth, data):
print("Prove the left element:")
left_data = input("Left data: ")
result, left_idx = prove_existence(root, tree_depth, left_data)
if not result:
print("Failed to prove left element!")
return False
print("Prove the right element:")
right_data = input("Right data: ")
result, right_idx = prove_existence(root, tree_depth, right_data)
if not result:
print("Failed to prove right element!")
return False
if right_idx != left_idx + 1:
print("Elements aren't adjacent!")
return False
if not (left_data < data < right_data):
print("Target data isn't lexicographically between left and right!")
return False
return True
# Check all the quantum commitments
for i, data in enumerate(required_data):
# Will you be asked to prove it exists? or that it doesn't?
# Nobody knows!
if os.urandom(1)[0] & 1 == 1:
print(f"Prove that '{data}' is part of your tree.")
result, _ = prove_existence(root, depth, data)
if not result:
sys.exit(1)
else:
print(f"Prove that '{data}' is NOT part of your tree.")
if not prove_nonexistence(root, depth, data):
sys.exit(1)
print("OK")
print()
# Choose some random query indices
query_indices = [random.randrange(0, 1 << depth) for _ in range(M)]
print("Show (and prove) the data at these indices:")
print(" ".join(map(str,query_indices)))
# Query some random indices
for query_index in query_indices:
print(f"What's at index {query_index}?")
data = input("Data: ")
result, idx = prove_existence(root, depth, data)
if idx != query_index:
print("Data isn't at the query index!")
result = False
if not result:
sys.exit(1)
print("OK")
print()
# Verify that the tree is actually sorted
queried_indices = sorted(seen_data_indices.keys())
queried_data = [seen_data_indices[idx] for idx in queried_indices]
if not all(queried_data[i+1] >= queried_data[i] for i in range(len(queried_data)-1)):
print("Data isn't sorted!")
sys.exit(1)
print("Wow, I guess you really are the Merkle Master.")
print(FLAG)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/crypto/factor-master/server.py | ctfs/TJCTF/2022/crypto/factor-master/server.py | #!/usr/local/bin/python -u
from Crypto.Util.number import getPrime, isPrime, getRandomInteger
import sys, random
print("Are you truly the master here?")
print()
print("We'll have to find out...")
print()
def fail():
print("You are not the master!")
sys.exit(1)
def challenge1():
p = getPrime(44)
q = getPrime(1024)
n = p * q
return [p, q], n
def challenge2():
p = getPrime(1024)
q = p + getRandomInteger(524)
if q % 2 == 0: q += 1
while not isPrime(q): q += 2
n = p * q
return [p, q], n
def challenge3():
small_primes = [n for n in range(2,10000) if isPrime(n)]
def gen_smooth(N):
r = 2
while True:
p = random.choice(small_primes)
if (r * p).bit_length() > N:
return r
r *= p
p = 1
while not isPrime(p):
p = gen_smooth(1024) + 1
q = getPrime(1024)
n = p * q
return [p, q], n
challenges = [challenge1, challenge2, challenge3]
responses = ["Okay, not bad.", "Nice job.", "Wow."]
for i, chal in enumerate(challenges):
print(f"CHALLENGE {i+1}")
factors, n = chal()
factors.sort()
print(f"n = {n}")
guess = input("factors = ? ")
if guess != " ".join(map(str,factors)):
fail()
print(responses[i])
print()
print("Here's your flag:")
with open("flag.txt") as f:
print(f.read().strip())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/crypto/copper-master/server.py | ctfs/TJCTF/2022/crypto/copper-master/server.py | #!/usr/local/bin/python -u
from Crypto.Util.number import *
import os
N = 768
e = 3
p = 1
while GCD(e, p - 1) != 1:
p = getPrime(N)
q = 1
while GCD(e, q - 1) != 1:
q = getPrime(N)
n = p * q
d = pow(e, -1, (p - 1) * (q - 1))
def pad(m, n_bits):
# otherwise recovering the message will be a bit of a pain...
assert m.bit_length() <= 500
return (0b111101010110111 << (n_bits - 15)) + \
((m ** 2) << 500) + \
m
def unpad(m_padded):
return m_padded & ((1 << 500) - 1)
def encrypt(m):
m = pad(m, 1400)
c = pow(m, e, n)
return c
def decrypt(c):
m = pow(c, d, n)
m = unpad(m)
return m
m = int.from_bytes(os.urandom(25), "big")
c = encrypt(m)
print(f"public key (n, e) = ({n}, {e})")
print(f"c = {c}")
guess = int(input("m = ? "))
if guess == m:
print("Wow! How did you do that?")
with open("flag.txt") as f:
print(f.read())
else:
print("Nice try, but I know my padding is secure!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/crypto/7sckp/server.py | ctfs/TJCTF/2022/crypto/7sckp/server.py | #!/usr/local/bin/python -u
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import random
from time import time
key = get_random_bytes(16)
flag = open('flag.txt', 'rb').read().strip()
def pad(msg, block_size):
random.seed(seed)
p = b''
pad_len = block_size - (len(msg) % block_size)
while len(p) < pad_len:
b = bytes([random.randrange(256)])
if b not in p:
p += b
return msg + p
def unpad(msg, block_size):
random.seed(seed)
p = b''
while len(p) < block_size:
b = bytes([random.randrange(256)])
if b not in p:
p += b
if p[0] not in msg:
raise ValueError('Bad padding')
pad_start = msg.rindex(p[0])
if msg[pad_start:] != p[:len(msg) - pad_start]:
raise ValueError('Bad padding')
return msg[:pad_start]
def encrypt(data):
cipher = AES.new(key, AES.MODE_CBC)
ct = cipher.encrypt(pad(data, AES.block_size))
return cipher.iv + ct
def decrypt(data):
iv = data[:AES.block_size]
ct = data[AES.block_size:]
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
return unpad(cipher.decrypt(ct), AES.block_size)
print('Hi! Welcome to our oracle, now extra secure because of our custom padding!')
seed = int(time() // 10)
print('We have this really cool secret here: ' + encrypt(flag).hex())
while True:
try:
decrypt(bytes.fromhex(input("Ciphertext: ")))
print("ok")
except:
print("error!!!")
print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/crypto/morph-master/server.py | ctfs/TJCTF/2022/crypto/morph-master/server.py | #!/usr/local/bin/python -u
from Crypto.Util.number import *
N = 1024
p = getPrime(N)
q = getPrime(N)
assert GCD(p * q, (p - 1) * (q - 1)) == 1
n = p * q
s = n ** 2
λ = (p - 1) * (q - 1) // GCD(p - 1, q - 1)
g = getRandomRange(1, s)
L = lambda x : (x - 1) // n
μ = pow(L(pow(g, λ, s)), -1, n)
def encrypt(m):
r = getRandomRange(1, n)
c = (pow(g, m, s) * pow(r, n, s)) % (s)
return c
def decrypt(c):
m = (L(pow(c, λ, s)) * μ) % n
return m
print(f"public key (n, g) = ({n}, ?)")
print(f"E(4) = {encrypt(4)}")
print()
print("Encrypt 'Please give me the flag' for your flag:")
c = int(input())
m = decrypt(c)
if long_to_bytes(m) == b"Please give me the flag":
print("Okay!")
with open("flag.txt") as f:
print(f.read())
else:
print("Hmm... not quite.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/web/fleecebook/db.py | ctfs/TJCTF/2022/web/fleecebook/db.py | import sqlite3
from uuid import uuid4
from pathlib import Path
path = Path(__file__).resolve().parent / 'database/db.sqlite3'
def conn_db():
conn = sqlite3.connect(path, check_same_thread=False)
cur = conn.cursor()
return (conn, cur)
if __name__ == '__main__':
path.parent.mkdir(parents=True, exist_ok=True)
conn, cur = conn_db()
cur.executescript('''
DROP TABLE IF EXISTS posts;
CREATE TABLE posts (id BLOB PRIMARY KEY, title TEXT, content TEXT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
''')
uuid = lambda: str(uuid4())
posts = [
(uuid(), 'fleece fleece fleece', 'i love wearing fleece-colored jackets. they are very soft.'),
(uuid(), 'e - the best letter in the alphabet', 'fleece is made of 50 percent e\'s. it also precedes the letter f, which is what fleece starts with. that is why it is the best letter in the alphabet.'),
(uuid(), 'fleece use', 'while sometimes used for fashion, fleece is often used for comfort. hug some fleece today and learn about your fleece aspirations.'),
(uuid(), 'mary fleece hoax', 'contrary to popular belief, mary did not befriend a lamb with fleece. either way, the lamb died.'),
(uuid(), 'cool facts about the word fleece', 'did you know that there are 120 distinct ways to re-arrange the letters in fleece? fleece also has no 6-letter anagrams.'),
]
cur.executemany('INSERT INTO posts (id, title, content) VALUES (?, ?, ?);', posts)
conn.commit()
conn.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TJCTF/2022/web/fleecebook/app.py | ctfs/TJCTF/2022/web/fleecebook/app.py | from flask import Flask, request, render_template, render_template_string, redirect, send_from_directory
from db import conn_db
from uuid import uuid4
conn, cur = conn_db()
app = Flask(__name__, static_url_path='')
@app.route('/static/<path:path>')
def static_file(path):
return send_from_directory('static', path)
@app.route('/')
def index():
posts = cur.execute('SELECT * FROM posts LIMIT 5;').fetchall()
return render_template('index.html', posts=posts)
@app.route('/post', methods=['GET', 'POST'])
def make_post():
if request.method == 'POST':
title = request.form.get('title')
content = request.form.get('content')
if title is None or content is None:
return 'missing title and/or content', 400
id = str(uuid4())
cur.execute(
'INSERT INTO posts (id, title, content) VALUES (?, ?, ?);', (id, title, content))
conn.commit()
return redirect('/post/' + id)
else:
return render_template('make_post.html')
@app.route('/post/<id>')
def view_post(id):
# view post
post = cur.execute('SELECT * FROM posts WHERE id = ?;', (id, )).fetchone()
if post is None:
return 'fleece could not be found </3', 404
post_format = """
{{ title }} - {{ timestamp }}
<br>
{{ content }}
"""
return render_template_string(post_format, title=post[1], content=post[2], timestamp=post[3])
@app.errorhandler(404)
def not_found(e):
return 'your fleece page (' + request.path + ') could not be found :notlikefleececry:'
@app.after_request
def add_security_headers(response):
response.headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self'; img-src 'self'; style-src 'self'; object-src 'none'; require-trusted-types-for 'script';"
return response
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SuSeC/2020/jailbreak/server.py | ctfs/SuSeC/2020/jailbreak/server.py | #!/usr/bin/env python
import ctypes
# We use external library because built-in functions are deleted
# and default 're' will no longer work.
# - https://github.com/kokke/tiny-regex-c
libregex = ctypes.CDLL('./libregex.so')
match = libregex.re_match
match.restype = ctypes.c_int
match.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
# code blacklist
blacklist = [
'eval', 'exec', 'setattr', 'system', 'open'
]
# built-in whitelist
whitelist = [
'print', 'eval', 'input', 'int', 'str', 'isinstance', 'setattr',
'__build_class__', 'Exception', 'KeyError'
]
def check_code(code):
if match(b'[-a-zA-Z0-9,\\.\\(\\)]+$', code.encode()) != 0:
raise Exception("Invalid code")
for word in blacklist:
if word in code:
raise Exception("'" + word + "' is banned")
def run_code():
code = input('code: ')
check_code(code)
eval(code)
if __name__ == '__main__':
for name in dir(__builtins__):
if name not in whitelist:
del __builtins__.__dict__[name]
try:
run_code()
print("[+] Done!")
except Exception as e:
print("[-] " + str(e))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hayyim/2022/pwn/AuViel/share/wrapper.py | ctfs/Hayyim/2022/pwn/AuViel/share/wrapper.py | #!/usr/bin/env python3
import os
import sys
import tempfile
def print(s):
sys.stdout.write(s)
sys.stdout.flush()
print("The number of files (max 3): ")
try:
count = int(sys.stdin.readline().strip())
except:
print("invalid input\n")
exit()
if count > 3 or count <= 0:
print("invalid input\n")
exit()
tmppath = [0, 0, 0]
cmd = "./clamscan"
for i in range(count):
print(f"file_size[{i}] (max 10000): ")
try:
file_size = int(sys.stdin.readline().strip())
except:
print("invalid input\n")
exit()
if file_size > 10000 or file_size <= 0:
print("invalid input\n")
exit()
print(f"file_data[{i}]: ")
file_data = sys.stdin.buffer.read(file_size)
fd, tmppath[i] = tempfile.mkstemp()
with open(tmppath[i], 'wb') as f:
f.write(file_data)
cmd += f' {tmppath[i]}'
os.system(cmd)
for i in range(count):
os.unlink(tmppath[i]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Bucket/2023/crypto/Search-2/search_2_generator.py | ctfs/Bucket/2023/crypto/Search-2/search_2_generator.py | from Crypto.Util.number import getPrime, inverse, bytes_to_long, isPrime
from string import ascii_letters, digits
from random import choice
p = bytes_to_long(open("flag.txt", "rb").read())
m = 0
while not isPrime(p):
p += 1
m += 1
q = getPrime(len(bin(p)))
n = p * q
e = 65537
l = (p-1)*(q-1)
d = inverse(e, l)
m = pow(m, e, n)
print(m)
print(n)
print(d) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Bucket/2023/crypto/Search-1/search_1_generator.py | ctfs/Bucket/2023/crypto/Search-1/search_1_generator.py | from Crypto.Util.number import getPrime, inverse, bytes_to_long
from string import ascii_letters, digits
from random import choice
m = open("flag.txt", "rb").read()
p = getPrime(128)
q = getPrime(128)
n = p * q
e = 65537
l = (p-1)*(q-1)
d = inverse(e, l)
m = pow(bytes_to_long(m), e, n)
print(m)
print(n)
leak = (p-2)*(q-2)
print(leak) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Bucket/2023/crypto/PsychologyRandom/encoder.py | ctfs/Bucket/2023/crypto/PsychologyRandom/encoder.py | seedKey = [] # set of 4 human random numbers between 0 and 255 inclusive
addKey = humanRandomGenerator(1,10) # human random number between 1 and 10 inclusive
for i in range(4):
seedKey.append(humanRandomGenerator(0, 255))
with open("flag.txt", "rb") as f:
flag = f.read()
encryptedFlag = bytearray()
for i in range(len(flag)):
encryptedFlag.append(flag[i] ^ seedKey[i%4])
seedKey[i%4] = (seedKey[i%4] + addKey) % 255
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Bucket/2023/crypto/Search-0/search_0_generator.py | ctfs/Bucket/2023/crypto/Search-0/search_0_generator.py | from Crypto.Util.number import getPrime, inverse, bytes_to_long
from string import ascii_letters, digits
from random import choice
m = open("flag.txt", "rb").read()
p = getPrime(128)
q = getPrime(128)
n = p * q
e = 65537
l = (p-1)*(q-1)
d = inverse(e, l)
m = pow(bytes_to_long(m), e, n)
print(m)
print(n)
p = "{0:b}".format(p)
for i in range(0,108):
print(p[i], end="") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Bucket/2023/crypto/Search-3/search_3_generator.py | ctfs/Bucket/2023/crypto/Search-3/search_3_generator.py | from Crypto.Util.number import getPrime, inverse, bytes_to_long, isPrime
from string import ascii_letters, digits
from random import choice
m = bytes_to_long(open("flag.txt", "rb").read())
p = getPrime(128)
q = getPrime(128)
n = p * p
e = 65537
l = (p-1)*(p-1)
d = inverse(e, l)
m = pow(m, e, n)
print(m)
print(n) | 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.