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/WHY/2025/Quals/web/Flyer/flyer.py | ctfs/WHY/2025/Quals/web/Flyer/flyer.py | from flask import Flask, request, render_template, abort, make_response
import subprocess
import string
import random
import os
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
colors = [ "#61f2ff", "#f25e95", "#fffb96", "#b03bbf", "#5234bf", "#f24534" ]
command_text_add = r"""convert -size 840x{height} -geometry +0+300 -gravity center -background none -stroke white -strokewidth 1 -fill white -font /var/www/flyer/static/Beon-Regular.ttf -pointsize 36 -interline-spacing 20 -kerning 1.5 label:"{text}" \( +clone -background "{color}" -shadow 100x2+0+0 \) +swap \( +clone -background "{color}" -shadow 100x5+0+0 \) +swap \( +clone -background "{color}" -shadow 100x11+0+0 \) +swap \( +clone -background "{color}" -shadow 100x19+0+0 \) +swap -background none -layers merge /var/www/flyer/assets/flyer.png +swap -gravity center -composite {tmpfile} > /dev/null 2>&1"""
charWidth = {',': 9.5, '-': 14.5, '0': 28.5, '1': 15.5, '2': 19.5, '3': 21.5, '4': 20.5, '5': 22.5, '6': 22.5, '7': 18.5, '8': 21.5, '9': 22.5, 'A': 24.5, 'B': 24.5, 'C': 28.5, 'D': 26.5, 'E': 23.5, 'F': 22.5, 'G': 28.5, 'H': 25.5, 'I': 9.5, 'J': 21.5, 'K': 23.5, 'L': 22.5, 'M': 33.5, 'N': 25.5, 'O': 30.5, 'P': 22.5, 'Q': 30.5, 'R': 23.5, 'S': 22.5, 'T': 23.5, 'U': 26.5, 'V': 25.5, 'W': 35.5, 'X': 29.5, 'Y': 26.5, 'Z': 26.5, '_': 17.5, 'a': 21.5, 'b': 23.5, 'c': 22.5, 'd': 23.5, 'e': 23.5, 'f': 18.5, 'g': 23.5, 'h': 24.5, 'i': 8.5, 'j': 8.5, 'k': 20.5, 'l': 8.5, 'm': 39.5, 'n': 24.5, 'o': 23.5, 'p': 23.5, 'q': 23.5, 'r': 20.5, 's': 21.5, 't': 19.5, 'u': 24.5, 'v': 23.5, 'w': 32.5, 'x': 23.5, 'y': 24.5, 'z': 22.5, ' ': 12.5}
@app.route('/')
def index():
return render_template("base.html")
@app.route('/generate', methods=['POST'])
def generate():
color = request.form.get("color", None)
text = request.form.get("text", None)
if not color or not text:
abort(400, "Missing arguments")
if int(color) not in range(6):
abort(400, "Invalid color")
if len(text) > 438:
abort(400, "Text too large")
return create_flyer(text, int(color))
def create_flyer(text, color):
global command_text_add
global colors
color = colors[color]
tmpfile = "/tmp/" + random_string(16) + ".png"
(height, text) = cutstring(text)
cmd = command_text_add.format(
height = height,
text = text,
color = color,
tmpfile = tmpfile
)
subprocess.run(cmd.encode('utf-8'), shell=True, timeout=10, cwd="/var/www/flyer")
if not os.path.isfile(tmpfile):
abort(500, "Error creating flyer")
with open(tmpfile, "rb") as f:
imgdata = f.read()
resp = make_response(imgdata)
os.remove(tmpfile)
resp.headers['Content-Type'] = 'image/png'
resp.headers['Content-Disposition'] = 'attachment;filename=flyer.png'
return resp
def random_string(n):
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=n))
def filterString(x):
forbidden_chars = '"#$%\'()*+/:;<=>?@[\\]^`{|}~'
if x in forbidden_chars:
abort(403, f"Found illegal string {x}")
def cutstring(s):
global charWidth
try:
s = s.strip()
lengthWord = 0
lengthLine = 0
sLine = ''
sWord = ''
wordLength = 0
countList = 0
sPrint = ''
for char in s:
filterString(char)
if char in charWidth.keys():
lengthWord = lengthWord + (charWidth[char])
lengthLine = lengthLine + (charWidth[char])
else:
lengthWord = lengthWord + 25
lengthLine = lengthLine + 25
if lengthLine < 800:
if char != ' ':
sWord = (str(sWord) + str(char))
else:
sLine = (str(sLine) + str(sWord))
lengthWord = 0
sWord = char
elif lengthWord > 800:
abort(400, f"Word {sWord} too long to fit on a line")
else:
sPrint = (str(sPrint) + str(((str(sLine) + str('DeL1m3T3r!')))))
lengthLine = 0
for i in sWord:
if i in charWidth.keys():
filterString(i)
lengthWord = lengthWord + (charWidth[char])
lengthLine = lengthLine + (charWidth[char])
else:
lengthWord = lengthWord + 25
lengthLine = lengthLine + 25
sLine = ''
sWord = (str(sWord) + str(char))
if char != ' ':
sLine = (str(sLine) + str(sWord))
sPrint = (str(sPrint) + str(sLine))
sPrintList = sPrint.split('DeL1m3T3r!')
textHeight = len(sPrintList) * 60
if textHeight > 780:
abort(400, "Height too long: " + str(textHeight))
text = '\\n'.join(sPrintList)
if len(text) > 460:
abort(400, "Length too long: " + str(len(text)))
return(textHeight,text)
except Exception as error:
if isinstance(error, HTTPException):
abort(error.code, error.description)
return(780, s)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WHY/2025/Finals/misc/TitleCase/TitleCase.py | ctfs/WHY/2025/Finals/misc/TitleCase/TitleCase.py | #!/usr/bin/env python3
eval(input().title())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WHY/2025/Finals/web/Flyer/flyer.py | ctfs/WHY/2025/Finals/web/Flyer/flyer.py | from flask import Flask, request, render_template, abort, make_response
import subprocess
import string
import random
import os
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
colors = [ "#61f2ff", "#f25e95", "#fffb96", "#b03bbf", "#5234bf", "#f24534" ]
command_text_add = r"""convert -size 840x{height} -geometry +0+300 -gravity center -background none -stroke white -strokewidth 1 -fill white -font /var/www/flyer/static/Beon-Regular.ttf -pointsize 36 -interline-spacing 20 -kerning 1.5 label:"{text}" \( +clone -background "{color}" -shadow 100x2+0+0 \) +swap \( +clone -background "{color}" -shadow 100x5+0+0 \) +swap \( +clone -background "{color}" -shadow 100x11+0+0 \) +swap \( +clone -background "{color}" -shadow 100x19+0+0 \) +swap -background none -layers merge /var/www/flyer/assets/flyer.png +swap -gravity center -composite {tmpfile} > /dev/null 2>&1"""
charWidth = {',': 9.5, '-': 14.5, '0': 28.5, '1': 15.5, '2': 19.5, '3': 21.5, '4': 20.5, '5': 22.5, '6': 22.5, '7': 18.5, '8': 21.5, '9': 22.5, 'A': 24.5, 'B': 24.5, 'C': 28.5, 'D': 26.5, 'E': 23.5, 'F': 22.5, 'G': 28.5, 'H': 25.5, 'I': 9.5, 'J': 21.5, 'K': 23.5, 'L': 22.5, 'M': 33.5, 'N': 25.5, 'O': 30.5, 'P': 22.5, 'Q': 30.5, 'R': 23.5, 'S': 22.5, 'T': 23.5, 'U': 26.5, 'V': 25.5, 'W': 35.5, 'X': 29.5, 'Y': 26.5, 'Z': 26.5, '_': 17.5, 'a': 21.5, 'b': 23.5, 'c': 22.5, 'd': 23.5, 'e': 23.5, 'f': 18.5, 'g': 23.5, 'h': 24.5, 'i': 8.5, 'j': 8.5, 'k': 20.5, 'l': 8.5, 'm': 39.5, 'n': 24.5, 'o': 23.5, 'p': 23.5, 'q': 23.5, 'r': 20.5, 's': 21.5, 't': 19.5, 'u': 24.5, 'v': 23.5, 'w': 32.5, 'x': 23.5, 'y': 24.5, 'z': 22.5, ' ': 12.5}
@app.route('/')
def index():
return render_template("base.html")
@app.route('/generate', methods=['POST'])
def generate():
color = request.form.get("color", None)
text = request.form.get("text", None)
if not color or not text:
abort(400, "Missing arguments")
if int(color) not in range(6):
abort(400, "Invalid color")
if len(text) > 438:
abort(400, "Text too large")
return create_flyer(text, int(color))
def create_flyer(text, color):
global command_text_add
global colors
color = colors[color]
tmpfile = "/tmp/" + random_string(16) + ".png"
(height, text) = cutstring(text)
cmd = command_text_add.format(
height = height,
text = text,
color = color,
tmpfile = tmpfile
)
subprocess.run(cmd.encode('utf-8'), shell=True, timeout=10, cwd="/var/www/flyer")
if not os.path.isfile(tmpfile):
abort(500, "Error creating flyer")
with open(tmpfile, "rb") as f:
imgdata = f.read()
resp = make_response(imgdata)
os.remove(tmpfile)
resp.headers['Content-Type'] = 'image/png'
resp.headers['Content-Disposition'] = 'attachment;filename=flyer.png'
return resp
def random_string(n):
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=n))
def filterString(x):
forbidden_chars = '"#$%\'()*+/:;<=>?@[\\]^`{|}~'
if x in forbidden_chars:
abort(403, f"Found illegal string {x}")
def cutstring(s):
global charWidth
try:
s = s.strip()
lengthWord = 0
lengthLine = 0
sLine = ''
sWord = ''
wordLength = 0
countList = 0
sPrint = ''
for char in s:
filterString(char)
if char in charWidth.keys():
lengthWord = lengthWord + (charWidth[char])
lengthLine = lengthLine + (charWidth[char])
else:
lengthWord = lengthWord + 25
lengthLine = lengthLine + 25
if lengthLine < 800:
if char != ' ':
sWord = (str(sWord) + str(char))
else:
sLine = (str(sLine) + str(sWord))
lengthWord = 0
sWord = char
elif lengthWord > 800:
abort(400, f"Word {sWord} too long to fit on a line")
else:
sPrint = (str(sPrint) + str(((str(sLine) + str('DeL1m3T3r!')))))
lengthLine = 0
for i in sWord:
if i in charWidth.keys():
filterString(i)
lengthWord = lengthWord + (charWidth[char])
lengthLine = lengthLine + (charWidth[char])
else:
lengthWord = lengthWord + 25
lengthLine = lengthLine + 25
sLine = ''
sWord = (str(sWord) + str(char))
if char != ' ':
sLine = (str(sLine) + str(sWord))
sPrint = (str(sPrint) + str(sLine))
sPrintList = sPrint.split('DeL1m3T3r!')
textHeight = len(sPrintList) * 60
if textHeight > 780:
abort(400, "Height too long: " + str(textHeight))
text = '\\n'.join(sPrintList)
if len(text) > 460:
abort(400, "Length too long: " + str(len(text)))
return(textHeight,text)
except Exception as error:
if isinstance(error, HTTPException):
abort(error.code, error.description)
return(780, s)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2021/crypto/Babysign/server.py | ctfs/THCon/2021/crypto/Babysign/server.py | from Crypto.Util.number import getPrime, GCD, inverse, bytes_to_long
import os
class SecureSigner():
def __init__(self):
p = getPrime(512)
q = getPrime(512)
e = 0x10001
phi = (p-1)*(q-1)
while GCD(e,phi) != 1:
p = getPrime(512)
q = getPrime(512)
phi = (p-1)*(q-1)
self.d = inverse(e,phi)
self.n = p * q
self.e = e
def sign(self, message):
return pow(message,self.d,self.n)
def verify(self, message, signature):
return pow(signature,self.e,self.n) == message
def menu():
print(
"""
1 - Sign an 8-bit integer
2 - Execute command
3 - Exit
"""
)
choice = input("Choice: ")
if choice == "1":
try:
m = int(input("Integer to sign: "))
if 0 <= m < 256:
print("Signature: {:d}".format(s.sign(m)))
else:
print("You can only sign 8-bit integers.")
except:
print("An error occured.")
exit(1)
elif choice == "2":
try:
cmd = input("Command: ")
m = bytes_to_long(cmd.encode())
signature = int(input("Signature: "))
if s.verify(m,signature):
os.system(cmd)
else:
print("Wrong signature.")
except:
print("An error occured.")
exit(1)
elif choice == "3":
exit(0)
else:
print("Incorrect input.")
exit(1)
if __name__ == '__main__':
s = SecureSigner()
print("Here are your parameters:\n - modulus n: {:d}\n - public exponent e: {:d}\n".format(s.n, s.e))
while True:
menu()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2021/crypto/Too_old_to_sign/server.py | ctfs/THCon/2021/crypto/Too_old_to_sign/server.py | #!/usr/local/bin/python3.8
from Crypto.PublicKey import RSA
from Crypto.Util.number import long_to_bytes,bytes_to_long
from secret import FLAG, aes_key
from hashlib import sha1
from os import urandom
def sign1(sk, m):
mq, dq = m % sk.q, sk.d % (sk.q - 1)
mp, dp = m % sk.p, sk.d % (sk.p - 1)
s1 = pow(mq, dp, sk.q)
s2 = pow(mp, dp, sk.p)
h = (sk.u * (s1 - s2)) % sk.q
s = (s2 + h * sk.p) % sk.n
return s
def sign2(sk, m):
mq, dq = m % sk.q, sk.d % (sk.q - 1)
mp, dp = m % sk.p, sk.d % (sk.p - 1)
s1 = pow(mq, dq, sk.q)
s2 = pow(mp, dq, sk.p)
h = (sk.u * (s1 - s2)) % sk.q
s = (s2 + h * sk.p) % sk.n
return s
def pad(m,n):
return m + urandom(n//8)
def encode(m,n):
return b"\x6a" + m[:(n-160-16)//8] + sha1(m).digest() + b"\xbc"
assert(len(aes_key) == 16)
private_key = RSA.generate(2048)
message = b"Here is a message to inform you that this AES key : -" + aes_key + b"- will allow you to decrypt my very secret message. I signed my message to prove my good faith, but make sure no one is watching...\n"
message += b"An anonymous vigilante trying to preserve Thcon and our delicious cassoulet"
padded_message = pad(message,2048)
encoded_message = encode(padded_message,2048)
signature1 = sign1(private_key,bytes_to_long(encoded_message))
print("signature1 =",signature1)
signature2 = sign2(private_key,bytes_to_long(encoded_message))
print("signature2 =",signature2)
print("e =",private_key.e)
print("n =",private_key.n)
pt = bytes_to_long(FLAG)
print("ct =",pow(pt,private_key.e,private_key.n))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2021/crypto/ECDSAFE/server.py | ctfs/THCon/2021/crypto/ECDSAFE/server.py | #!/usr/local/bin/python3.8
from os import urandom
from Crypto.Util.number import inverse
from hashlib import sha256
from Crypto.Random import random
import ecdsa
from flag import FLAG
class PRNG:
def __init__(self,seed,m,flag):
self.state = seed
self.m = m
self.counter = 0
self.flag = flag
def next_state(self):
b = self.flag[self.counter % len(self.flag)]
self.state = (self.state + b) % self.m
self.counter += 1
return self.state
C = ecdsa.NIST256p
G = C.generator
N = int(C.order)
seed = random.randint(1,N-1)
prng = PRNG(seed,N,FLAG)
private_key = int(sha256(urandom(16)).hexdigest(),16) % N
public_key = G * private_key
print("Public key : ",(int(public_key.x()),int(public_key.y())))
signatures = []
for i in range(len(FLAG)):
k = prng.next_state() % N
P = G * k
r = int(P.x()) % N
h = int(sha256(urandom(16)).hexdigest(),16)
s = inverse(k,N)*(h+r*private_key)%N
signatures.append([h,r,s])
print(signatures) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2021/crypto/weebox.py/weebox.py | ctfs/THCon/2021/crypto/weebox.py/weebox.py | import hashlib
import sys
#
# weebox.py
# - written by plcp
# - owned by quarkslab
# - only engages its author for code quality :)
#
nb_bits = 256
nb_bytes = 32
nb_words = 64
word_len = 4
word_mask = (2**word_len) - 1
ladder_size = 2**word_len
group = 115792089210356248762697446949407573530086143415290314195533631308867097853951
order = 115792089210356248762697446949407573529996955224135760342422259061068512044369
#
# finite field arithmetic
#
moduli = None
def invmod(a):
return pow(a % moduli, moduli - 2, moduli)
def mulmod(a, b):
return (a * b) % moduli
def doublemod(a):
return (a + a) % moduli
def addmod(a, b):
return (a + b) % moduli
def submod(a, b):
return (moduli + a - b) % moduli
#
# curve arithmetic
#
gptx = 108916722531310784954987870693632311777886073173317798030971327994717526058474
gpty = 48669730670864784357653778404419338261994208753462863646109767832706509632230
gptz = 73235898817912095104913541943786679798085951656820227383958162362143073870143
gpt = (gptx, gpty, gptz)
def to_affine(pt):
global moduli
last, moduli = moduli, group
x, y, z = pt
iz = invmod(z)
iz2 = mulmod(iz, iz)
x = mulmod(x, iz2)
y = mulmod(y, mulmod(iz2, iz))
moduli = last
return (x, y)
def doublept(pt):
x, y, z = pt
y2 = mulmod(y, y)
y4 = mulmod(y2, y2)
z2 = mulmod(z, z)
z4 = mulmod(z2, z2)
x2 = mulmod(x, x)
s = mulmod(4, mulmod(x, y2))
m = mulmod(3, submod(x2, z4))
xd = submod(mulmod(m, m), doublemod(s))
yd = submod(mulmod(m, submod(s, xd)), mulmod(8, y4))
zd = doublemod(mulmod(y, z))
return (xd, yd, zd)
def addpt(pt, other):
x1, y1, z1 = pt
x2, y2, z2 = other
z1p2 = mulmod(z1, z1)
z2p2 = mulmod(z2, z2)
u1 = mulmod(x1, z2p2)
u2 = mulmod(x2, z1p2)
# mmmh, ignore infinity?
#
if u1 == u2:
return doublept(pt)
v1 = mulmod(y1, mulmod(z2p2, z2))
v2 = mulmod(y2, mulmod(z1p2, z1))
h = submod(u2, u1)
r = submod(v2, v1)
h2 = mulmod(h, h)
h3 = mulmod(h2, h)
x = submod(submod(mulmod(r, r), h3), doublemod(mulmod(u1, h2)))
y = submod(mulmod(r, submod(mulmod(u1, h2), x)), mulmod(v1, h3))
z = mulmod(h, mulmod(z1, z2))
return (x, y, z)
def negpt(pt):
global s1, s2, s3
x, y, z = pt
return (x, moduli - y, z)
def scalarmult(pt, scalar):
global moduli
last, moduli = moduli, group
ret = None
mask = 1 << nb_bits
for _ in range(nb_bits):
mask >>= 1
if ret is not None:
ret = doublept(ret)
if scalar & mask:
ret = addpt(ret, pt) if ret is not None else pt
moduli = last
return ret
#
# windowing
#
class scalar_table:
def __init__(self, data, table):
self.table = table
self.data = data
def __call__(self, scalar):
assert moduli == order
scalar = scalar % moduli
words = []
for _ in range(nb_words):
words.append(scalar & word_mask)
scalar >>= word_len
acc = 0
for idx in range(nb_words):
acc = mulmod(ladder_size, acc)
acc = addmod(acc, self.table[nb_words * words[-1 - idx] + idx])
return acc
class point_table:
def __init__(self, data, table):
self.table = table
self.data = data
def __call__(self, scalar):
global moduli
last, moduli = moduli, group
words = []
for _ in range(nb_words):
words.append(scalar & word_mask)
scalar >>= word_len
acc = self.table[nb_words * words[-1]]
for idx in range(1, nb_words):
acc = addpt(acc, self.table[nb_words * words[-1 - idx] + idx])
moduli = last
return acc
#
# load tables
#
def load(table):
ret = []
for idx in range(1024):
blob = table[idx * 32:(idx + 1) * 32]
ret.append(int.from_bytes(blob, byteorder='big'))
return scalar_table(table, ret)
def loadpt(table):
ret = []
for idx in range(1024):
blob = table[idx * 32 * 3:(idx + 3) * 32 * 3]
x = int.from_bytes(blob[0:32], byteorder='big')
y = int.from_bytes(blob[32:64], byteorder='big')
z = int.from_bytes(blob[64:96], byteorder='big')
ret.append((x, y, z))
return point_table(table, ret)
with open('tables.bin', 'rb') as f:
tables = f.read()
la8b2f19f = load(tables[0:32768])
l193d94fd = load(tables[32768:65536])
lc987ed3a = load(tables[65536:98304])
l73dc1cd1 = load(tables[98304:131072])
la3f31e5b = load(tables[131072:163840])
l0c7dced9 = loadpt(tables[163840:262144])
l676247ea = load(tables[262144:294912])
l23892dfe = load(tables[294912:327680])
lb97b239d = load(tables[327680:360448])
l46939eac = load(tables[360448:393216])
lb9d6a1ea = load(tables[393216:425984])
l31e5930b = load(tables[425984:458752])
lc8891a89 = load(tables[458752:491520])
le06cd15a = load(tables[491520:524288])
l48c04bbb = load(tables[524288:557056])
l342337a4 = load(tables[557056:589824])
ld95bb85f = load(tables[589824:622592])
l58d3310b = load(tables[622592:655360])
l9fd80926 = load(tables[655360:688128])
l2a03fe7a = load(tables[688128:720896])
l4d477f0d = load(tables[720896:753664])
lb23e60f2 = load(tables[753664:786432])
la3472e5f = load(tables[786432:819200])
l5ec41a3a = load(tables[819200:851968])
l5a7b02ce = load(tables[851968:884736])
l74013f60 = load(tables[884736:917504])
l09c92783 = load(tables[917504:950272])
l7ed57829 = load(tables[950272:983040])
l89c6ab42 = load(tables[983040:1015808])
#
# verify
#
def load_pub(pub):
global moduli
last, moduli = moduli, group
x = int.from_bytes(pub, byteorder='big')
cst = 41058363725152142129326129780047268409114441015993725554835256314039467401291
x3 = mulmod(mulmod(x, x), x)
y2 = addmod(submod(x3, mulmod(3, x)), cst)
yd = pow(y2, (moduli + 1) // 4, moduli)
pub = addpt(addpt(gpt, (x, yd, 1)), negpt(gpt))
moduli = last
return pub
def verify(msg, sig, pub):
global moduli
last, moduli = moduli, order
hashed = hashlib.sha256(msg).digest()
# load
#
r, s = sig[:nb_bytes], sig[nb_bytes:]
e = int.from_bytes(hashed, byteorder='big') % moduli
r = int.from_bytes(r, byteorder='big') % moduli
s = int.from_bytes(s, byteorder='big') % moduli
pub = load_pub(pub)
# u1 & u2
#
s = invmod(s)
u1 = mulmod(e, s)
u2 = mulmod(r, s)
# point
moduli = group
pt = addpt(scalarmult(gpt, u1), scalarmult(pub, u2))
x, _ = to_affine(pt)
# is sig valid?
#
return (x % order) == r
#
# signature
#
def sign(msg):
global moduli
last, moduli = moduli, order
hashed = hashlib.sha256(msg).digest()
# compute r
#
e = int.from_bytes(hashed, byteorder='big') % order
ie = invmod(e)
t0 = la8b2f19f(e) % order
t1 = l193d94fd(t0) % order
t2 = mulmod(t1, lc987ed3a(ie))
t3 = addmod(t2, l73dc1cd1(e))
t4 = addmod(t3, la3f31e5b(ie))
t5 = l0c7dced9(t4)
tmp0 = l676247ea(e) % order
t6 = scalarmult(t5, mulmod(invmod(tmp0), l23892dfe(e)))
r, _ = to_affine(t6)
# compute s
#
t7 = lb97b239d(t4) % order
tmp1 = invmod(t7)
t8 = mulmod(tmp0, l46939eac(tmp1))
t9 = mulmod(tmp0, lb9d6a1ea(tmp1))
ta = mulmod(r, l31e5930b(ie))
ta = addmod(ta, lc8891a89(mulmod(r, ie)))
ta = addmod(ta, le06cd15a(ie))
ta = addmod(ta, mulmod(l48c04bbb(ie), l342337a4(r)))
ta = addmod(ta, mulmod(ld95bb85f(ie), l58d3310b(r)))
ta = addmod(ta, mulmod(l9fd80926(r), l2a03fe7a(ie)))
tb = mulmod(r, l4d477f0d(ie))
tb = addmod(tb, lb23e60f2(mulmod(r, ie)))
tb = addmod(tb, la3472e5f(ie))
tb = addmod(tb, mulmod(l5ec41a3a(ie), l5a7b02ce(r)))
tb = addmod(tb, mulmod(l74013f60(ie), l09c92783(r)))
tb = addmod(tb, mulmod(l7ed57829(r), l89c6ab42(ie)))
s = addmod(mulmod(ta, t8), mulmod(tb, t9))
# finalize
#
r = r.to_bytes(nb_bytes, byteorder='big')
s = s.to_bytes(nb_bytes, byteorder='big')
moduli = last
return r + s
if __name__ == "__main__":
pub = '9274d0bb1bd842d732a3ddc415032e45efa0130d8140a4fa77e67e284224968e'
pub = bytes.fromhex(pub)
msg = b'A specter is haunting the world, the specter of crypto anarchy.'
sig = sign(msg)
assert verify(msg, sig, pub)
if len(sys.argv) != 2:
print('Usage: {} <hex>'.format(sys.argv[0]))
sys.exit(1)
msg = bytes(sys.argv[1], encoding='utf8')
sig = sign(msg)
assert verify(msg, sig, pub)
print('signature:', sig.hex())
print('public key:', pub.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2021/crypto/Rsa_internal_attacker/chall.py | ctfs/THCon/2021/crypto/Rsa_internal_attacker/chall.py | #!/usr/bin/env python3
from Crypto.Util.number import getPrime, inverse, bytes_to_long
import random
from math import gcd
def init():
p = getPrime(1024)
q = getPrime(1024)
return p, q
def new_user(p, q):
phi = (p - 1) * (q - 1)
while True:
e = random.randint(2, 100000)
if gcd(e, phi) == 1:
break
d = inverse(e, phi)
return e, d
def encrypt(m, e, n):
return pow(m, e, n)
p, q = init()
n = p * q
e_a, d_a = new_user(p, q)
e_b, d_b = new_user(p, q)
FLAG = b"THC2021{??????????????????????????????????????}"
c = encrypt(bytes_to_long(FLAG), e_b, n)
print(f"The public modulus : {hex(n)}")
print(f"Your key pair : ({hex(e_a)}, {hex(d_a)})")
print(f"Your boss public key : {hex(e_b)}")
print(f"Intercepted message : {hex(c)}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2021/crypto/Kidsign/server.py | ctfs/THCon/2021/crypto/Kidsign/server.py | from Crypto.Util.number import inverse, isPrime
from random import SystemRandom
from hashlib import sha256
from flag import FLAG
import os
rand = SystemRandom()
class ElGamal:
def __init__(self):
self.q = 89666094075799358333912553751544914665545515386283824011992558231120286657213785559151513056027280869020616111209289142073255564770995469726364925295894316484503027288982119436576308594740674437582226015660087863550818792499346330713413631956572604302171842281106323020998625124370502577704273068156073608681
assert(isPrime(self.q))
self.p = 2*self.q + 1
assert(isPrime(self.p))
self.g = 2
self.H = sha256
self.x = rand.randint(1,self.p-2)
self.y = pow(self.g,self.x,self.p)
def sign(self,m):
k = rand.randint(2,self.p-2)
while GCD(k,self.p-1) != 1:
k = rand.randint(2,self.p-2)
r = pow(self.g,k,self.p)
h = int(self.H(m).hexdigest(),16)
s = ((h - self.x * r)* inverse(k,self.p-1)) % (self.p - 1)
assert(s != 0)
return (r,s)
def verify(self,m,r,s):
if r <= 0 or r >= (self.p):
return False
if s <= 0 or s >= (self.p-1):
return False
h = int(self.H(m).hexdigest(),16)
return pow(self.g,h,self.p) == (pow(self.y,r,self.p) * pow(r,s,self.p)) % self.p
if __name__ == '__main__':
S = ElGamal()
print("Here are your parameters:\n - generator g: {:d}\n - prime p: {:d}\n - public key y: {:d}\n".format(S.g, S.p, S.y))
message = os.urandom(16)
print("If you can sign this message : {:s}, I'll reward you with a flag!".format(message.hex()))
r = int(input("r: "))
s = int(input("s: "))
if S.verify(message,r,s):
print(FLAG)
else:
print("Nope.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2025/crypto/OTPas_ouf/OTP_encryption.py | ctfs/THCon/2025/crypto/OTPas_ouf/OTP_encryption.py | from random import randint
def generate_OTP():
OTP = b''
for _ in range(10):
OTP += int.to_bytes(randint(0,255))
return OTP
def encrypt_file(input_file: str, output_file: str, passwd: bytes):
with open(input_file, "rb") as ifile:
input_data = ifile.read()
with open(output_file, 'wb') as ofile:
buffer = bytes([(input_data[k] ^ passwd[k % len(passwd)]) for k in range(len(input_data))])
ofile.write(buffer)
if __name__ == '__main__':
otp = generate_OTP()
input_file = input("Entrer le nom du fichier à chiffrer: ").lower()
output_file = input_file + '.encrypted'
encrypt_file(input_file, output_file, otp)
print(f"Le fichier {input_file} a été chiffré avec succès.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2025/crypto/Mammoths_Personnal_Slot_Machine/server_REDACTED.py | ctfs/THCon/2025/crypto/Mammoths_Personnal_Slot_Machine/server_REDACTED.py | import random
import socket
import time
random.seed(some_number)
print("Random values:", [random.getrandbits(32) for _ in range(here_too)])
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 12345))
server_socket.listen(5)
print("Server listening on port 12345")
while True:
conn, addr = server_socket.accept()
try:
print(f"Connection from {addr}")
conn.sendall(b"Guess which number I'm thinking:\n")
while True:
data = conn.recv(1024)
if not data:
break
try:
guess = int(data.strip())
except ValueError:
conn.sendall(b"Invalid input. Send a number.\n")
continue
correct_number = random.getrandbits(32)
if guess == correct_number:
conn.sendall(b"Correct! Here is your flag: THC{This_is_not_the_real_flag}\n")
break
else:
conn.sendall(f"Nope! The number was {correct_number}. Try again!\nGuess which number I'm thinking:\n".encode())
conn.close()
except Exception as e:
print(f"Error: {e}")
conn.close()
server_socket.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/THCon/2022/pwn/codemov/codemov.py | ctfs/THCon/2022/pwn/codemov/codemov.py | #!/usr/bin/env python3
from pwn import *
context.arch = 'amd64'
print("Enter your shellcode (80 bytes max): ")
shellcode = []
while True:
try:
code = input().replace(';', '').lower().strip()
if code == "end":
break
if not code.startswith("mov"):
log.failure("Invalid instruction")
exit()
shellcode.append(code)
except EOFError:
break
shellcode = asm('\n'.join(shellcode))
log.info('Executing shellcode')
r = process('./executor', alarm=30)
r.sendline(shellcode)
r.wait_for_close()
log.success('kthxbye') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Auvergnhack/2025/crypto/Monkey_News/back.py | ctfs/Auvergnhack/2025/crypto/Monkey_News/back.py | from flask import Flask, render_template, request, redirect, url_for, session, make_response
from werkzeug.security import check_password_hash
import os
import time
import base64
import subprocess
app = Flask(__name__)
app.secret_key = os.urandom(24)
f=open('flag.txt')
flag=f.read().rstrip('\n')
def load_users():
users = {}
if os.path.exists('databases/users.txt'):
with open('databases/users.txt', 'r') as f:
for line in f:
username, password_hash, rights = line.strip().split(';')
users[username] = {'password_hash': password_hash, 'rights': rights}
return users
def save_users(users):
with open('databases/users.txt', 'w') as f:
for username, data in users.items():
f.write(f"{username};{data['password_hash']};{data['rights']}\n")
def load_chats(user1, user2):
chats = []
if user1 == "KingMonkey":
save_chat("KingMonkey", user2, flag)
if user2 == "KingMonkey":
save_chat("KingMonkey", user1, flag)
filename = f"databases/chats/{min(user1, user2)}_{max(user1, user2)}.txt"
if os.path.exists(filename):
with open(filename, 'r') as f:
for line in f:
try:
from_user, to_user, date, message = line.strip().split(';')
except:
continue
if (from_user == user1 and to_user == user2) or (from_user == user2 and to_user == user1):
chats.append({'from': from_user, 'to': to_user, 'date': date, 'message': message})
return chats
def save_chat(from_user, to_user, message):
date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
filename = f"databases/chats/{min(from_user, to_user)}_{max(from_user, to_user)}.txt"
print(filename)
os.makedirs(os.path.dirname(filename), exist_ok=True) #
with open(filename, 'a') as f:
f.write(f"{from_user};{to_user};{date};{message.replace(';','')}\n")
def get_active_conversations(user):
active_conversations = []
for filename in os.listdir('databases/chats'):
if filename.startswith(user):
other_user = filename.replace(f"{user}_", "").replace(".txt", "")
active_conversations.append(other_user)
if filename.endswith(f"_{user}.txt"):
other_user = filename.replace(f"_{user}.txt", "")
active_conversations.append(other_user)
return active_conversations
@app.route('/')
def index():
if 'username' in session:
return redirect(url_for('news'))
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
users = load_users()
if username in users and check_password_hash(users[username]['password_hash'], password):
rights = base64.b64encode(users[username]['rights'].encode('utf-8')).decode('utf-8')
result = subprocess.run([f"{os.getcwd()}/superadminverificator", "--operation", "0", "--data", rights], capture_output=True)
specs = result.stdout.decode('utf-8').rstrip('\n')
print(specs)
resp = make_response(redirect(url_for('news')))
# We should as this in session
resp.set_cookie('rights', rights)
resp.set_cookie('specs', specs)
session['username'] = username
return resp
else:
return "Invalid credentials!", 401
return render_template('login.html')
@app.route('/news')
def news():
if 'username' not in session:
return redirect(url_for('login'))
return render_template('news.html', username=session['username'])
@app.route('/chat', methods=['GET', 'POST'])
def chat():
if 'username' not in session:
return redirect(url_for('login'))
user_rights = request.cookies.get('rights')
try:
rights = base64.b64decode(user_rights)
except Exception as e:
rights = b""
specs = request.cookies.get('specs')
if user_rights is None or specs is None:
return redirect(url_for('news'))
result = subprocess.run([f"{os.getcwd()}/superadminverificator", "--operation", "1", "--data", f"{user_rights}", "--value", f"{specs}"], capture_output=True)
users = load_users()
user_list = []
if result.returncode == 0:
if rights.endswith(b"_super"):
user_list += [username for username, data in users.items() ]
elif rights.endswith(b"admin"):
user_list = [username for username, data in users.items() if data['rights'] in ['admin', 'member']]
else:
user_list = [username for username, data in users.items() if data['rights'] == 'member']
else:
return redirect(url_for('news'))
if request.method == 'POST':
to_user = request.form['to_user']
message = request.form['message']
if to_user in user_list:
save_chat(session['username'], to_user, message)
active_conversations = get_active_conversations(session['username'])
to_user = request.args.get('to_user')
if to_user:
chats = load_chats(session['username'], to_user)
else:
chats = []
return render_template('chat.html', chats=chats, users=user_list, active_conversations=active_conversations)
if __name__ == '__main__':
app.run(debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyKor/2025/crypto/x2=-1/prob.py | ctfs/CyKor/2025/crypto/x2=-1/prob.py | #!/usr/bin/python3
import math
import os
import signal
from Crypto.Util.number import *
from hashlib import sha256
##### PARAMS #####
P = 2**47 - 297 # Field size
N = 256 # Number of parties
kappa = 64 # Security parameter
tau = 50 # Number of repetitions
##################
# No more suffering from MTU/slow interaction !!
def input_list(name, size):
ret = []
while len(ret) < size:
ret += input(f'{name} > ').split(',')
return ret[:size]
def H(SALT, domain, party_index, SEED):
msg = b'Cykor' + SALT + bytes([domain, party_index]) + SEED
return bytes_to_long(sha256(msg).digest()) % P
def init():
print('================================================================================')
print('Prove your knowledge of x such that x^2 = -1 (mod P), without revealing x itself')
print('================================================================================')
def protocol(SALT, rounds, target):
### Round 1 : Committing to the seeds and views of the parties
Delta_c = int(input("Δc = "))
Delta_x = int(input("Δx = "))
### Round 2 : Challenging the checking protocol
r = bytes_to_long(os.urandom(6)) % P
print(f"{r = }")
### Round 3 : Commit to simulation of the checking protocol
alpha_share = input_list('alpha_shares', N)
alpha_share = [int(x) for x in alpha_share]
beta_share = input_list('beta_shares', N)
beta_share = [int(x) for x in beta_share]
v_share = input_list('v_shares', N)
v_share = [int(x) for x in v_share]
alpha = sum(alpha_share) % P
beta = sum(beta_share) % P
v = sum(v_share) % P
### Round 4 : Challenging the views of the MPC protocol
i_bar = bytes_to_long(os.urandom(1))
print(f"{i_bar = }")
### Round 5 : Opening the views of the MPC and checking protocols.
# Note that seeds[i_bar] is unused in below check routine.
seeds = input_list('seeds', N)
seeds = [bytes.fromhex(x) for x in seeds]
# Now the interactive between user is done,
# server vefifies it.
# Generate shares of beaver triple (a, b, c)
# and input share x (except i_bar)
a_share = [0] * N
b_share = [0] * N
c_share = [0] * N
x_share = [0] * N
for i in range(N):
if i == i_bar:
continue
a_share[i] = H(SALT, 0, i, seeds[i])
b_share[i] = H(SALT, 1, i, seeds[i])
c_share[i] = H(SALT, 2, i, seeds[i])
x_share[i] = H(SALT, 3, i, seeds[i])
# Adjust c_share[0] and x_share[0] using Δc and Δx.
# A prover provides honest adjust values, I guess....?
c_share[0] = (c_share[0] + Delta_c) % P
x_share[0] = (x_share[0] + Delta_x) % P
# If x^2 == target and c == ab, then z = 0.
# 1. Check whether v == 0
if v != 0:
return False
# 2. Check whether shares of alpha, beta, and v are valid
for i in range(N):
if i == i_bar:
continue
# Validity of alpha share
alpha_verify = (r * x_share[i] + a_share[i]) % P
if alpha_verify != alpha_share[i]:
return False
# Validity of beta share
beta_verify = (x_share[i] + b_share[i]) % P
if beta_verify != beta_share[i]:
return False
# Validity of v share
v_verify = 0
if i == 0:
v_verify = (r*target - c_share[i] + alpha * b_share[i] + beta * a_share[i] - alpha * beta) % P
else:
v_verify = (-c_share[i] + alpha * b_share[i] + beta * a_share[i]) % P
if v_verify != v_share[i]:
return False
return True
if __name__ == '__main__':
signal.alarm(1800)
init()
SALT = os.urandom(kappa // 4)
print(f"SALT = {SALT.hex()}")
for i in range(tau):
print(f"===== {i+1}/{tau} =====\n")
if not protocol(SALT, rounds = i, target = P-1):
print("bye...")
break
print("ok, cool!")
else:
flag = open("flag", "rb").read()
print(flag) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyKor/2025/crypto/Rock_Scissors_Paper/chall.py | ctfs/CyKor/2025/crypto/Rock_Scissors_Paper/chall.py | import hashlib
import random
import json
from secret import flag
RSP = ['Rock', 'Scissors', 'Paper']
HASH_LIST = ['md5', 'sha1', 'sha256']
SALT_MAX = 10
ROUND = 2000
class Alice:
def __init__(self):
self.rsp_list = [random.choice(RSP) for _ in range(ROUND)]
self.hash_choice = [random.choice(HASH_LIST) for _ in range(ROUND)]
self.index = 0
def hash(self, rspnsalt):
if self.hash_func == 'md5':
return hashlib.md5(rspnsalt).hexdigest()
elif self.hash_func == 'sha1':
return hashlib.sha1(rspnsalt).hexdigest()
elif self.hash_func == 'sha256':
return hashlib.sha256(rspnsalt).hexdigest()
else:
pass
def next(self):
self.rsp = self.rsp_list[self.index].encode()
self.salt = random.randbytes(SALT_MAX-len(self.rsp))
self.hash_func = self.hash_choice[self.index]
self.hash_val = self.hash(self.rsp + self.salt)
self.index += 1
return {"my_hash" : self.hash_val}, {"rsp" : self.rsp.decode(), "salt" : self.salt.hex(), "hash_func" : self.hash_func}
def verify(self, rsp, salt, hash_func, hash_val):
self.hash_func = hash_func
return bytes.fromhex(self.hash(rsp.encode() + salt)) == hash_val
class Game:
def __init__(self):
self.score = 0
def judge(self, Alice, you):
rules = {"Rock" : "Scissors", "Scissors" : "Paper", "Paper" : "Rock"}
if Alice == you:
self.draw()
elif rules[you] == Alice:
self.win()
else:
self.lose()
def win(self):
print('win')
self.score +=1
def lose(self):
print('lose')
self.score +=0
def draw(self):
print('draw')
self.score +=0
def result(self):
return self.score > 1600
def main():
print("""======================================
this is rock scissors paper game
you must win 1600 times in 2000 chance
======================================""")
game = Game()
alice = Alice()
for _ in range(ROUND):
first_submit, second_submit = alice.next()
print(f'this is my hash -> {json.dumps(first_submit)}')
try:
recv = json.loads(input("what is your hash?\n"))
recv_hash = bytes.fromhex(recv['my_hash'])
except Exception as e:
print(e)
exit(0)
print(f'this is my rsp, salt and hash_func -> {json.dumps(second_submit)}')
try:
recv = json.loads(input("what is your conponents?\n"))
rsp = recv["rsp"]
salt = bytes.fromhex(recv["salt"])
hash_func = recv["hash_func"]
except Exception as e:
print(e)
exit(0)
assert alice.verify(rsp, salt, hash_func, recv_hash)
game.judge(second_submit['rsp'], rsp)
if game.result():
print(flag)
print(game.score)
else:
print('fail')
print(game.score)
exit(0)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyKor/2025/web/dbchat/pow-solver.py | ctfs/CyKor/2025/web/dbchat/pow-solver.py | from __future__ import annotations
import base64
import hashlib
import json
import os
import threading
import time
from typing import Optional
# Paste the /pow/start token here.
CHALLENGE = ""
THREADS = os.cpu_count() or 1
def b64url_decode(s: str) -> bytes:
pad = "=" * (-len(s) % 4)
return base64.urlsafe_b64decode(s + pad)
def leading_zero_bits(digest: bytes) -> int:
total = 0
for b in digest:
if b == 0:
total += 8
else:
total += 8 - b.bit_length()
break
return total
def parse_challenge(token: str):
try:
msg_b64, _sig = token.split(".")
payload = json.loads(b64url_decode(msg_b64))
bits = int(payload["bits"])
salt = b64url_decode(payload["salt"])
exp = int(payload["exp"])
except Exception as e: # noqa: BLE001
raise ValueError("Invalid challenge token") from e
if time.time() > exp:
raise ValueError("Challenge already expired")
return bits, salt, exp
def solve(bits: int, salt: bytes, threads: int) -> str:
"""
Brute-force search for a suffix that satisfies the leading zero bits check.
Uses simple str(counter) as the suffix to keep things deterministic.
"""
stop = threading.Event()
result: list[Optional[str]] = [None]
def worker(start: int, step: int):
counter = start
while not stop.is_set():
suffix = str(counter)
h = hashlib.sha256(salt + suffix.encode()).digest()
if leading_zero_bits(h) >= bits:
result[0] = suffix
stop.set()
return
counter += step
threads = max(1, threads)
pool = [threading.Thread(target=worker, args=(i, threads), daemon=True) for i in range(threads)]
for t in pool:
t.start()
for t in pool:
t.join()
if not result[0]:
raise RuntimeError("Failed to find solution")
return result[0]
def main():
if not CHALLENGE:
raise SystemExit("Please set the CHALLENGE constant to your token.")
bits, salt, exp = parse_challenge(CHALLENGE)
print(f"[+] Challenge parsed: bits={bits}, expires_in={int(exp - time.time())}s")
print(f"[+] Salt length: {len(salt)} bytes")
print(f"[+] Searching with {THREADS} threads ...")
started = time.time()
suffix = solve(bits, salt, THREADS)
elapsed = time.time() - started
print(f"[+] Found suffix: {suffix}")
print(f"[+] Time: {elapsed:.2f}s")
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/CyKor/2025/web/se1enium/pow-solver.py | ctfs/CyKor/2025/web/se1enium/pow-solver.py | from __future__ import annotations
import base64
import hashlib
import json
import os
import threading
import time
from typing import Optional
# Paste the /pow/start token here.
CHALLENGE = ""
THREADS = os.cpu_count() or 1
def b64url_decode(s: str) -> bytes:
pad = "=" * (-len(s) % 4)
return base64.urlsafe_b64decode(s + pad)
def leading_zero_bits(digest: bytes) -> int:
total = 0
for b in digest:
if b == 0:
total += 8
else:
total += 8 - b.bit_length()
break
return total
def parse_challenge(token: str):
try:
msg_b64, _sig = token.split(".")
payload = json.loads(b64url_decode(msg_b64))
bits = int(payload["bits"])
salt = b64url_decode(payload["salt"])
exp = int(payload["exp"])
except Exception as e: # noqa: BLE001
raise ValueError("Invalid challenge token") from e
if time.time() > exp:
raise ValueError("Challenge already expired")
return bits, salt, exp
def solve(bits: int, salt: bytes, threads: int) -> str:
"""
Brute-force search for a suffix that satisfies the leading zero bits check.
Uses simple str(counter) as the suffix to keep things deterministic.
"""
stop = threading.Event()
result: list[Optional[str]] = [None]
def worker(start: int, step: int):
counter = start
while not stop.is_set():
suffix = str(counter)
h = hashlib.sha256(salt + suffix.encode()).digest()
if leading_zero_bits(h) >= bits:
result[0] = suffix
stop.set()
return
counter += step
threads = max(1, threads)
pool = [threading.Thread(target=worker, args=(i, threads), daemon=True) for i in range(threads)]
for t in pool:
t.start()
for t in pool:
t.join()
if not result[0]:
raise RuntimeError("Failed to find solution")
return result[0]
def main():
if not CHALLENGE:
raise SystemExit("Please set the CHALLENGE constant to your token.")
bits, salt, exp = parse_challenge(CHALLENGE)
print(f"[+] Challenge parsed: bits={bits}, expires_in={int(exp - time.time())}s")
print(f"[+] Salt length: {len(salt)} bytes")
print(f"[+] Searching with {THREADS} threads ...")
started = time.time()
suffix = solve(bits, salt, THREADS)
elapsed = time.time() - started
print(f"[+] Found suffix: {suffix}")
print(f"[+] Time: {elapsed:.2f}s")
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/CyKor/2025/web/asterisk/pow-solver.py | ctfs/CyKor/2025/web/asterisk/pow-solver.py | from __future__ import annotations
import base64
import hashlib
import json
import os
import threading
import time
from typing import Optional
# Paste the /pow/start token here.
CHALLENGE = ""
THREADS = os.cpu_count() or 1
def b64url_decode(s: str) -> bytes:
pad = "=" * (-len(s) % 4)
return base64.urlsafe_b64decode(s + pad)
def leading_zero_bits(digest: bytes) -> int:
total = 0
for b in digest:
if b == 0:
total += 8
else:
total += 8 - b.bit_length()
break
return total
def parse_challenge(token: str):
try:
msg_b64, _sig = token.split(".")
payload = json.loads(b64url_decode(msg_b64))
bits = int(payload["bits"])
salt = b64url_decode(payload["salt"])
exp = int(payload["exp"])
except Exception as e: # noqa: BLE001
raise ValueError("Invalid challenge token") from e
if time.time() > exp:
raise ValueError("Challenge already expired")
return bits, salt, exp
def solve(bits: int, salt: bytes, threads: int) -> str:
"""
Brute-force search for a suffix that satisfies the leading zero bits check.
Uses simple str(counter) as the suffix to keep things deterministic.
"""
stop = threading.Event()
result: list[Optional[str]] = [None]
def worker(start: int, step: int):
counter = start
while not stop.is_set():
suffix = str(counter)
h = hashlib.sha256(salt + suffix.encode()).digest()
if leading_zero_bits(h) >= bits:
result[0] = suffix
stop.set()
return
counter += step
threads = max(1, threads)
pool = [threading.Thread(target=worker, args=(i, threads), daemon=True) for i in range(threads)]
for t in pool:
t.start()
for t in pool:
t.join()
if not result[0]:
raise RuntimeError("Failed to find solution")
return result[0]
def main():
if not CHALLENGE:
raise SystemExit("Please set the CHALLENGE constant to your token.")
bits, salt, exp = parse_challenge(CHALLENGE)
print(f"[+] Challenge parsed: bits={bits}, expires_in={int(exp - time.time())}s")
print(f"[+] Salt length: {len(salt)} bytes")
print(f"[+] Searching with {THREADS} threads ...")
started = time.time()
suffix = solve(bits, salt, THREADS)
elapsed = time.time() - started
print(f"[+] Found suffix: {suffix}")
print(f"[+] Time: {elapsed:.2f}s")
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/Cygenix/2024/crypto/DH_900/encrypt.py | ctfs/Cygenix/2024/crypto/DH_900/encrypt.py | mod = int(input('Public mod: '))
base = int(input('Public base: '))
a_secret = int(input('A secret: '))
b_secret = int(input('B secret: '))
a_public = (base ** a_secret) % mod
b_public = (base ** b_secret) % mod
print('=================')
print('A public = ' + str(a_public))
print('B public = ' + str(b_public))
a_shared = (b_public ** a_secret) % mod
b_shared = (a_public ** b_secret) % mod
print('A shared secret = ' + str(a_shared))
print('B shared secret = ' + str(b_shared))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/misc/Befuddled2/challenge.py | ctfs/WolvCTF/2024/misc/Befuddled2/challenge.py | from befunge import befunge, create_grid
import sys
code = input('code? ')
grid = create_grid(code + '\n')
if code == '':
print('no code?')
sys.exit(1)
if len(grid) > 1:
print('must be a one liner!')
sys.exit(1)
if any(c in code for c in '<>'):
print('no')
sys.exit(1)
if len(grid[0]) > 16:
print('too long :(')
sys.exit(1)
befunge(grid, open('flag.txt').read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/misc/Befuddled2/befunge.py | ctfs/WolvCTF/2024/misc/Befuddled2/befunge.py |
import sys
def create_grid(code):
GRID = []
r = 0
c = 0
row = []
for x in code:
if x == '\n':
r += 1
c = 0
GRID.append(row)
row = []
else:
row.append(x)
c += 1
# right pad with spaces
maxlen = max(len(r) for r in GRID)
for i in range(len(GRID)):
GRID[i] += [' '] * (maxlen - len(GRID[i]))
return GRID
def befunge(GRID, FLAG):
PC = [0, 0]
DIR = 0
DIR_DELTAS = [0, 1, 0, -1, 0]
STACK = [ord(c) for c in FLAG[::-1]]
STRINGMODE = False
MAXITER = 1024
for _ in range(MAXITER):
if PC[0] < 0 or PC[1] < 0:
break
try:
ch = GRID[PC[0]][PC[1]]
if STRINGMODE:
if ch == '"':
STRINGMODE = False
else:
STACK.append(ord(ch))
else:
match ch:
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9':
STACK.append(int(ch))
case '+':
a = STACK.pop()
b = STACK.pop()
STACK.append(a+b)
case '-':
a = STACK.pop()
b = STACK.pop()
STACK.append(b-a)
case '*':
a = STACK.pop()
b = STACK.pop()
STACK.append(a*b)
case '/':
a = STACK.pop()
b = STACK.pop()
STACK.append(b//a)
case '%':
a = STACK.pop()
b = STACK.pop()
STACK.append(b%a)
case '!':
a = STACK.pop()
if a == 0:
STACK.append(1)
else:
STACK.append(0)
case '`':
a = STACK.pop()
b = STACK.pop()
if b > a:
STACK.append(1)
else:
STACK.append(0)
# take out the case to stop any unicode shenanigans
case '_':
a = STACK.pop()
if a == 0:
DIR = 0
else:
DIR = 2
case '|':
a = STACK.pop()
if a == 0:
DIR = 1
else:
DIR = 3
case '"':
STRINGMODE = True
case ':':
STACK.append(STACK[-1])
case '\\':
STACK[-2], STACK[-1] = STACK[-1], STACK[-2]
case '$':
STACK.pop()
case '.':
print(STACK.pop(), end=' ')
case ',':
print(chr(STACK.pop()), end='')
case '#':
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
case 'p':
y = STACK.pop()
x = STACK.pop()
v = STACK.pop()
GRID[y][x] = chr(v)
case 'g':
y = STACK.pop()
x = STACK.pop()
STACK.append(ord(GRID[y][x]))
case '@':
break
case ' ':
pass
case _:
print(f'Error: unknown character "{ch}"')
break
# end match
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
except Exception as e:
print('\noh no! anyway...')
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/misc/Befuddled3/challenge.py | ctfs/WolvCTF/2024/misc/Befuddled3/challenge.py | from befunge import befunge, create_grid
import sys
code = input('code? ')
grid = create_grid(code + '\n')
if code == '':
print('no code?')
sys.exit(1)
if len(grid) > 1:
print('must be a one liner!')
sys.exit(1)
if len(grid[0]) > 8:
print('too long :(')
sys.exit(1)
befunge(grid, open('flag.txt').read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/misc/Befuddled3/befunge.py | ctfs/WolvCTF/2024/misc/Befuddled3/befunge.py |
import sys
def create_grid(code):
GRID = []
r = 0
c = 0
row = []
for x in code:
if x == '\n':
r += 1
c = 0
GRID.append(row)
row = []
else:
row.append(x)
c += 1
# right pad with spaces
maxlen = max(len(r) for r in GRID)
for i in range(len(GRID)):
GRID[i] += [' '] * (maxlen - len(GRID[i]))
return GRID
def befunge(GRID, FLAG):
PC = [0, 0]
DIR = 0
DIR_DELTAS = [0, 1, 0, -1, 0]
STACK = [ord(c) for c in FLAG[::-1]]
STRINGMODE = False
MAXITER = 1024
for _ in range(MAXITER):
if PC[0] < 0 or PC[1] < 0:
break
try:
ch = GRID[PC[0]][PC[1]]
if STRINGMODE:
if ch == '"':
STRINGMODE = False
else:
STACK.append(ord(ch))
else:
match ch:
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9':
STACK.append(int(ch))
case '+':
a = STACK.pop()
b = STACK.pop()
STACK.append(a+b)
case '-':
a = STACK.pop()
b = STACK.pop()
STACK.append(b-a)
case '*':
a = STACK.pop()
b = STACK.pop()
STACK.append(a*b)
case '/':
a = STACK.pop()
b = STACK.pop()
STACK.append(b//a)
case '%':
a = STACK.pop()
b = STACK.pop()
STACK.append(b%a)
case '!':
a = STACK.pop()
if a == 0:
STACK.append(1)
else:
STACK.append(0)
case '`':
a = STACK.pop()
b = STACK.pop()
if b > a:
STACK.append(1)
else:
STACK.append(0)
# take out the case to stop any unicode shenanigans
case '_':
a = STACK.pop()
if a == 0:
DIR = 0
else:
DIR = 2
case '|':
a = STACK.pop()
if a == 0:
DIR = 1
else:
DIR = 3
case '"':
STRINGMODE = True
case ':':
STACK.append(STACK[-1])
case '\\':
STACK[-2], STACK[-1] = STACK[-1], STACK[-2]
case '$':
STACK.pop()
case '.':
print(STACK.pop(), end=' ')
case ',':
print(chr(STACK.pop()), end='')
case '#':
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
case 'p':
y = STACK.pop()
x = STACK.pop()
v = STACK.pop()
GRID[y][x] = chr(v)
case 'g':
y = STACK.pop()
x = STACK.pop()
STACK.append(ord(GRID[y][x]))
case '@':
break
case ' ':
pass
case _:
print(f'Error: unknown character "{ch}"')
break
# end match
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
except Exception as e:
print('\noh no! anyway...')
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/misc/Befuddled1/challenge.py | ctfs/WolvCTF/2024/misc/Befuddled1/challenge.py | from befunge import befunge, create_grid
import sys
code = input('code? ')
grid = create_grid(code + '\n')
if code == '':
print('no code?')
sys.exit(1)
if len(grid) > 1:
print('must be a one liner!')
sys.exit(1)
if len(grid[0]) > 16:
print('too long :(')
sys.exit(1)
befunge(grid, open('flag.txt').read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/misc/Befuddled1/befunge.py | ctfs/WolvCTF/2024/misc/Befuddled1/befunge.py |
import sys
def create_grid(code):
GRID = []
r = 0
c = 0
row = []
for x in code:
if x == '\n':
r += 1
c = 0
GRID.append(row)
row = []
else:
row.append(x)
c += 1
# right pad with spaces
maxlen = max(len(r) for r in GRID)
for i in range(len(GRID)):
GRID[i] += [' '] * (maxlen - len(GRID[i]))
return GRID
def befunge(GRID, FLAG):
PC = [0, 0]
DIR = 0
DIR_DELTAS = [0, 1, 0, -1, 0]
STACK = [ord(c) for c in FLAG[::-1]]
STRINGMODE = False
MAXITER = 1024
for _ in range(MAXITER):
if PC[0] < 0 or PC[1] < 0:
break
try:
ch = GRID[PC[0]][PC[1]]
if STRINGMODE:
if ch == '"':
STRINGMODE = False
else:
STACK.append(ord(ch))
else:
match ch:
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9':
STACK.append(int(ch))
case '+':
a = STACK.pop()
b = STACK.pop()
STACK.append(a+b)
case '-':
a = STACK.pop()
b = STACK.pop()
STACK.append(b-a)
case '*':
a = STACK.pop()
b = STACK.pop()
STACK.append(a*b)
case '/':
a = STACK.pop()
b = STACK.pop()
STACK.append(b//a)
case '%':
a = STACK.pop()
b = STACK.pop()
STACK.append(b%a)
case '!':
a = STACK.pop()
if a == 0:
STACK.append(1)
else:
STACK.append(0)
case '`':
a = STACK.pop()
b = STACK.pop()
if b > a:
STACK.append(1)
else:
STACK.append(0)
case '>' | '^' | '<' | 'v':
DIR = '>v<^'.index(ch)
case '_':
a = STACK.pop()
if a == 0:
DIR = 0
else:
DIR = 2
case '|':
a = STACK.pop()
if a == 0:
DIR = 1
else:
DIR = 3
case '"':
STRINGMODE = True
case ':':
STACK.append(STACK[-1])
case '\\':
STACK[-2], STACK[-1] = STACK[-1], STACK[-2]
case '$':
STACK.pop()
case '.':
print(STACK.pop(), end=' ')
case ',':
print(chr(STACK.pop()), end='')
case '#':
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
case 'p':
y = STACK.pop()
x = STACK.pop()
v = STACK.pop()
GRID[y][x] = chr(v)
case 'g':
y = STACK.pop()
x = STACK.pop()
STACK.append(ord(GRID[y][x]))
case '@':
break
case ' ':
pass
case _:
print(f'Error: unknown character "{ch}"')
break
# end match
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
except Exception as e:
print('\noh no! anyway...')
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/rev/Shredded/shredder.py | ctfs/WolvCTF/2024/rev/Shredded/shredder.py | import random
with open(".\\shredded.c", "r") as f:
lines = f.readlines()
longest = 0
for i in lines:
i = i.replace("\n", " ")
if len(i) > longest:
longest = len(i)
padLines = []
for i in lines:
padLines.append(i.replace("\n"," ") + " " * (longest - len(i)))
print(i)
split = ["" for _ in range(longest)]
for line in padLines:
for i in range(longest):
split[i] += line[i]
split[i] += "\n"
split.pop()
random.shuffle(split)
'''for j in range(len(split[0])):
for i in split:
if i[j] != "\n":
print(i[j], end="")
print()'''
#block to print out the shredded file
for i in range(len(split)):
fname = ".\\shredFiles\\shred" + str(i) + ".txt"
with open(fname, "w") as f:
f.write(split[i])
print("Shredded file into " + str(longest-1) + " shreds") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/rev/befudged_up/runner.py | ctfs/WolvCTF/2024/rev/befudged_up/runner.py | from befunge import read_in, befunge
prog = read_in('prog.befunge')
print('flag? ')
befunge(prog)
print('')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/rev/befudged_up/befunge.py | ctfs/WolvCTF/2024/rev/befudged_up/befunge.py |
import sys
def read_in(filename):
GRID = []
r = 0
c = 0
row = []
with open(filename, 'r') as f:
contents = f.read()
for x in contents:
if x == '\n':
r += 1
c = 0
GRID.append(row)
row = []
else:
row.append(x)
c += 1
# right pad with spaces
maxlen = max(len(r) for r in GRID)
for i in range(len(GRID)):
GRID[i] += [' '] * (maxlen - len(GRID[i]))
return GRID
def befunge(GRID):
PC = [0, 0]
DIR = 0
DIR_DELTAS = [0, 1, 0, -1, 0]
STACK = []
STRINGMODE = False
MAXITER = 2**20
for _ in range(MAXITER):
try:
ch = GRID[PC[0]][PC[1]]
if STRINGMODE:
if ch == '"':
STRINGMODE = False
else:
STACK.append(ord(ch))
else:
match ch:
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9':
STACK.append(int(ch))
case '+':
a = STACK.pop()
b = STACK.pop()
STACK.append(a+b)
case '-':
a = STACK.pop()
b = STACK.pop()
STACK.append(b-a)
case '*':
a = STACK.pop()
b = STACK.pop()
STACK.append(a*b)
case '/':
a = STACK.pop()
b = STACK.pop()
STACK.append(b//a)
case '%':
a = STACK.pop()
b = STACK.pop()
STACK.append(b%a)
case '!':
a = STACK.pop()
if a == 0:
STACK.append(1)
else:
STACK.append(0)
case '`':
a = STACK.pop()
b = STACK.pop()
if b > a:
STACK.append(1)
else:
STACK.append(0)
case '>' | '^' | '<' | 'v':
DIR = '>v<^'.index(ch)
case '_':
a = STACK.pop()
if a == 0:
DIR = 0
else:
DIR = 2
case '|':
a = STACK.pop()
if a == 0:
DIR = 1
else:
DIR = 3
case '"':
STRINGMODE = True
case ':':
STACK.append(STACK[-1])
case '\\':
STACK[-2], STACK[-1] = STACK[-1], STACK[-2]
case '$':
STACK.pop()
case '.':
print(STACK.pop(), end=' ')
case ',':
print(chr(STACK.pop()), end='')
case '#':
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
case 'p':
y = STACK.pop()
x = STACK.pop()
v = STACK.pop()
GRID[y][x] = chr(v)
case 'g':
y = STACK.pop()
x = STACK.pop()
STACK.append(ord(GRID[y][x]))
case '~':
x = sys.stdin.read(1)
STACK.append(ord(x))
case '@':
break
case ' ':
pass
case _:
print(f'Error: unknown character "{ch}"')
break
# end match
PC[0] += DIR_DELTAS[DIR]
PC[1] += DIR_DELTAS[DIR + 1]
except Exception as e:
print('oh no', e, PC)
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/crypto/TagSeries1/chal.py | ctfs/WolvCTF/2024/crypto/TagSeries1/chal.py | import sys
import os
from Crypto.Cipher import AES
MESSAGE = b"GET FILE: flag.txt"
QUERIES = []
BLOCK_SIZE = 16
KEY = os.urandom(BLOCK_SIZE)
def oracle(message: bytes) -> bytes:
aes_ecb = AES.new(KEY, AES.MODE_ECB)
return aes_ecb.encrypt(message)[-BLOCK_SIZE:]
def main():
for _ in range(3):
command = sys.stdin.buffer.readline().strip()
tag = sys.stdin.buffer.readline().strip()
if command in QUERIES:
print(b"Already queried")
continue
if len(command) % BLOCK_SIZE != 0:
print(b"Invalid length")
continue
result = oracle(command)
if command.startswith(MESSAGE) and result == tag and command not in QUERIES:
with open("flag.txt", "rb") as f:
sys.stdout.buffer.write(f.read())
sys.stdout.flush()
else:
QUERIES.append(command)
assert len(result) == BLOCK_SIZE
sys.stdout.buffer.write(result + b"\n")
sys.stdout.flush()
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/WolvCTF/2024/crypto/Limited_2/NY_chal_time.py | ctfs/WolvCTF/2024/crypto/Limited_2/NY_chal_time.py | import time
import random
import sys
if __name__ == '__main__':
flag = input("Flag? > ").encode('utf-8')
correct = [192, 123, 40, 205, 152, 229, 188, 64, 42, 166, 126, 125, 13, 187, 91]
if len(flag) != len(correct):
print('Nope :(')
sys.exit(1)
if time.gmtime().tm_year >= 2024 or time.gmtime().tm_year < 2023:
print('Nope :(')
sys.exit(1)
if time.gmtime().tm_yday != 365 and time.gmtime().tm_yday != 366:
print('Nope :(')
sys.exit(1)
for i in range(len(flag)):
# Totally not right now
time_current = int(time.time())
random.seed(i+time_current)
if correct[i] != flag[i] ^ random.getrandbits(8):
print('Nope :(')
sys.exit(1)
time.sleep(random.randint(1, 60))
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/crypto/TagSeries3/chal.py | ctfs/WolvCTF/2024/crypto/TagSeries3/chal.py | import sys
import os
from hashlib import sha1
MESSAGE = b"GET FILE: "
SECRET = os.urandom(1200)
def main():
_sha1 = sha1()
_sha1.update(SECRET)
_sha1.update(MESSAGE)
sys.stdout.write(_sha1.hexdigest() + '\n')
sys.stdout.flush()
_sha1 = sha1()
command = sys.stdin.buffer.readline().strip()
hash = sys.stdin.buffer.readline().strip()
_sha1.update(SECRET)
_sha1.update(command)
if command.startswith(MESSAGE) and b"flag.txt" in command:
if _sha1.hexdigest() == hash.decode():
with open("flag.txt", "rb") as f:
sys.stdout.buffer.write(f.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/WolvCTF/2024/crypto/Limited_1/chal_time.py | ctfs/WolvCTF/2024/crypto/Limited_1/chal_time.py | import time
import random
import sys
if __name__ == '__main__':
flag = input("Flag? > ").encode('utf-8')
correct = [189, 24, 103, 164, 36, 233, 227, 172, 244, 213, 61, 62, 84, 124, 242, 100, 22, 94, 108, 230, 24, 190, 23, 228, 24]
time_cycle = int(time.time()) % 256
if len(flag) != len(correct):
print('Nope :(')
sys.exit(1)
for i in range(len(flag)):
random.seed(i+time_cycle)
if correct[i] != flag[i] ^ random.getrandbits(8):
print('Nope :(')
sys.exit(1)
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/crypto/Blocked2/server.py | ctfs/WolvCTF/2024/crypto/Blocked2/server.py |
import random
import secrets
import sys
import time
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Util.strxor import strxor
MASTER_KEY = secrets.token_bytes(16)
def encrypt(message):
if len(message) % 16 != 0:
print("message must be a multiple of 16 bytes long! don't forget to use the WOLPHV propietary padding scheme")
return None
iv = secrets.token_bytes(16)
cipher = AES.new(MASTER_KEY, AES.MODE_ECB)
blocks = [message[i:i+16] for i in range(0, len(message), 16)]
# encrypt all the blocks
encrypted = [cipher.encrypt(b) for b in [iv, *blocks]]
# xor with the next block of plaintext
for i in range(len(encrypted) - 1):
encrypted[i] = strxor(encrypted[i], blocks[i])
return iv + b''.join(encrypted)
def main():
message = open('message.txt', 'rb').read()
print(""" __ __
_ ______ / /___ / /_ _ __
| | /| / / __ \\/ / __ \\/ __ \\ | / /
| |/ |/ / /_/ / / /_/ / / / / |/ /
|__/|__/\\____/_/ .___/_/ /_/|___/
/_/""")
print("[ email portal ]")
print("you are logged in as doubledelete@wolp.hv")
print("")
print("you have one new encrypted message:")
print(encrypt(message).hex())
while True:
print(" enter a message to send to dree@wolp.hv, in hex")
s = input(" > ")
message = bytes.fromhex(s)
print(encrypt(message).hex())
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/crypto/yORs_Truly_heart/yors-truly.py | ctfs/WolvCTF/2024/crypto/yORs_Truly_heart/yors-truly.py | import base64
plaintext = "A string of text can be encrypted by applying the bitwise XOR operator to every character using a given key"
key = "" # I have lost the key!
def byte_xor(ba1, ba2):
return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])
ciphertext_b64 = base64.b64encode(byte_xor(key.encode(), plaintext.encode()))
ciphertext_decoded = base64.b64decode("NkMHEgkxXjV/BlN/ElUKMVZQEzFtGzpsVTgGDw==")
print(ciphertext_decoded) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/crypto/TwoTimePad/chall.py | ctfs/WolvCTF/2024/crypto/TwoTimePad/chall.py | from Crypto.Random import random, get_random_bytes
BLOCK_SIZE = 16
with(open('./genFiles/wolverine.bmp', 'rb')) as f:
wolverine = f.read()
with(open('./genFiles/flag.bmp', 'rb')) as f:
flag = f.read()
w = open('eWolverine.bmp', 'wb')
f = open('eFlag.bmp', 'wb')
f.write(flag[:55])
w.write(wolverine[:55])
for i in range(55, len(wolverine), BLOCK_SIZE):
KEY = get_random_bytes(BLOCK_SIZE)
w.write(bytes(a^b for a, b in zip(wolverine[i:i+BLOCK_SIZE], KEY)))
f.write(bytes(a^b for a, b in zip(flag[i:i+BLOCK_SIZE], KEY)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2024/crypto/TagSeries2/chal.py | ctfs/WolvCTF/2024/crypto/TagSeries2/chal.py | import sys
import os
from Crypto.Cipher import AES
MESSAGE = b"GET: flag.txt"
QUERIES = []
BLOCK_SIZE = 16
KEY = os.urandom(BLOCK_SIZE)
RANDOM_IV = os.urandom(BLOCK_SIZE)
def oracle(message: bytes) -> bytes:
aes_cbc = AES.new(KEY, AES.MODE_CBC, RANDOM_IV)
return aes_cbc.encrypt(message)[-BLOCK_SIZE:]
def main():
for _ in range(4):
command = sys.stdin.buffer.readline().strip()
tag = sys.stdin.buffer.readline().strip()
if command in QUERIES:
print(b"Already queried")
continue
if len(command) % BLOCK_SIZE != 0:
print(b"Invalid length")
continue
result = oracle(command + len(command).to_bytes(16, "big"))
if command.startswith(MESSAGE) and result == tag and command not in QUERIES:
with open("flag.txt", "rb") as f:
sys.stdout.buffer.write(f.read())
sys.stdout.flush()
else:
QUERIES.append(command)
assert len(result) == BLOCK_SIZE
sys.stdout.buffer.write(result + b"\n")
sys.stdout.flush()
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/WolvCTF/2024/crypto/Blocked1/server.py | ctfs/WolvCTF/2024/crypto/Blocked1/server.py |
"""
----------------------------------------------------------------------------
NOTE: any websites linked in this challenge are linked **purely for fun**
They do not contain real flags for WolvCTF.
----------------------------------------------------------------------------
"""
import random
import secrets
import sys
import time
from Crypto.Cipher import AES
MASTER_KEY = secrets.token_bytes(16)
def generate(username):
iv = secrets.token_bytes(16)
msg = f'password reset: {username}'.encode()
if len(msg) % 16 != 0:
msg += b'\0' * (16 - len(msg) % 16)
cipher = AES.new(MASTER_KEY, AES.MODE_CBC, iv=iv)
return iv + cipher.encrypt(msg)
def verify(token):
iv = token[0:16]
msg = token[16:]
cipher = AES.new(MASTER_KEY, AES.MODE_CBC, iv=iv)
pt = cipher.decrypt(msg)
username = pt[16:].decode(errors='ignore')
return username.rstrip('\x00')
def main():
username = f'guest_{random.randint(100000, 999999)}'
print(""" __ __
_ ______ / /___ / /_ _ __
| | /| / / __ \\/ / __ \\/ __ \\ | / /
| |/ |/ / /_/ / / /_/ / / / / |/ /
|__/|__/\\____/_/ .___/_/ /_/|___/
/_/""")
print("[ password reset portal ]")
print("you are logged in as:", username)
print("")
while True:
print(" to enter a password reset token, please press 1")
print(" if you forgot your password, please press 2")
print(" to speak to our agents, please press 3")
s = input(" > ")
if s == '1':
token = input(" token > ")
if verify(bytes.fromhex(token)) == 'doubledelete':
print(open('flag.txt').read())
sys.exit(0)
else:
print(f'hello, {username}')
elif s == '2':
print(generate(username).hex())
elif s == '3':
print('please hold...')
time.sleep(2)
# thanks chatgpt
print("Thank you for reaching out to WOLPHV customer support. We appreciate your call. Currently, all our agents are assisting other customers. We apologize for any inconvenience this may cause. Your satisfaction is important to us, and we want to ensure that you receive the attention you deserve. Please leave your name, contact number, and a brief message, and one of our representatives will get back to you as soon as possible. Alternatively, you may also visit our website at https://wolphv.chal.wolvsec.org/ for self-service options. Thank you for your understanding, and we look forward to assisting you shortly.")
print("<beep>")
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2023/crypto/keyexchange/challenge.py | ctfs/WolvCTF/2023/crypto/keyexchange/challenge.py | #!/opt/homebrew/bin/python3
from Crypto.Util.strxor import strxor
from Crypto.Util.number import *
from Crypto.Cipher import AES
n = getPrime(512)
s = getPrime(256)
a = getPrime(256)
# n can't hurt me if i don't tell you
print(pow(s, a, n))
b = int(input("b? >>> "))
secret_key = pow(pow(s, a, n), b, n)
flag = open('/flag', 'rb').read()
key = long_to_bytes(secret_key)
enc = strxor(flag + b'\x00' * (len(key) - len(flag)), key)
print(enc.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2023/crypto/Galois-t_is_this/server.py | ctfs/WolvCTF/2023/crypto/Galois-t_is_this/server.py | #!/usr/bin/python3
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.number import *
from Crypto.Util.strxor import *
import os
from pathlib import Path
def GF_mult(x, y):
product = 0
for i in range(127, -1, -1):
product ^= x * ((y >> i) & 1)
x = (x >> 1) ^ ((x & 1) * 0xE1000000000000000000000000000000)
return product
def H_mult(H, val):
product = 0
for i in range(16):
product ^= GF_mult(H, (val & 0xFF) << (8 * i))
val >>= 8
return product
def GHASH(H, A, C):
C_len = len(C)
A_padded = bytes_to_long(A + b'\x00' * (16 - len(A) % 16))
if C_len % 16 != 0:
C += b'\x00' * (16 - C_len % 16)
tag = H_mult(H, A_padded)
for i in range(0, len(C) // 16):
tag ^= bytes_to_long(C[i*16:i*16+16])
tag = H_mult(H, tag)
tag ^= bytes_to_long((8*len(A)).to_bytes(8, 'big') + (8*C_len).to_bytes(8, 'big'))
tag = H_mult(H, tag)
return tag
FLAG = Path('flag.txt').read_text()
# 128-bit blocks
AES_BLOCK_SIZE = 16
key = get_random_bytes(16)
header = b'WolvCTFCertified'
message = b'heythisisasupersecretsupersecret'
used_nonces = set()
def incr(counter):
temp = bytes_to_long(counter)
return long_to_bytes(temp + 1, 16)[-16:]
def check_nonce(nonce):
# if you can't reuse the nonce, surely you can't explot this oracle!
if(nonce in used_nonces):
print("Sorry, a number used once can't be used twice!")
exit(0)
used_nonces.add(nonce)
def encrypt(nonce, pt):
pt = bytes.fromhex(pt)
assert(len(pt) % 16 == 0)
numBlocks = len(pt) // AES_BLOCK_SIZE
if(numBlocks > 3):
print("Sorry, we just don't have the resources to encrypt a message that long!")
exit(0)
nonce = bytes.fromhex(nonce)
assert(len(nonce) == 16)
check_nonce(nonce)
cipher = AES.new(key, AES.MODE_ECB)
hkey = cipher.encrypt(b'\0' * 16)
enc = b''
for i in range(numBlocks + 1):
enc += cipher.encrypt(nonce)
# the counter is just the nonce, right? right??
nonce = incr(nonce)
ct = b''
for i in range(1, numBlocks + 1):
ct += strxor(
enc[i * AES_BLOCK_SIZE: (i+1) * AES_BLOCK_SIZE],
pt[(i-1) * AES_BLOCK_SIZE: i * AES_BLOCK_SIZE])
authTag = strxor(
enc[:AES_BLOCK_SIZE],
long_to_bytes(GHASH(bytes_to_long(hkey), header, ct)))
return ct.hex(), authTag.hex()
def decrypt(nonce, ct, tag):
ct = bytes.fromhex(ct)
assert(len(ct) % 16 == 0)
numBlocks = len(ct) // AES_BLOCK_SIZE
nonce = bytes.fromhex(nonce)
assert(len(nonce) == 16)
check_nonce(nonce)
tag = bytes.fromhex(tag)
assert(len(tag) == 16)
cipher = AES.new(key, AES.MODE_ECB)
hkey = cipher.encrypt(b'\0' * 16)
enc = b''
for i in range(numBlocks + 1):
enc += cipher.encrypt(nonce)
# the counter is just the nonce, right?
nonce = incr(nonce)
pt = b''
for i in range(1, numBlocks + 1):
pt += strxor(
enc[i * AES_BLOCK_SIZE: (i+1) * AES_BLOCK_SIZE],
ct[(i-1) * AES_BLOCK_SIZE: i * AES_BLOCK_SIZE])
authTag = strxor(
enc[:AES_BLOCK_SIZE],
long_to_bytes(GHASH(bytes_to_long(hkey), header, ct)))
if(pt == message):
if(authTag == tag):
print(FLAG)
else:
print("Whoops, that doesn't seem to be authentic!")
else:
print("Hmm, that's not the message I was looking for...")
MENU = """
1. Encrypt
2. Submit
3. Exit
"""
def main():
print("If you can send me a valid super secret super secret I'll give you a reward!")
while len(used_nonces) < 3:
print(MENU)
command = input("> ")
match command:
case "1":
nonce = input("IV (hex) > ")
pt = input("Plaintext (hex) > ")
ct, tag = encrypt(nonce, pt)
print("CT: ", ct)
print("TAG: ", tag)
case "2":
nonce = input("IV (hex) > ")
ct = input("Ciphertext (hex) > ")
tag = input("Tag (hex) > ")
decrypt(nonce, ct, tag)
exit(0)
case other:
print("Bye!")
exit(0)
print("I know encryption is fun, but you can't just keep doing it...")
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/WolvCTF/2023/crypto/Z2kDH/Z2kDH.py | ctfs/WolvCTF/2023/crypto/Z2kDH/Z2kDH.py | #!/usr/bin/python3
modulus = 1 << 258
def Z2kDH_init(private_exponent):
"""
Computes the public result by taking the generator 5 to the private exponent, then removing the last 2 bits
private_exponent must be a positive integer less than 2^256
"""
return pow(5, private_exponent, modulus) // 4
def Z2kDH_exchange(public_result, private_exponent):
"""
Computes the shared secret by taking the sender's public result to the receiver's private exponent, then removing the last 2 bits
public_result must be a non-negative integer less than 2^256
private_exponent must be a positive integer less than 2^256
"""
return pow(public_result * 4 + 1, private_exponent, modulus) // 4
alice_private_exponent = int(open('alice_private_exponent.txt').read(), 16)
bob_private_exponent = int(open('bob_private_exponent.txt').read(), 16)
alice_public_result = Z2kDH_init(alice_private_exponent)
bob_public_result = Z2kDH_init(bob_private_exponent)
# These are sent over the public channel:
print(f'{alice_public_result:064x}') # Alice sent to Bob
print(f'{bob_public_result:064x}') # Bob sent to Alice
alice_shared_secret = Z2kDH_exchange(bob_public_result, alice_private_exponent)
bob_shared_secret = Z2kDH_exchange(alice_public_result, bob_private_exponent)
assert alice_shared_secret == bob_shared_secret # the math works out!
# ...Wait, how did they randomly end up with this shared secret? What a coincidence!
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2023/crypto/DownUnder/key_exchange.py | ctfs/WolvCTF/2023/crypto/DownUnder/key_exchange.py | from flask import Flask, request, jsonify
from json import loads
from Crypto.Util.number import long_to_bytes, bytes_to_long
from hashlib import sha256
from hmac import new
from uuid import uuid4
from generate import generate
app = Flask(__name__)
key = {
'0' : 0 , '1' : 1 , '2' : 2 , '3' : 3 , '4' : 4 , '5' : 5 , '6' : 6 ,
'a' : 70, 'b' : 71, 'c' : 72, 'd' : 73, 'e' : 74, 'f' : 75, 'g' : 76, 'h' : 77, 'i' : 78, 'j' : 79,
'k' : 80, 'l' : 81, 'm' : 82, 'n' : 83, 'o' : 84, 'p' : 85, 'q' : 86, 'r' : 87, 's' : 88, 't' : 89,
'u' : 90, 'v' : 91, 'w' : 92, 'x' : 93, 'y' : 94, 'z' : 95, '_' : 96, '{' : 97, '}' : 98, '!' : 99,
}
sessions = {}
def bytes_to_long_flag(bytes_in):
long_out = ''
for b in bytes_in:
long_out += str(key[chr(b)])
return int(long_out)
def long_to_bytes_flag(long_in):
new_map = {v: k for k, v in key.items()}
list_long_in = [int(x) for x in str(long_in)]
str_out = ''
i = 0
while i < len(list_long_in):
if list_long_in[i] < 7:
str_out += new_map[list_long_in[i]]
else:
str_out += new_map[int(str(list_long_in[i]) + str(list_long_in[i + 1]))]
i += 1
i += 1
return str_out.encode("utf_8")
def diffie_hellman(A, g, b, p):
B = pow(g,b,p)
s = pow(A,b,p)
message = b'My totally secure message to Alice'
password = long_to_bytes(s)
my_hmac = new(key=password, msg = message, digestmod=sha256)
return str(bytes_to_long(my_hmac.digest())), B
@app.route("/")
def home():
old_session = request.cookies.get('session')
A = request.args.get('A', type = int)
if not isinstance(A, int):
return "Missing required query string parameter: A"
if not old_session:
p, q, g = generate()
session = {"id": uuid4().hex, 'p': p, 'q': q, 'g': g, "attempts": 0}
sessions[session['id']] = session
else:
if old_session not in sessions.keys():
return "Invalid session"
if not sessions[old_session]['attempts'] < 7:
sessions.pop(old_session)
return "Too many attempts"
p, q, g, attempts = sessions[old_session]['p'], sessions[old_session]['q'], sessions[old_session]['g'], sessions[old_session]['attempts']
session = {"id": old_session, 'p': p, 'q': q, 'g': g, "attempts": attempts + 1}
sessions[old_session] = session
if b > q:
return "Connection reset"
try:
hmac, B = diffie_hellman(int(A), g, b, p)
res = jsonify({"hmac": hmac, "B": B, "p": p, "q": q, "g": g})
res.set_cookie('session', session['id'])
return res
except:
return "Internal error. A was: " + str(A)
f = open("flag.txt", "r")
flag = f.read().strip()
b = bytes_to_long_flag(flag.encode('utf-8'))
if __name__ == "__main__":
app.run(port=54321)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2022/crypto/CPA-SecureDiffie–Hellman/key_exchange.py | ctfs/WolvCTF/2022/crypto/CPA-SecureDiffie–Hellman/key_exchange.py | from flask import Flask
from flask import request
from Crypto.Util.number import bytes_to_long, long_to_bytes
from hashlib import sha256
from hmac import new
app = Flask(__name__)
# ephemerals live on as seeds!
# wrap flag in wsc{}
# Someone has cracked sha-256 and has started impersonating me to Alice on the internet!
# Here's the oracle they proved sha-256 is forgeable on
# Guess the internet will just have to move on to sha-512 or more likely sha-3
key = {
'0' : 0 , '1' : 1 , '2' : 2 , '3' : 3 , '4' : 4 , '5' : 5 , '6' : 6 ,
'a' : 70, 'b' : 71, 'c' : 72, 'd' : 73, 'e' : 74, 'f' : 75, 'g' : 76, 'h' : 77, 'i' : 78, 'j' : 79,
'k' : 80, 'l' : 81, 'm' : 82, 'n' : 83, 'o' : 84, 'p' : 85, 'q' : 86, 'r' : 87, 's' : 88, 't' : 89,
'u' : 90, 'v' : 91, 'w' : 92, 'x' : 93, 'y' : 94, 'z' : 95, '_' : 96, '#' : 97, '$' : 98, '!' : 99,
}
def bytes_to_long_flag(bytes_in):
long_out = ''
for b in bytes_in:
long_out += str(key[chr(b)])
return int(long_out)
def long_to_bytes_flag(long_in):
new_map = {v: k for k, v in key.items()}
list_long_in = [int(x) for x in str(long_in)]
str_out = ''
i = 0
while i < len(list_long_in):
if list_long_in[i] < 7:
str_out += new_map[list_long_in[i]]
else:
str_out += new_map[int(str(list_long_in[i]) + str(list_long_in[i + 1]))]
i += 1
i += 1
return str_out.encode("utf_8")
def diffie_hellman(A):
p = 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151
g = 5016207480195436608185086499540165384974370357935113494710347988666301733433042648065896850128295520758870894508726377746919372737683286439372142539002903041
B = pow(g,b,p) #unused in our protocal
s = pow(A,b,p)
message = b'My totally secure message to Alice'
password = long_to_bytes(s)
my_hmac = new(key=password, msg = message, digestmod=sha256)
return str(bytes_to_long(my_hmac.digest()))
@app.route("/")
def home():
A = request.args.get('A')
if not A:
return "Missing required query string parameter: A"
else:
try:
result = diffie_hellman(int(A))
return result
except:
return "A must be an integer: " + A;
f = open("flag.txt", "r")
flag = f.read()
b = bytes_to_long_flag(flag.encode('utf-8'))
if __name__ == "__main__":
app.run(port=54321)
# Someone mentioned CPA-Security to me... No idea what that has to do with this
# All the homies hate 521 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2022/crypto/EAV-SecureDiffie–Hellman/key_exchange.py | ctfs/WolvCTF/2022/crypto/EAV-SecureDiffie–Hellman/key_exchange.py | from Crypto.Util.number import bytes_to_long
# I love making homespun cryptographic schemes!
def diffie_hellman():
f = open("flag.txt", "r")
flag = f.read()
a = bytes_to_long(flag.encode('utf-8'))
p = 320907854534300658334827579113595683489
g = 3
A = pow(g,a,p) #236498462734017891143727364481546318401
if __name__ == "__main__":
diffie_hellman()
# EAV-Secure? What's that? | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WolvCTF/2022/crypto/RSAFrustration/RSA_Frustration_-_encrypt.py | ctfs/WolvCTF/2022/crypto/RSAFrustration/RSA_Frustration_-_encrypt.py | from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes
def encrypt(numToEncrypt):
def getPrimeCustom(bitLength, e):
while True:
i = getPrime(bitLength)
if (i-1) % e**2 == 0:
return i
global e
global C
bitLength = ((len(bin(numToEncrypt)) - 2) // 2) + 9
e = 113
p = getPrimeCustom(bitLength, e)
q = getPrimeCustom(bitLength, e)
N = p * q
print(f"N = {N}")
C = pow(numToEncrypt, e, N)
return C
msg = b"wsc{????????????????????}"
numToEncrypt = bytes_to_long(msg)
# maybe if I keep encrypting it will fix itself???
# surely it won't make it worse
encryptedNum = encrypt(numToEncrypt)
for x in range(26):
encryptedNum = encrypt(encryptedNum)
print(f"e = {e}")
print(f"C = {C}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DarkCTF/2020/pynotes/share/template.py | ctfs/DarkCTF/2020/pynotes/share/template.py | #!/usr/bin/python3
import sys
import os
import binascii
import re
import subprocess
import signal
def handler(x, y):
sys.exit(-1)
signal.signal(signal.SIGALRM, handler)
signal.alarm(30)
def gen_filename():
return '/tmp/' + binascii.hexlify(os.urandom(16)).decode('utf-8')
def is_bad_str(code):
code = code.lower()
# I don't like these words :)
for s in ['__', 'module', 'class', 'code', 'base', 'globals', 'exec', 'eval', 'os', 'import', 'mro', 'attr', 'sys']:
if s in code:
return True
return False
def is_bad(code):
return is_bad_str(code)
place_holder = '/** code **/'
template_file = 'pppp.py'
EOF = 'DARKCTF'
MAX_SIZE = 10000
def main():
print(f'Give me the source code(size < {MAX_SIZE}). EOF word is `{EOF}\'')
sys.stdout.flush()
size = 0
code = ''
while True:
s = sys.stdin.readline()
size += len(s)
if size > MAX_SIZE:
print('too long')
sys.stdout.flush()
return False
idx = s.find(EOF)
if idx < 0:
code += s
else:
code += s[:idx]
break
if is_bad(code):
print('bad code')
sys.stdout.flush()
return False
with open(template_file, 'r') as f:
template = f.read()
filename = gen_filename() + ".py"
with open(filename, 'w') as f:
f.write(template.replace(place_holder, code))
os.system('cp _note.cpython-36m-x86_64-linux-gnu.so /tmp/')
os.system(f'./python3 {filename}')
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DarkCTF/2020/pynotes/share/pppp.py | ctfs/DarkCTF/2020/pynotes/share/pppp.py | from _note import *
from sys import modules
del modules['os']
keys = list(__builtins__.__dict__.keys())
for k in keys:
# present for you
if k not in ['int', 'id', 'print', 'range', 'hex', 'bytearray', 'bytes']:
del __builtins__.__dict__[k]
/** code **/
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/misc/As_a_programmer/code_RSA.py | ctfs/NewYear/2024/misc/As_a_programmer/code_RSA.py | from Crypto.Util.number import getPrime , bytes_to_long , GCD
import random
random.seed()
flag = b'grodno{fake_flag}'
KEY_SIZE = 512
RSA_E = 3
def gen_RSA_params(N, e):
while True:
p, q = getPrime(N), getPrime(N)
if GCD(e, (p - 1) * (q - 1)) == 1: break
n = p * q
check(p, q, n)
return (p, q, n)
def check(p, q, n):
a_ = random.randint(1, 100000)
b_ = random.randint(1, 100000)
c_ = random.randint(1, 100000)
d_ = random.randint(1, 100000)
s = pow_m(p, pow_m(q, a_, c_ * (p - 1) * (q - 1)), n)
t = pow_m(q, pow_m(p, b_, d_ * (p - 1) * (q - 1)), n)
result = s + t
print(f"s = {s}")
print(f"t = {t}")
print(f"result = {result}")
def pow_m(base, degree, module):
degree = bin(degree)[2:]
r = 1
for i in range(len(degree) - 1, -1, -1):
r = (r * base ** int(degree[i])) % module
base = (base ** 2) % module
return r
dp, q, n = gen_RSA_params(KEY_SIZE, RSA_E)
m = bytes_to_long(flag)
c = pow(m, RSA_E, n)
print(f"e = {RSA_E}")
print(f"n = {n}")
print(f"c = {c}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/code/Random_cipher/code_terror.py | ctfs/NewYear/2024/code/Random_cipher/code_terror.py | from random import randint
def encrypt(text):
key = randint(1, 2 * len(text))
print (ord(text[0]), key)
result = []
for c in text:
result.append(ord(c) + (ord(c) % key))
key = key + 1
return result | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/code/Negative_hash/-PolynomialHash.py | ctfs/NewYear/2024/code/Negative_hash/-PolynomialHash.py | def PolynomialHash(string, a):
result = 0
l = len(string)
for i in range(l):
result += ord(string[i]) * ((-a) ** (l - i - 1))
return result
flag = "****************"
PolynomialHash(flag, 100) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/code/Polynomial_hash/PolynomialHash.py | ctfs/NewYear/2024/code/Polynomial_hash/PolynomialHash.py | def PolynomialHash(s, a):
return sum([ord(s[i]) * pow(a, len(s)-i-1) for i in range(len(s))])
flag = "***********"
PolynomialHash(flag, 256)
#35201194166317999524907401661096042001277 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/code/assert/crackme.py | ctfs/NewYear/2024/code/assert/crackme.py | # uncompyle6 version 3.5.0
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.5 (default, Nov 16 2020, 22:23:17)
# [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
# Embedded file name: crackme.py
# Compiled at: 2011-09-19 04:54:37
import sys, types
assert len(sys.argv) == 10
a, b, c, d, e, f, g, h, i = [ int(x) for x in sys.argv[1:] ]
assert b == c
assert c == g
assert g == h
assert g + b + c == 0
codestr = ('').join(chr(x) for x in [a, b, c, d, e, f, g, h, i])
result = ''
assert 3 * a + 12 * d + e + 4 * f + 6 * i == 2194
assert -6 * a + 2 * d - 4 * e - f + 9 * i == -243
assert a + 6 * d + 2 * e + 7 * f + 11 * i == 2307
assert 5 * a - 2 * d - 7 * e + 76 * f + 8 * i == 8238
assert 2 * a - 2 * d - 2 * e - 2 * f + 2 * i == -72
def xorc(a, b):
return chr(ord(a) ^ ord(b))
def xorstr(a, b):
return ('').join([ xorc(a[(i % len(a))], c) for i, c in enumerate(b) ])
result += xorstr(codestr, '\x1bro#&\x0b{t;\x19_44;Wrt\x0cLp35|\x100r\x0c\x15s_1{\x16y_&\x0f3f2$;wh`\x12_dt*\x11gg:\x12g_7:Tgrg\x11s}')
def getSolutionAsParameterAndPrint(myChallengeSolution):
print (0)
recycled_code = getSolutionAsParameterAndPrint.func_code
new_code = types.CodeType(recycled_code.co_argcount, recycled_code.co_nlocals, recycled_code.co_stacksize, recycled_code.co_flags, codestr, recycled_code.co_consts, recycled_code.co_names, recycled_code.co_varnames, recycled_code.co_filename, recycled_code.co_name, recycled_code.co_firstlineno, recycled_code.co_lnotab, recycled_code.co_freevars, recycled_code.co_cellvars)
new_fun = types.FunctionType(new_code, globals(), 'keepOnDigging', getSolutionAsParameterAndPrint.func_defaults)
new_fun(result) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/crypto/AND_encryption/AND-encryption.py | ctfs/NewYear/2024/crypto/AND_encryption/AND-encryption.py | #! /usr/bin/python3
from random import randint
def and_encr(key):
mess = [randint(32, 127) for x in range(0,len(key))]
return "".join([hex(ord(k) & m)[2:].zfill(2) for (k,m) in zip(key, mess)])
flag = 'fake-flag'
while True:
while True:
choise = input("1. Прислать шифр\n2. Проверить флаг\nВаш выбор: ")
if choise in ['1','2']:
break
if choise == '1':
print (and_encr(flag))
else:
if flag == input("Flag: "):
print (f"Правильно !\nВаш флаг: {flag})
break
else:
print (f"Ошибка, сэр !")
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/crypto/Gift_from_Cyber_Santa_Claus/Gift_from_Santa.py | ctfs/NewYear/2024/crypto/Gift_from_Cyber_Santa_Claus/Gift_from_Santa.py | import random
from math import gcd
def _prime_factors(n): # Returns a list that includes prime factors with their repetitions
prime_factors = lambda n: [i for i in range(2, n+1) if n%i == 0 and all(i % j != 0 for j in range(2, int(i**0.5)+1))]
factors = []
while n > 1:
for factor in prime_factors(n):
factors.append(factor)
n //= factor
return factors
def lcm(a, b): # Least common multiple
return abs(a*b) // gcd(a, b)
def create_initial_seed(primes):
res = 0
for p1 in primes:
for p2 in primes:
if p1 <= p2:
res = res ^ lcm(p1, p2)
return res
# Read random integer numbers from [1000, 100000]
numbers = map(int, list(open('From _bag_of_Santa.txt').read().split()))
primes_set = set()
initial_value = []
# Create Initial seed
for n in numbers:
primes = _prime_factors(n)
for p in primes:
primes_set.add(p)
initial_value.append(create_initial_seed(primes))
random.shuffle(initial_value)
iv = initial_value[0] ** 3 # big enough to fail brute force on seed
random.seed(iv)
# Generate cipher with random key
flag = "grodno{fake_flag}" # This is message
enc = [ord(flag[i]) ^ random.randint(0, 255) for i in range(len(flag))]
with open('output_for_Santa.txt', 'w') as file:
print(primes_set, file=file)
print(enc, file=file) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/crypto/39_Bobs_friends/39_letters.py | ctfs/NewYear/2024/crypto/39_Bobs_friends/39_letters.py | from Crypto.Util.number import getPrime, bytes_to_long
flag = b'grodno{fake_flag}'
m = bytes_to_long(flag)
e = 39
n = [getPrime(1024) * getPrime(1024) for i in range(e)]
c = [pow(m, e, n[i]) for i in range(e)]
open("all_letters.txt", 'w').write(f"e = {e}\nc = {c}\nn = {n}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/crypto/Like_a_simple_RSA/Asim_en.py | ctfs/NewYear/2024/crypto/Like_a_simple_RSA/Asim_en.py | from random import randint
def gen_key():
a, b, c, d = randint(3 * 64), randint(4 * 64), randint(5 * 64), randint(6 * 64)
e = a * b - 1
f = c * e + a + e
g = d * e + b * f
h = c * d * e + a * d + c * b + g * g
public_key = (h, f)
private_key = g
key = (public_key, private_key)
return key
def encrypt(m, public_key):
c = (m * public_key[1]) % public_key[0]
return c
def decrypt(c, public_key, private_key):
m = (c * private_key) % public_key[0]
return m | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/crypto/Highly_ambiguous_RSA/Triple_ambiguous_RSA.py | ctfs/NewYear/2024/crypto/Highly_ambiguous_RSA/Triple_ambiguous_RSA.py | from Crypto.Util.number import bytes_to_long
n1 = 1852892720062887225761965098961519184717028045747184821229381416690649150175077469195015762879827
e1 = 18712
n2 = 1684786560529453911475754845780536300328197792513126663487817526891350560429162837595257498214731
e2 = 17656
n3 = 1476397917727380110001203955119376017350831987887155549202221944834157018381937476166521375696257
e3 = 19407
c = 611696235674033015624831923566847674953519491228623379258607782032635868791588102056975818050929
flag = b'grodno{REDACTED}'
m = bytes_to_long(flag)
c = pow(m, e1, n1)
c = pow(c, e2, n2)
c = pow(c, e3, n3)
print (f"n1 = {n1}")
print (f"e1 = {e1}")
print (f"n2 = {n2}")
print (f"e2 = {e2}")
print (f"n3 = {n3}")
print (f"e3 = {e3}")
print (f"c = {c}")
# Output
n1 = 1852892720062887225761965098961519184717028045747184821229381416690649150175077469195015762879827
e1 = 18712
n2 = 1684786560529453911475754845780536300328197792513126663487817526891350560429162837595257498214731
e2 = 17656
n3 = 1476397917727380110001203955119376017350831987887155549202221944834157018381937476166521375696257
e3 = 19407
c = 611696235674033015624831923566847674953519491228623379258607782032635868791588102056975818050929
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewYear/2024/crypto/Tabular_integral/code-1_RSA.py | ctfs/NewYear/2024/crypto/Tabular_integral/code-1_RSA.py | from Crypto.Util.number import getPrime , bytes_to_long , GCD
import random
random.seed()
flag = b'grodno{fake_flag}'
KEY_SIZE = 512
RSA_E = 65535
def gen_RSA_params(N, e):
while True:
p, q = getPrime(N), getPrime(N)
if GCD(e, (p - 1) * (q - 1)) == 1: break
n = p * q
check(p, q, n)
return (p, q, n)
def check(p, q, n):
a_ = random.randint(1, 100000)
b_ = random.randint(1, 100000)
c_ = random.randint(1, 100000)
d_ = random.randint(1, 100000)
s = pow_m(p, pow_m(q, a_, c_ * (p - 1) * (q - 1)), n)
t = pow_m(q, pow_m(p, b_, d_ * (p - 1) * (q - 1)), n)
result = s + t
print(f"result = {result}")
def pow_m(base, degree, module):
degree = bin(degree)[2:]
r = 1
for i in range(len(degree) - 1, -1, -1):
r = (r * base ** int(degree[i])) % module
base = (base ** 2) % module
return r
dp, q, n = gen_RSA_params(KEY_SIZE, RSA_E)
m = bytes_to_long(flag)
c = pow(m, RSA_E, n)
print(f"e = {RSA_E}")
print(f"n = {n}")
print(f"c = {c}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2024/crypto/flip/main.py | ctfs/TetCTF/2024/crypto/flip/main.py | # Please ensure that you solved the challenge properly at the local.
# If things do not run smoothly, you generally won't be allowed to make another attempt.
from secret.network_util import check_client, ban_client
import sys
import os
import subprocess
import tempfile
OFFSET_PLAINTEXT = 0x4010
OFFSET_KEY = 0x4020
def main():
if not check_client():
return
key = os.urandom(16)
with open("encrypt", "rb") as f:
content = bytearray(f.read())
# input format: hex(plaintext) i j
try:
plaintext_hex, i_str, j_str = input().split()
pt = bytes.fromhex(plaintext_hex)
assert len(pt) == 16
i = int(i_str)
assert 0 <= i < len(content)
j = int(j_str)
assert 0 <= j < 8
except Exception as err:
print(err, file=sys.stderr)
# ban_client()
return
# update key, plaintext, and inject the fault
content[OFFSET_KEY:OFFSET_KEY + 16] = key
content[OFFSET_PLAINTEXT:OFFSET_PLAINTEXT + 16] = pt
content[i] ^= (1 << j)
tmpfile = tempfile.NamedTemporaryFile(delete=True)
with open(tmpfile.name, "wb") as f:
f.write(content)
os.chmod(tmpfile.name, 0o775)
tmpfile.file.close()
# execute the modified binary
try:
ciphertext = subprocess.check_output(tmpfile.name, timeout=1.0)
print(ciphertext.hex())
except Exception as err:
print(err, file=sys.stderr)
ban_client()
return
# please guess the AES key
if bytes.fromhex(input()) == key:
with open("secret/flag.txt") as f:
print(f.read())
from datetime import datetime
print(datetime.now(), plaintext_hex, i, j, file=sys.stderr)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2024/web/X_Et_Et/challenge/bot/utils.py | ctfs/TetCTF/2024/web/X_Et_Et/challenge/bot/utils.py | from uuid import UUID
def is_valid_uuid(uuid_to_test, version=4):
try:
uuid_obj = UUID(uuid_to_test, version=version)
except ValueError:
return False
return str(uuid_obj) == uuid_to_test | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2024/web/X_Et_Et/challenge/bot/app.py | ctfs/TetCTF/2024/web/X_Et_Et/challenge/bot/app.py | from flask import Flask, request, render_template
import os
import subprocess
from utils import *
import base64
app = Flask(__name__)
PORT = int(os.getenv('PORT', '5001'))
BIND_ADDR = os.getenv('BIND_ADDR', '0.0.0.0')
app.config["LOG_TYPE"] = os.environ.get("LOG_TYPE", "stream")
app.config["LOG_LEVEL"] = os.environ.get("LOG_LEVEL", "INFO")
@app.route('/', methods=['POST'])
def add_task():
id = request.form.get('id')
title = request.form.get('title')
content = request.form.get('content')
msg = 'Error! Please notice admin'
print(title,content)
# Check valid id
if is_valid_uuid(id):
command = f"rm -rf /tmp/.X99-lock;export id='{base64.b64encode(id.encode('utf-8')).decode('utf-8')}'; export title='{base64.b64encode(title.encode('utf-8')).decode('utf-8')}' ;export content='{base64.b64encode(content.encode('utf-8')).decode('utf-8')}';/bin/sh /app/app/run.sh"
print('[+] Executing: {}'.format(command))
os.system(command)
print('[+] Done: {}'.format(command))
else:
msg = 'Invalid Report Id'
return msg
def main():
app.run(host=BIND_ADDR, port=PORT) # debug=True
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/TetCTF/2024/web/X_Et_Et/challenge/server/models.py | ctfs/TetCTF/2024/web/X_Et_Et/challenge/server/models.py | from app import db
class User(db.Model):
username = db.Column(db.String(50), primary_key=True)
password = db.Column(db.String(50))
# Define the Ticket model
class Ticket(db.Model):
id = db.Column(db.String(36), primary_key=True, unique=True)
title = db.Column(db.String(100))
new = db.Column(db.Integer)
content = db.Column(db.Text)
username = db.Column(db.String(50))
timestamp = db.Column(db.DateTime, default=db.func.current_timestamp())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2024/web/X_Et_Et/challenge/server/utils.py | ctfs/TetCTF/2024/web/X_Et_Et/challenge/server/utils.py | from uuid import UUID
import json
import requests
def is_valid_uuid(uuid_to_test, version=4):
try:
uuid_obj = UUID(uuid_to_test, version=version)
except ValueError:
return False
return str(uuid_obj) == uuid_to_test
def is_valid_captcha(secret, captcha):
if secret == "":
return True
else:
return verify(secret, captcha)
def verify(secret_key, response):
payload = {'response': response, 'secret': secret_key}
response = requests.post(
"https://www.google.com/recaptcha/api/siteverify", payload)
response_text = json.loads(response.text)
return response_text['success']
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2024/web/X_Et_Et/challenge/server/app.py | ctfs/TetCTF/2024/web/X_Et_Et/challenge/server/app.py | from utils import *
from flask import Flask, render_template, request,Response, session, redirect, url_for,jsonify
import requests
from flask_sqlalchemy import SQLAlchemy
import uuid
import os
import logging
import bleach, time
app = Flask(__name__)
app.config["LOG_TYPE"] = os.environ.get("LOG_TYPE", "stream")
app.config["LOG_LEVEL"] = os.environ.get("LOG_LEVEL", "INFO")
app.secret_key = os.environ.get('SECRET_KEY', os.urandom(32))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ticket.db'
admin_password = os.environ.get('PASSWD', uuid.uuid4().hex)
captcha_secret_key = os.environ.get('RECAPTCHA_SECRET_KEY', "")
site_key = os.environ.get('SITE_KEY', "")
csp_header_value = (
"default-src 'self'; "
"script-src 'self' ; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"font-src 'self'; "
"frame-src 'none'; "
"object-src 'none'; "
"base-uri 'self'; "
"form-action 'self'; "
"manifest-src 'self'; "
"upgrade-insecure-requests; "
"block-all-mixed-content; "
"require-sri-for script style; "
)
db = SQLAlchemy(app)
ADMIN_COOKIE = ""
class User(db.Model):
username = db.Column(db.String(50), primary_key=True)
password = db.Column(db.String(50))
# Define the Ticket model
class Ticket(db.Model):
id = db.Column(db.String(36), primary_key=True, unique=True)
title = db.Column(db.String(100))
new = db.Column(db.Integer)
content = db.Column(db.Text)
username = db.Column(db.String(50))
timestamp = db.Column(db.DateTime, default=db.func.current_timestamp())
def is_valid_ticket(id, username):
# mess = ""
if not is_valid_uuid(id):
return "Invalid ticket id"
ticket = db.session.get(Ticket, id)
if not ticket or (ticket.username != username and username != "admin"):
return "No ticket found"
return "OK"
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
data = request.form
username = data.get('username')
password = data.get('password')
if username and password:
user = User.query.filter_by(username=username).first()
print(user)
if user and password == user.password:
session['username'] = username.strip()
# Redirect to the home page or perform other actions upon successful login
return redirect(url_for('home'))
return render_template('login.html', error_message='Invalid username or password.')
else:
return render_template('login.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
data = request.form
username = data.get('username')
password = data.get('password')
error_message= "success"
if username and password:
print(User.query.filter_by(username=username).first())
if User.query.filter_by(username=username).first():
error_message = 'Username already exists. Please choose a different username.'
return render_template('signup.html', error_message=error_message)
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
else:
error_message = 'Invalid username or password.'
return render_template('signup.html', error_message=error_message)
else:
return render_template('signup.html')
@app.route('/ticket', methods=['POST'])
def post_ticket():
data = request.form
username = session.get('username')
if not username:
res = "No user found"
return render_template("home.html", error_message=res)
title = data.get('title')[:100]
content = (data.get('content'))
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
unique_filename = str(uuid.uuid4())
file_path = os.path.join("/tmp/", unique_filename+os.path.splitext(file.filename)[1])
file.save(file_path)
if not data['content'] or not data['title']:
res = "Content and Title is empty"
return render_template("home.html", error_message=res)
if username=="admin":
content = "[IMPORTANT ALERT]"+ content
else:
content = "[NOMAL ALERT]"+ content
content+=f"<br>Attachment: http://localhost/tmp/{unique_filename}"
ticket = Ticket(id=unique_filename, title=title,
content=content, username=username,new=1)
db.session.add(ticket)
db.session.commit()
return redirect(url_for(f'get_ticket', id=ticket.id))
@app.route('/ticket/<id>')
def get_ticket(id):
username = session.get('username')
if not username:
res = "No user found"
return render_template("ticket.html", error_message=res)
if not is_valid_uuid(id):
res = "Invalid ticket id"
return render_template("ticket.html", error_message=res)
ticket = db.session.get(Ticket, id)
if not ticket or (ticket.username != username and username != "admin"):
res = "No ticket found"
return render_template("ticket.html", error_message=res)
else:
ticket.new=0;
db.session.add(ticket)
return render_template("ticket.html", ticket=ticket,files=f"/tmp/{id}")
@app.route('/tmp/<id>')
def get_files(id):
if not is_valid_uuid(id):
res = "Invalid ticket id"
return jsonify({'error': res}), 400
ticket = db.session.get(Ticket, id)
if not ticket :
res = "No ticket found"
return jsonify({'error': res}), 400
else:
files = os.popen(f"cat /tmp/{id}*").read()
return jsonify(data=files),200,{'Content-Type': 'text/plain; charset=utf-8'}
@app.route('/report', methods=['POST', 'GET'])
def report():
if request.method == "POST":
username = session.get('username')
data = request.form
if not username:
res = "No user found"
return render_template("ticket.html", error_message=res)
id = data.get("id")
res = is_valid_ticket(id, username)
if res != "OK":
return render_template("ticket.html", error_message=res)
# send request to bot worker
ticket = db.session.get(Ticket, id)
r = requests.post("http://127.0.0.1:5001/",
data={"id": id, "title": bleach.clean(ticket.title),"content": bleach.clean(ticket.content) })
app.logger.info(r.text)
time.sleep(3)
return render_template("ticket.html", error_message=res)
else:
return render_template("ticket.html")
@app.route('/IsNew')
def isnew():
client_ip = request.remote_addr
print(client_ip)
if client_ip:
if client_ip == "127.0.0.1":
id = request.args.get("id")
res = is_valid_uuid(id)
if res:
ticket = db.session.get(Ticket, id)
return render_template("admin.html",ticket=ticket),200,{"Content-Security-Policy":csp_header_value}
return render_template("home.html")
else:
return redirect(url_for('login'))
@app.route('/')
def home():
username = session.get('username')
print(username)
if username:
return render_template("home.html")
else:
return redirect(url_for('login'))
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('home'))
def create_admin_user():
global admin_password
admin_username = 'admin'
admin_user = db.session.get(User, admin_username)
if not admin_user:
admin_user = User(username=admin_username, password=admin_password)
db.session.add(admin_user)
db.session.commit()
else:
admin_password = admin_user.password
with app.app_context():
db.create_all()
create_admin_user()
if __name__ == '__main__':
with app.app_context():
db.create_all()
create_admin_user()
app.run(debug=False, port=80, host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2023/crypto/toy/toy.py | ctfs/TetCTF/2023/crypto/toy/toy.py | import base64
import json
import random
import sys
import os
from Crypto.Util.number import isPrime
from Crypto.Cipher import AES
RSA_KEY_SZ = 256
AES_KEY_SZ = 128
class AuthEncryption:
def __init__(self, key: bytes):
self._rand = random.Random(key)
mask = (0b11 << (RSA_KEY_SZ // 2 - 2)) | 1
p = q = 0
while not isPrime(p):
p = self._rand.getrandbits(RSA_KEY_SZ // 2) | mask
while not isPrime(q):
q = self._rand.getrandbits(RSA_KEY_SZ // 2) | mask
self.n = p * q
assert self.n.bit_length() == RSA_KEY_SZ
self.exp = self._rand.getrandbits(RSA_KEY_SZ)
self.aes_key = self._rand.randbytes(AES_KEY_SZ // 8)
def _generate_signature(self, data: bytes) -> bytes:
msg = int.from_bytes(data, "big")
sig = pow(msg, self.exp, self.n)
return sig.to_bytes(RSA_KEY_SZ // 8, "big")
def _verify_signature(self, data: bytes, sig: bytes) -> bool:
msg = int.from_bytes(data, "big")
s = int.from_bytes(sig, "big")
if s >= self.n:
print("[warning: sig >= modulo]", end=' ')
s %= self.n
return pow(msg, self.exp, self.n) == s
def _xxcrypt(self, data: bytes) -> bytes:
aes = AES.new(self.aes_key, AES.MODE_CTR, nonce=b'\x00' * 12)
return aes.encrypt(data)
def encrypt(self, plaintext: bytes) -> bytes:
sig = self._generate_signature(plaintext)
return self._xxcrypt(plaintext + sig)
def decrypt(self, data: bytes) -> bytes:
decrypted = self._xxcrypt(data)
plaintext, sig = decrypted[:-RSA_KEY_SZ // 8], decrypted[-RSA_KEY_SZ // 8:]
assert self._verify_signature(plaintext, sig), "integrity verification failed"
return plaintext
if __name__ == '__main__':
from secret import FLAG
encryptor = AuthEncryption(os.urandom(16))
m = b'{"name": "admin", "admin": true, "issued_date": "01/01/2023"}'
assert encryptor.decrypt(encryptor.encrypt(m)) == m, "sanity check failed"
for _ in range(16000):
try:
token = encryptor.decrypt(base64.b64decode(input()))
info = json.loads(token)
if info["admin"]:
print(f"Somehow the sanity-check token is leaked, token={info}", file=sys.stderr)
print(FLAG)
else:
print(f"Hi {info['name']}")
except Exception as err:
print(err)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2023/crypto/shuffle64/shuffle64.py | ctfs/TetCTF/2023/crypto/shuffle64/shuffle64.py | import sys
from typing import List, Iterator
from bitarray import bitarray # https://pypi.org/project/bitarray/
import random
import base64
import string
ALPHABET = (string.ascii_letters + string.digits + '+/').encode()
assert len(ALPHABET) == 64
State = List[int]
def swap(arr: State, i: int, j: int):
arr[i] ^= arr[j]
arr[j] ^= arr[i]
arr[i] ^= arr[j]
def rc4_key_scheduling(key: bytes) -> State:
S = list(range(64))
j = 0
for i in range(64):
j = (j + S[i] + key[i % len(key)]) % 64
swap(S, i, j)
return S
def rc4_pseudo_random_generator(S: State) -> Iterator[int]:
i = j = 0
while True:
i = (i + 1) % 64
j = (j + S[i]) % 64
swap(S, i, j)
yield S[(S[i] + S[j]) % 64]
def shuffle(s: bytes) -> bytes:
bits = bitarray()
bits.frombytes(s)
random.shuffle(bits)
return bits.tobytes()
def xor(s1: bytes, s2: bytes) -> bytes:
assert len(s1) == len(s2)
return bytes(c1 ^ c2 for c1, c2 in zip(s1, s2))
if __name__ == '__main__':
from secret import FLAG
assert len(FLAG) % 3 == 0
random.seed(2023)
print(sys.version)
prg = rc4_pseudo_random_generator(rc4_key_scheduling(FLAG))
# RC4 has biased outputs at the beginning -> better to discard some bytes first!
[next(prg) for _ in range(2023)]
for i in range(64):
shuffled = shuffle(FLAG)
key = bytes(ALPHABET[next(prg)] for _ in range(len(FLAG) // 3 * 4))
print(xor(shuffled, base64.b64decode(key)).hex())
# Output:
# 3.10.7 (main, Nov 24 2022, 19:45:47) [GCC 12.2.0]
# af05a2ac3fa43be576a7c90a4ebfa5d9cfb98bc9a8970ffb2ead0fff9379e395d06199d5729bea
# 399d153c9f628af31d9e12d5bd8d5e0370a2e02fc45f7a84903806bac1e7e2cf15c9117b8a698e
# d461dbbd63f4543dd2e9b59927d442340afbede5796a7820d919596e8c42a086aed72b410478fe
# 41d278f4fc2e172ba8334464c5c60869f7e301f4b4175f731d0d209b0e41d64bc483f5eda239e7
# 9cd357b35f39d2b7f36b2bb019e8a446ff5fa4a38c7604fb08a5710680b77c08d13e7b1f11b864
# ea93c40265df394a4b446b7ab06a8f38ab9d78209b2ae75716a9837a992ae789a90a0f8dd1482f
# d9528ede8bea699ed4f026f2cc375a638c7ec1ab3b0a1db3257297c5cfe718b7c39821e4192ec4
# cb0d60203b6c931e4e9f16ff2cfce5e2bf921c9afc7dc555adaa8ad0e0809b85ea7949ec952d10
# c64099f22f8d259e1ff95139c24160fdba5f73ecd64853c4dbb2904f73f5b7717926daf4666dcb
# fa0a112ac36a73718ca81d3acf740e5199277ccabf453b3a76cb09dc1e282aec21fc594ff526f3
# c60fbcdb60877c0033e85a07163888798f47cc9f7ec427774971cd559a61c7342d867ce9eec6a9
# badb8981a617997dd5f45f28aa88e1578b9b000fb7efba6c62e1aed24240de90773df2d0650d6b
# a5992d87e39cf86ef49ee2d8a5817b7227abbbc698fa7b0f3df69213b4deead4920914c38820a4
# 23a3efd42bdce31830f606a753ed6a3102f5d7ae2173ccaa83adc817488ebc3a355d647984a339
# fa4c6f106e935f6ce2e8b46ca083afe6ceb40f6ec395e4de63dde75b568567a1d759a9860efbb8
# 0604703b44862b5ee8e6a24a94fc9df2764950cc20143e75811d4ca2054b9e8b27b0bd2b302920
# 2e124f3330924ee0eeb70eaa30619424cb6fa2958fff65577ddc6d32cc3435068903f9f3ba0d48
# 8163b5eab7c9dc5114a7b5e3c4be5f2d8723d903583499a3a23e09c749d9c2ccf880b657a8b66f
# 86905524dfca869789d605e046d5b50ed9f1fbefda4a6d35d7cbf87e445ea3744312c5add13059
# dcaa9d4a2146d1f206d19b091745d160e253167f94838ced661844478f5fd68bafbc85a1617d8c
# 28cb751fbb04d32fa0fa07b6f811cf2c07dfcd084439c9eed5279ff91190a38271ceebd99a029f
# 9a06cfd74f831e5b990a5c80b9ccf8a66205d3b23135fc60a23a3cd443f40c1952168b2454b80d
# 493dc7b8e1c7a7e77971c89cb623047ba1cfd8f22715a79a608a6c0211f53a6fb9e353dffb471c
# 20558dada57c6bf41db4adcb76e8786a0edf83f32754cebf400d533027b29cc6e809b7bc4f9b88
# aa20061213ffdf8c472834e82a6d619fdc4abb146b2f8fc08d698ab36d1a5dfcfb0869ae8b5ff5
# c62c9691af6c398a8122126ff8edf24e758ece54050619f0ba70436c1b11f222f72f23540f030c
# fbd8bca4e3b79a73ccf72e823e3f54d9e07e5f0035946fb1ea28e10522e5c1f447cd9ae88478b5
# acb426f38825507b32de15e4502bfaeb4198bb28262d367601af318b9fd482c2c2e9a46c4508aa
# b891b4f8231338e32911022605b02d5b4832c6ca8e3e243c4dcbb6e784e2219314fffeb8e6c86c
# 6c6a735cc72730abd0f3ab80ed766dbd042dea071798fc1da2d0f1150635a0a3a762e1629ed21e
# 52bd7994bf2de4c4de9dc6a6db8391eccffdba41c8720502dc127f4c379dc1ef0d1eb568d2f79c
# 9c41884cde75d6d059c9e3c4d259adb532be6fe720f7dedec1651164fc5cbb7bd5a62cc65042ab
# 5be48cb9203fd459fab80a2528e5e169a445ce86bf48d519446ce2ae8a675ac16c2dcf472438b8
# d265c48a575434fc247840d318e2de626da9ce5f3c6e9977572cdf2f192494ab7ddd503943b5c7
# 2dc4dbb136acba7147f3cd1224072abe56b299360ccf2eceaded59869dce5070ac95776c358564
# aeef2cabfb4f2acd681b4881270cf6e583a2127eeda90d9443d019d810903d2b423b1c5f39b16a
# ee1a4af6bf9695f7ae0b5024d230323fab2848c1f1c89f7854e03446a0d523286a64d4df06527c
# e815656072fcdf61292f6314bc6df3ded358b93ec5faa99cab55fe2470c45e9b854fb3fae236d6
# 28f0b3460ccb99ba6890adc1cc356c82999716ecb8fd62cd88fda5900393d473c01a7abcc7d295
# 07b9a78d3947be7f521a7b9e1e18f8873903469c3648cae9a8c1bf63f3f67b1e4cdb2429389680
# 5004b4bd239eb17da4ce4a35ab0d57a8464b7a586b6c999310ee9c500d91cbff1551f0642411c7
# ea6585296ef3f035f35123bdfa34ce5f9935208a9f116d78ac367e980a8afdb5374e665fb7355e
# dbfd89c269251763bb015524a6f5b3662ba7092bae521ed55c3bb8f4ddbbccee2a64c576ce7838
# b4327ebbea476d1a9761cbf87ce03f8999c1392c8fe87bf87a2af2823631d940d71c56000b30bf
# f55f487512cf947675b806b93e1e1e8dc98ccc07a86443f4b6726534d6c1215800a3db94fb8150
# 81485da4e069acf8f81326b4907c3b2a76e97af4c397f21453832d7e229706e100ec437e0aa123
# 4dfd1c8ba190ac619667e546abe851f9fe8dda2d25b75bdc372c82f445141133cfb437c8cfda8f
# 1a3c78b2ce36a2d1fc6667a7e980b03f15b7aafbc65a37e355f7a5f2b84ff1c0378da3ac9a0c8f
# 4f94d2be3b09c5f58578103de25d05baf401f03237e087ef005c3c8bfd03bae5a0bf80981d9836
# 800113bf74c97f5c17aff0126ba0737f3d0e339d761a002509097893f9f34814ee094a8b385cdb
# 7f202ff28a795b61a57ee08dcbad0a78471b6a20f02ef4ce5ee2be1f0d47da51f31d0dc4659183
# 3dab75b57e1a12bc4a47a16d818c4ec038e4c84942a4b8dabaade1fe4b17457a4b70921927811b
# 5d4bf5108126870c1b82a0f5cd0f39d2ac3185b7b24589bbfb33510a0bab57946146a33a7b7d00
# e97e73d3a043bb8eca4b1899bf701218ade5fe50b4ded86d7f801ed23be02565fee8035305773f
# d726e1c17ddfd8302b6d113172864ffb9a7dc061c442f388a61f3bf9fd184ebb45888752e06f9c
# 189984469c2940cd49007eaa8633b0850ac895f9baa257b7052f9f3ee5fd378e719370f16c58a7
# d5572c192699e2548bcb84029644b6aefab1fe63ed83cb4ebe5f97c4335a863a0f060af688ac09
# 2da13de259f28cb87e08d78d9ac3e17dbfbca9cc0a44012795e341d794d60979beb0f3ca38c9d9
# c8cb809009d57524df86c4bea34d3a0763c8c6b359fde792fead665a135d7e1c9c50b3f5cbbf8a
# 62f49752e696eac2ef091880069915d7588c440d790757cd475f8c7f9674f0186ba7ccab6aaf4e
# 57ac751d3e8cad6303971170e50bf905a652e39cb5dc62c0d3015e3c62406970613248f642aa03
# da6c84c73d1232df50ca09fe6060aaec2d56d02b64b9c7e73684a1cc2edd7395d7856b0b8b5d9b
# 4249f329b49b8d994ed26be3c00c49e81517a855fac3d682e07e753a8334e9a65a87bd797f9337
# 2629093413e7dc356eace3fb317306e849b55cd40972699d76dc1ad7c02766a354b9c67a7b464b
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2023/crypto/shuffle128/shuffle128.py | ctfs/TetCTF/2023/crypto/shuffle128/shuffle128.py | import sys
from typing import List, Iterator
from bitarray import bitarray # https://pypi.org/project/bitarray/
import random
State = List[int]
def swap(arr: State, i: int, j: int):
arr[i] ^= arr[j]
arr[j] ^= arr[i]
arr[i] ^= arr[j]
def rc4_key_scheduling(key: bytes) -> State:
S = list(range(128))
j = 0
for i in range(128):
j = (j + S[i] + key[i % len(key)]) % 128
swap(S, i, j)
return S
def rc4_pseudo_random_generator(S: State) -> Iterator[int]:
i = j = 0
while True:
i = (i + 1) % 128
j = (j + S[i]) % 128
swap(S, i, j)
yield S[(S[i] + S[j]) % 128]
def shuffle(s: bytes) -> bytes:
bits = bitarray()
bits.frombytes(s)
random.shuffle(bits)
return bits.tobytes()
def xor(s1: bytes, s2: bytes) -> bytes:
assert len(s1) == len(s2)
return bytes(c1 ^ c2 for c1, c2 in zip(s1, s2))
if __name__ == '__main__':
from secret import FLAG
random.seed(2023)
print(sys.version)
prg = rc4_pseudo_random_generator(rc4_key_scheduling(FLAG))
for _ in range(64):
shuffled = shuffle(FLAG)
key = bytes(next(prg) for _ in range(len(FLAG)))
print(xor(shuffled, key).hex())
# Output
# 3.10.7 (main, Nov 24 2022, 19:45:47) [GCC 12.2.0]
# 7dfdf6eba4da43bf7ca6eb64d3fbaac5e764b2c8e66e1f2a30e3b9e95b2ef48b28f105cdfc
# 3353e19ed6a3ecad7716831b8cc149ad3a1990c8f4682c434d1b7f417e7df9e9ca0743fc3a
# 2e15e68721c7773a920d9622cbad21b2d48e00358b1107b300ba19c3a48291dc1579eaf4f4
# e0f6b4e61390ce8d1eab002af797eb022c58a6576ef55c78b917268b9fe4d3f45dfc7d5dc3
# de11f01e825a69e5b1e004db1f79974ca9e42a2b0c0197dcb322f5a0e43cf7ddfdb529699d
# 976dbf67bf2f67fd947c69696c5ef5bb9186b8031d279165a5fcd1f6ac9d7f668b847ecfc0
# 01f123b89f75d3ab5f744caa4dd892eac598a0b1413cc0abf93509b2bc254a5714fd979f7a
# 488b3d4d110f2dca864f6589a58033cc23ca3618db8ce59f398b7b9a6dfd93220e1cd02538
# 6b92f7e54e6406b2d7d1176f5604e22cf4c6710ff35fa4cf7d33a7d1855a7f868da8713faa
# f9302dccf5c000ef69c2440fbe22b7eaeb5a95483dda09a0b0414e297ad81fb64fabc60025
# c9b5dcf6031051d3433ddc358f7e18b3f7cec58b37bace17f2fd1e39b1cac64fbfcdbff2aa
# bddac6c00310a5c80cb73d640a1b0592ed5d99984971a085941e7ea8e2fd0e86aaa1b7098f
# 2ac7cdeb9e7eeb5abad2b4ed1238de39cb17aa4f4d8827ebd36d4a99acb9fb4e44cd365186
# b38ed3a76f5751faaca88fbae7ef53a6a4baa4f29b4bca0ef782b373969d3df62d9c276d69
# 20f40b4267ae37f994dac8fccbb652d29abce709dc9f52223ddebe441899edfb8dc3a31a5d
# c9116855c08f1d04cbe6d86d0e9523c564fd3dd8bb79f7898ea7e624aba832e6530ad1231c
# b388f35a0f2009326bf66170156e57a36eea83285698fcdf2ba1fbbad199dc9d7860158d5e
# 1f8c81249a0428cd781494ada971c49e1cd7121af374ecc70d902ad0f4f736e4ef23f61fc9
# b70d877d5ff8c38096faecb1de2df31ce467372c09c66c54b8e122123b539966937bb94d52
# 72951dcfda3601c762b4ea5119e40e93bbe7a595a35db985cb990f3bbcc74ddc7157f0baff
# ca0532f7df0239d0fe60e9a62852384f6cce737884808134fb1960e84803fb6ddc144df3c9
# 78f35e7e26df365e213787a3885ca11c76d14fb998d4a440826b2d8adaa5fe85065c9e9c0d
# f3110f509bd39e5ead882e85ccb31906809a0c29e33a79f0b3229e671dba1353c89968c4a4
# 2ac15e7a5dcc821c58ac08d526e5a350ef994bb485fc1c916f59e366e6f7e7ddc76b4a0cae
# 381a2afbc6aa95643248d8dd39c44fd7090746af9fa3f3c4f70ba56298d6ca1b36b7d19ec8
# b098dfffe1cd19019ba9c472f6f966964352a958eda8707553021870ba51c9a0b573a59f99
# 02578a8b58c1e9c9d5f4321e0b8eb66922905ec2dfd3bf1a6ef583fcce8846243cf6c609d9
# 93efb1acf6b268c5a79746a28c64adbbbc81924991e13aa971d64f4087c87650ebb6309daa
# 9fcbff37a9919d676e6ce86d9bae8f75376b1a7a76de304c622fe163ea7549a8dcccb095f7
# ad25c09cdcc768b53a519daf6f1a0861b4c9530cc9d0cf82fbf7c9f5a9acc2346d611a21d0
# 08aee3c019e664d88f3f1147c4f52d33f2f4ab9fea176625f24a14d517a1d59d338e5bf0aa
# 479de7e5e8e7841382bb7c9c844f7f8d900979bd360c6d84dc69bd17e7f4ced202afce5964
# 65c43c740e68be4ac64c559f09b461904be78fe5f5eaa6f78afb23a1d9c12ecf1d14a287a3
# 90063ef6a3b48091f514f1b87dc3ef40942989648043df1dda7d1221c0efea863f69f2fba6
# e4c2976ec29fec9cc3d04ec5f4dde4e282886be0c5ee471ccb8cd201558adb759375c27d78
# 1ec9458af0857b6f437ee5d72de707eb6d38df96a830bb53775667f9722a46869e0954b5ad
# 5de6f6df232cc29f3fcaac177f323ecfd99732e7559f9d6ffdd706e387bcc23127891be4e1
# 7df2884288490b19fd7d20c746508c3ee8e77706c549ba5a07bf9cc183ede90e5cdd6cc59b
# 6ebc5d2caff2d0fc8afb538ea990f4289f716375834a67966dc6eba35b7559726826c23bd4
# e6bdfbfe7f094d6ecfdf76433cfc3c64c5041ad8aeaf84ba5c8473b24d836f332e8e41eabe
# 6b845fefb8e5fe2253600c137047ee029a1bab28e9b45eda71597169148593938049092ee2
# 1172b4a57311da2ff968e1071c4eff0bd22a333cfdc8a6fdef41a4b98f69620152bbeb60b5
# 5a788ee6a476eaaa3f581eaebc2589efa640ac37fc5faa4f3591b7db58234dd8fb9743192d
# 07d49bf8af3cf3ac77db932a41b81d61736b7e8f5bb656b2a9637f57b7871c1297bf5e3b14
# 94d1d09e9c3d024538c4e5fedafbf5aed564d9998dec700647f704115f281efe74aefc0231
# b11b4ff19b77cd69f1881e5401c6e56a9bbf2e88bb443b3340de8d01c4768c6efa34233b35
# dfc7edc0fa6232d7df18717c9dec7631295a035afdeeea7e2dfaec3518e58c8189f65dd52f
# 5490e892fca7f4be4312ad69b1eed46e11cb94bf8bafd2ef725e77fd9620ba980fa1d46563
# b9066eb49cb42ecfdcd9f7713e0feddb920043908df127cf35386df3b4bce6fab3c6a3e89f
# 8c51507ea79ffb2914436f8c9fa39501d89b8f9446cbe2fcfb0bada4886ff76b20ce1e29f3
# 6df94fc313b82da575073aeb54c35e5d3ff0c9dc7032cbffcc92b47b2fead75610d6157bca
# b92cf23e538fc6b3d1c0e28dd81f3c2a58d890bf323da321a39c9fb601caee4bcc1ccc9abd
# 0cc0985f966eb484c5f26b9bb8821dabf3b88d3471b55c6351a43fde32428519241a0ddd76
# 78cf7e7bf1ffa53812d1c9b47fc23852b2fcd318f7ea21dba12ad3a1d4f38e2ba1a5116aa9
# e35e377f7972b49fbb82a42f90443ca77adb678fa278bf93046c8ec2bc05cb2155d5b506d6
# 3bc4ffa6eb16c6da6c40d78b132131092bc8f0696a81e14deca5018daea56c6678befbc1f8
# 138d167661180fc7b7c52fa821c518a29d41c5a73aee9969f74b096cff8fca7ead4f5affe9
# 3784f8b584545b1ef09aa3815182776966eb9d4758f25ae89550aee3916dce6f40d29c79ee
# 09913e8ed1778c95cbac302c86cc4ba5ad8b5fe113c78352d00979e84dcd10c3ecd036fba0
# d1ed85304ea4a3e03233544efb85017c9cd1d3259d959acc0f0dbdaece9ed668d937d52309
# e6b89393cfd0e888c8dce582495d216760eb1a8032103351d15c8033a46aae338a11ac99ee
# 92683cb1cb9f24a7925395f54be8b0e520ffd5afbc80c11256e33324bf2509a1c9b64f46dc
# 0b7e5204fba4ceec74ee7b35417ecb88fa8a74c6575bb6de8f15f1257b6e02a42e4b56dff0
# 49d609e06cb04aa787ebe99d741d4b60b909a00c0de6faecbf4c6d21559495a7c67060625d
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2023/web/NewYearBot/main.py | ctfs/TetCTF/2023/web/NewYearBot/main.py | from flask import Flask, request
import re, random, os
app = Flask(__name__)
FL4G = os.environ.get('secret_flag')
fail = "???<br><img src='https://i.imgur.com/mUfnGmL.png' width='20%' />"
NewYearCategoryList = ["NewYearCommonList", "NewYearHealthList", "NewYearFamilyList", "NewYearWealthList"]
NewYearCommonList = ["Chúc Mừng Năm Mới!", "Happy New Year!", "Cheers to a new year and another chance for us to get it right!", "Let's make 2023 our best year yet.", "Năm mới Vui Vẻ", "New year! New Me!"]
NewYearHealthList = ["Sức Khoẻ Dồi Dào!", "Wishing you and yours health and prosperity in the new year", "May the new year bring you peace", "Joy, and happiness!", "Tết An Lành"]
NewYearFamilyList = ["Gia Đình Hạnh Phúc!", "Hoping that the new year will bring you and your family a year full of joy and serenity", "Together! Forever!", "Best wishes for your family"]
NewYearWealthList = ["Năm Mới Phát Tài!", "Have a sparkling New Year!", "Here's hoping you make the most of 2023!", "May the new year bless you with health, wealth, and happiness.", "An Khang Thịnh Vượng"]
# random greeting
def random_greet(s):
return eval("%s[random.randint(0,len(%s)-1)]" % (s, s))+"</center>"
def botValidator(s):
# Number only!
for c in s:
if (57 < ord(c) < 123):
return False
# The number should only within length of greeting list.
n = "".join(x for x in re.findall(r'\d+', s))
if n.isnumeric():
ev = "max("
for gl in NewYearCategoryList:
ev += "len(%s)," % gl
l = eval(ev[:-1]+")")
if int(n) > (l-1):
return False
return True
@app.route('/', methods=['GET', 'POST'])
def greeting():
bot = ""
css = """
<br><br>
<center>
<strong><font size=5 color='purple'>Get New Year Quotes From Our New Year Bot!</font></strong>
<br>_[<img src="https://i.imgur.com/uYBBhWn.gif" width="5%" />]_
</center>
<style>
.centered {
position: fixed; /* or absolute */
top: 25%;
left: 35%;
}
</style>
"""
front = """
<form action="/" method="POST" >
<select name="type">
<option value="greeting_all">All</option>
<option value="NewYearCommonList">Common</option>
<option value="NewYearHealthList">Health</option>
<option value="NewYearFamilyList">Family</option>
<option value="NewYearWealthList">Wealth</option>
</select>
<input type="text" hidden name="number" value="%s" />
<input type="submit" value="Ask" /><br>
</form>
"""%random.randint(0,3)
greeting = ""
try:
debug = request.args.get("debug")
if request.method == 'POST':
greetType = request.form["type"]
greetNumber = request.form["number"]
if greetType == "greeting_all":
greeting = random_greet(random.choice(NewYearCategoryList))
else:
try:
if greetType != None and greetNumber != None:
greetNumber = re.sub(r'\s+', '', greetNumber)
if greetType.isidentifier() == True and botValidator(greetNumber) == True:
if len("%s[%s]" % (greetType, greetNumber)) > 20:
greeting = fail
else:
greeting = eval("%s[%s]" % (greetType, greetNumber))
try:
if greeting != fail and debug != None:
greeting += "<br>You're choosing %s, it has %s quotes"%(greetType, len(eval(greetType)))
except:
pass
else:
greeting = fail
else:
greeting = random_greet(random.choice(NewYearCategoryList))
except:
greeting = fail
pass
else:
greeting = random_greet(random.choice(NewYearCategoryList))
if fail not in greeting:
bot_list = ["( ´ ∀ `)ノ~ ♡", "(✿◕ᴗ◕)つ━━✫・*。", "(๑˘ᵕ˘)"]
else:
bot_list = ["(≖ ︿ ≖ ✿)", "ᕙ(⇀‸↼‶)ᕗ", "(≖ ︿ ≖ ✿)ꐦꐦ", "┌( ಠ_ಠ )┘"]
bot = random.choice(bot_list)
except:
pass
return "%s<div class='centered'>%s<strong><font color='red'>%s<br>NewYearBot >> </font></strong>%s</div>"%(css, front, bot, greeting)
# Main
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/TetCTF/2023/web/AdminLairayOldSchool/container/images-services/src/bot.py | ctfs/TetCTF/2023/web/AdminLairayOldSchool/container/images-services/src/bot.py | import requests
import os, sys
import base64
if sys.version_info.major < 3:
from urllib import url2pathname
else:
from urllib.request import url2pathname
# https://stackoverflow.com/questions/10123929/fetch-a-file-from-a-local-url-with-python-requests
class LocalFileAdapter(requests.adapters.BaseAdapter):
"""Protocol Adapter to allow Requests to GET file:// URLs
@todo: Properly handle non-empty hostname portions.
"""
@staticmethod
def _chkpath(method, path):
"""Return an HTTP status for the given filesystem path."""
if method.lower() in ('put', 'delete'):
return 501, "Not Implemented" # TODO
elif method.lower() not in ('get', 'head'):
return 405, "Method Not Allowed"
elif os.path.isdir(path):
return 400, "Path Not A File"
elif not os.path.isfile(path):
return 404, "File Not Found"
elif not os.access(path, os.R_OK):
return 403, "Access Denied"
else:
return 200, "OK"
def send(self, req, **kwargs): # pylint: disable=unused-argument
"""Return the file specified by the given request
@type req: C{PreparedRequest}
@todo: Should I bother filling `response.headers` and processing
If-Modified-Since and friends using `os.stat`?
"""
path = os.path.normcase(os.path.normpath(url2pathname(req.path_url)))
response = requests.Response()
response.status_code, response.reason = self._chkpath(req.method, path)
if response.status_code == 200 and req.method.lower() != 'head':
try:
response.raw = open(path, 'rb')
except (OSError, IOError) as err:
response.status_code = 500
response.reason = str(err)
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
response.request = req
response.connection = self
return response
def close(self):
pass
if __name__ == '__main__':
try:
if (len(sys.argv) < 2):
exit()
url = sys.argv[1]
headers = {'user-agent': 'PythonBot/0.0.1'}
request = requests.session()
request.mount('file://', LocalFileAdapter())
# check extentsion
white_list_ext = ('.jpg', '.png', '.jpeg', '.gif')
vaild_extension = url.endswith(white_list_ext)
if (vaild_extension):
# check content-type
res = request.head(url, headers=headers, timeout=3)
if ('image' in res.headers.get("Content-type")
or 'image' in res.headers.get("content-type")
or 'image' in res.headers.get("Content-Type")):
r = request.get(url, headers=headers, timeout=3)
print(base64.b64encode(r.content))
else:
print(0)
else:
print(0)
except Exception as e:
# print e
print(0) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py | ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py | import requests
import os, sys
import base64
if sys.version_info.major < 3:
from urllib import url2pathname
else:
from urllib.request import url2pathname
# https://stackoverflow.com/questions/10123929/fetch-a-file-from-a-local-url-with-python-requests
class LocalFileAdapter(requests.adapters.BaseAdapter):
"""Protocol Adapter to allow Requests to GET file:// URLs
@todo: Properly handle non-empty hostname portions.
"""
@staticmethod
def _chkpath(method, path):
"""Return an HTTP status for the given filesystem path."""
if method.lower() in ('put', 'delete'):
return 501, "Not Implemented" # TODO
elif method.lower() not in ('get', 'head'):
return 405, "Method Not Allowed"
elif os.path.isdir(path):
return 400, "Path Not A File"
elif not os.path.isfile(path):
return 404, "File Not Found"
elif not os.access(path, os.R_OK):
return 403, "Access Denied"
else:
return 200, "OK"
def send(self, req, **kwargs): # pylint: disable=unused-argument
"""Return the file specified by the given request
@type req: C{PreparedRequest}
@todo: Should I bother filling `response.headers` and processing
If-Modified-Since and friends using `os.stat`?
"""
path = os.path.normcase(os.path.normpath(url2pathname(req.path_url)))
response = requests.Response()
response.status_code, response.reason = self._chkpath(req.method, path)
if response.status_code == 200 and req.method.lower() != 'head':
try:
response.raw = open(path, 'rb')
except (OSError, IOError) as err:
response.status_code = 500
response.reason = str(err)
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
response.request = req
response.connection = self
return response
def close(self):
pass
if __name__ == '__main__':
try:
if (len(sys.argv) < 2):
exit()
url = sys.argv[1]
headers = {'user-agent': 'PythonBot/0.0.1'}
request = requests.session()
request.mount('file://', LocalFileAdapter())
# check extentsion
white_list_ext = ('.jpg', '.png', '.jpeg', '.gif')
vaild_extension = url.endswith(white_list_ext)
if (vaild_extension):
# check content-type
res = request.head(url, headers=headers, timeout=3)
if ('image' in res.headers.get("Content-type")
or 'image' in res.headers.get("content-type")
or 'image' in res.headers.get("Content-Type")):
r = request.get(url, headers=headers, timeout=3)
print(base64.b64encode(r.content))
else:
print(0)
else:
print(0)
except Exception as e:
# print e
print(0) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2023/web/TetCTFToken/TetCTFToken/app.py | ctfs/TetCTF/2023/web/TetCTFToken/TetCTFToken/app.py | # from ducnt && khanghh import <3. GLHF everyone
import uuid
import json
import time
import logging
import hashlib
import string
import pycurl
import random
import string
from web3 import Web3
from flask import Flask, render_template, json, request, redirect, session, jsonify, url_for
from flaskext.mysql import MySQL
from werkzeug.security import generate_password_hash, check_password_hash
from urllib.parse import urlparse
from io import BytesIO
from contextlib import closing
from flask_session import Session
mysql = MySQL()
app = Flask(__name__)
app.secret_key = '#####CENSORED#####'
app.config['MYSQL_DATABASE_USER'] = 'TetCTFToken'
app.config['MYSQL_DATABASE_PASSWORD'] = '#####CENSORED#####'
app.config['MYSQL_DATABASE_DB'] = 'TetCTFToken'
app.config['MYSQL_DATABASE_HOST'] = "TetCTFTokenDatabase"
app.config["WAFWTF"] = ["..","../","./","union","select","from","where","ftp","ssh","redis","mysql","smtp","file","mail","curl","flag"]
app.config["STRING_ONLY"] = string.ascii_letters
app.config["SECRET_KEY"] = "#####CENSORED#####"
app.config["LIST_USERNAME_BY_DEAULT"] = ["admin","ducnt","khanghh"]
app.config["RPC_URL"] = "https://bsc-testnet.public.blastapi.io"
app.config["FLAGSTORE_ADDRESS"] = "#####CENSORED#####"
app.config["FLAGSTORE_ABI"] = """[{ "inputs": [ { "internalType": "string", "name": "", "type": "string" } ], "name": "flagClaimed", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }]"""
mysql.init_app(app)
@app.route('/')
def main():
if session.get('user'):
return render_template('dashboard.html')
else:
return render_template('index.html')
@app.route('/showBuyFlag', methods=['GET', 'POST'])
def showBuyFlag():
if session.get('user'):
global _pow2
_pow2 = proof_that_tony_stark_has_a_heart()
return render_template('buyflag.html',pow=_pow2)
else:
return render_template('index.html')
@app.route('/showDashboard')
def showDashboard():
if session.get('user'):
return render_template('dashboard.html')
else:
return render_template('signin.html')
@app.route('/showSignin')
def showSignin():
if session.get('user'):
return render_template('dashboard.html')
else:
return render_template('signin.html')
@app.route('/showSignUp')
def showSignUp():
global _pow3
_pow3 = proof_that_tony_stark_has_a_heart()
return render_template('signup.html',pow=_pow3)
@app.route('/showforgotpassword')
def showForgotPassword():
global _pow
_pow = proof_that_tony_stark_has_a_heart()
return render_template('forgotpassword.html', pow=_pow)
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
@app.route('/secret-token/<Type>',methods=['GET'])
def gen_token(Type):
return Type
@app.route('/trigger-reset-passwd-with-username/<string:_username>',methods=['GET'])
def userType(_username):
try:
_pow_from_player = request.args['inputPoW']
if verify_pow(_pow,str(_pow_from_player)):
for _check in app.config["LIST_USERNAME_BY_DEAULT"]:
if _check in _username:
return render_template('error.html',error = "Permission Denied !!!")
_secret_token = str(uuid.uuid4())
conn = mysql.connect()
cursor = conn.cursor()
_hashed_password = generate_password_hash(_secret_token)
cursor.callproc('sp_ResetPasswdUser',(_username, _hashed_password))
data = cursor.fetchall()
conn.commit()
cursor.close()
conn.close()
_secret_reset_passwd_URL = url_for('gen_token',Type = _secret_token, _external=True)
for _WAF_WTF in app.config["WAFWTF"]:
if _WAF_WTF in _secret_reset_passwd_URL:
return render_template('error.html',error = 'Oops, Not Today !!!')
_trigger_send_url = parse(_secret_reset_passwd_URL)
return render_template('notification.html', noti = "Reset Passwd Successfully. If Your User Exist, Check it out !!!")
else:
return render_template('error.html',error = "Something go wrong homie !")
except Exception as e:
return render_template('error.html',error = "Something go wrong homie !")
#PoW BTW
def proof_that_tony_stark_has_a_heart():
return str(uuid.uuid4())[:5]
def verify_pow(_pow, _result):
if hashlib.md5(_result.encode('utf-8')).hexdigest()[:5] == str(_pow):
return True
else:
return False
def parse(_url):
try:
_obj = BytesIO()
crl = pycurl.Curl()
crl.setopt(crl.URL, _url)
crl.setopt(crl.WRITEDATA, _obj)
crl.setopt(pycurl.TIMEOUT, 10)
try:
crl.perform()
except Exception as e:
crl.close()
return render_template('error.html',error = "Something go wrong homie !")
crl.close()
return True
except Exception as e:
return render_template('error.html',error = "Something go wrong homie !")
def isFlagClaimed(_addr):
try:
w3 = Web3(Web3.HTTPProvider(app.config["RPC_URL"]))
flagStore = w3.eth.contract(address=app.config["FLAGSTORE_ADDRESS"], abi=app.config["FLAGSTORE_ABI"])
return flagStore.functions.flagClaimed(_addr).call()
except Exception as e:
return render_template('error.html',error = "Something go wrong homie !")
def check_FlagClaimable_on_smartcontract(_username):
try:
isClaimed = isFlagClaimed(str(_username))
return isClaimed
except Exception as e:
return render_template('error.html',error = "Something go wrong homie !")
@app.route('/signUp',methods=['POST'])
def signUp():
try:
_name = request.form['inputName']
_email = request.form['inputEmail']
_pow_from_player = request.form['inputPoW']
#we are in the private token sale phase so you cannot login ATM
_password = str(uuid.uuid4())
if verify_pow(_pow3, _pow_from_player):
if _name and _email and _password:
conn = mysql.connect()
cursor = conn.cursor()
_hashed_password = generate_password_hash(_password)
cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
data = cursor.fetchall()
conn.commit()
cursor.close()
conn.close()
return render_template('notification.html', noti = "Register Successfully. For the privacy of our customers, We cannot tell you that the user exists or not. Also, We are in the private token sale phase so you cannot login ATM.")
else:
return render_template('error.html', error='Enter the required fields homie')
return render_template('error.html',error = "Something go wrong homie !")
except Exception as e:
return render_template('error.html',error = "Something go wrong homie !")
@app.route('/validateLogin',methods=['POST'])
def validateLogin():
try:
_username = request.form['inputEmail']
_password = request.form['inputPassword']
con = mysql.connect()
cursor = con.cursor()
cursor.callproc('sp_validateLogin',(_username,))
data = cursor.fetchall()
cursor.close()
con.close()
if len(data) > 0:
if check_password_hash(str(data[0][3]),_password):
session['user'] = data[0][0]
return redirect('/showDashboard')
else:
return render_template('error.html',error = 'Wrong Email Address or Password !!!')
else:
return render_template('error.html',error = 'Wrong Email Address or Password !!!')
except Exception as e:
return render_template('error.html',error = "Something go wrong homie !")
#save the best for last homie
@app.route('/buyflag',methods=['POST','GET'])
def buyflag():
try:
if session.get('user'):
_user_id = int(session.get('user'))
for _WAF_WTF in app.config["WAFWTF"]:
if _WAF_WTF in str(_user_id):
return render_template('error.html',error = 'Oops, Not Today !!!')
_pow_from_player = request.form['inputPoW']
connn = mysql.connect()
cursor2 = connn.cursor()
cursor2.callproc('sp_getUsername',(_user_id,))
data = cursor2.fetchall()
cursor2.close()
connn.close()
_current_username = data[0][0]
if verify_pow(_pow2, _pow_from_player):
if check_FlagClaimable_on_smartcontract(_current_username):
flag = open('/flag.txt', 'r+')
_flag = flag.read()
flag.close()
return render_template('flagclaimed.html', flag = _flag)
else:
return render_template('error.html',error = "Not Enough TetCTF Token For Claiming The Flag or Wrong Username In This Session !!!")
else:
return render_template('error.html',error = "Something go wrong homie !")
else:
return render_template('error.html',error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html',error = "Something go wrong homie !")
if __name__ == "__main__":
app.run(host='0.0.0.0',port='31337') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2022/pwn/ezflag/www/cgi-bin/upload.py | ctfs/TetCTF/2022/pwn/ezflag/www/cgi-bin/upload.py | #!/usr/bin/env python3
import os
import cgi
import base64
import socket
def write_header(key, value) -> None:
print('{:s}: {:s}'.format(key, value))
def write_status(code, msg) -> None:
print('Status: {:d} {:s}'.format(code, msg), end='\n\n')
def write_location(url) -> None:
print('Location: {:s}'.format(url), end='\n\n')
def handle_get() -> None:
with open('../html/upload.html', 'rb') as f:
dat = f.read()
write_header('Content-Type', 'text/html')
write_header('Content-Length', str(len(dat)))
write_status(200, 'OK')
print(dat.decode('utf-8'), end=None)
def valid_file_name(name) -> bool:
if len(name) == 0 or name[0] == '/':
return False
if '..' in name:
return False
if '.py' in name:
return False
return True
def handle_post() -> None:
fs = cgi.FieldStorage()
item = fs['file']
if not item.file:
write_status(400, 'Bad Request')
return
if not valid_file_name(item.filename):
write_status(400, 'Bad Request')
return
normalized_name = item.filename.strip().replace('./', '')
path = ''.join(normalized_name.split('/')[:-1])
os.makedirs('../upload/' + path, exist_ok=True)
with open('../upload/' + normalized_name, 'wb') as f:
f.write(item.file.read())
write_location('/uploads/' + normalized_name)
def check_auth() -> bool:
auth = os.environ.get('HTTP_AUTHORIZATION')
if auth is None or len(auth) < 6 or auth[0:6] != 'Basic ':
return False
auth = auth[6:]
try:
data = base64.b64decode(auth.strip().encode('ascii')).split(b':')
if len(data) != 2:
return False
username = data[0]
password = data[1]
if len(username) > 8 or len(password) > 16:
return False
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 4444))
s.settimeout(5)
s.send(username + b'\n' + password + b'\n')
result = s.recv(1)
s.close()
if result == b'Y':
return True
return False
except:
return False
if __name__ == '__main__':
if not check_auth():
write_header('WWW-Authenticate', 'Basic')
write_status(401, 'Unauthorized')
else:
method = os.environ.get('REQUEST_METHOD')
if method == 'POST':
handle_post()
elif method == 'GET':
handle_get()
else:
write_status(405, 'Method Not Allowed')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2022/pwn/ezflag/www/upload/shell.py | ctfs/TetCTF/2022/pwn/ezflag/www/upload/shell.py | import socket
import base64
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 4444))
s.settimeout(5)
s.send(b'admin\n\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n')
print(base64.b64encode(s.recv(256)).decode('ascii'))
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TetCTF/2022/crypto/shares_v2/shares_v2.py | ctfs/TetCTF/2022/crypto/shares_v2/shares_v2.py | """
In this new version, I introduce a new feature: master share. A master share
is always required to recover the original secret/password.
I implement this feature by using the master share to "encrypt" the linear
combination results.
"""
from shares import *
from typing import Tuple, List
from secrets import randbits, randbelow
MASTER_SHARE_SZ = 128
def get_shares_v2(password: str, n: int, t: int) -> Tuple[int, List[str]]:
"""
Get password shares.
Args:
password: the password to be shared.
n: the number of non-master shares returned.
t: the minimum number of non-master shares needed to recover the
password.
Returns:
the shares, including the master share (n + 1 shares in total).
"""
assert n <= MASTER_SHARE_SZ
master_share = randbits(MASTER_SHARE_SZ)
unprocessed_non_master_shares = get_shares(password, n, t)
non_master_shares = []
for i, share in enumerate(unprocessed_non_master_shares):
v = CHAR_TO_INT[share[-1]]
if (master_share >> i) & 1:
v = (v + P // 2) % P
non_master_shares.append(share[:-1] + INT_TO_CHAR[v])
return master_share, non_master_shares
def combine_shares_v2(master_share: int, non_master_shares: List[str]) -> str:
raise Exception("unimplemented")
def main():
pw_len = n = t = 32
password = "".join(INT_TO_CHAR[randbelow(P)] for _ in range(pw_len))
for _ in range(2022):
line = input()
if line == password:
from secret import FLAG
print(FLAG)
return
else:
_, non_master_shares = get_shares_v2(password, n, t)
print(non_master_shares)
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/TetCTF/2022/crypto/shares/shares.py | ctfs/TetCTF/2022/crypto/shares/shares.py | """
This is an (incomplete) implement for a new (and experimental) secret/password
sharing scheme.
The idea is simple. Basically, a secret or password is turned into a set of
finite field elements and each share is just a linear combination of these
elements. On the other hand, when enough shares are collected, the finite field
elements are determined, allowing the original secret or password to be
recovered.
"""
from typing import List
from secrets import randbelow
import string
ALLOWED_CHARS = string.ascii_lowercase + string.digits + "_"
P = len(ALLOWED_CHARS)
INT_TO_CHAR = {}
CHAR_TO_INT = {}
for _i, _c in enumerate(ALLOWED_CHARS):
INT_TO_CHAR[_i] = _c
CHAR_TO_INT[_c] = _i
def get_shares(password: str, n: int, t: int) -> List[str]:
"""
Get password shares.
Args:
password: the password to be shared.
n: the number of shares returned.
t: the minimum number of shares needed to recover the password.
Returns:
the shares.
"""
assert len(password) <= t
assert n > 0
ffes = [CHAR_TO_INT[c] for c in password]
ffes += [randbelow(P) for _ in range(t - len(password))]
result = []
for _ in range(n):
coeffs = [randbelow(P) for _ in range(len(ffes))]
s = sum([x * y for x, y in zip(coeffs, ffes)]) % P
coeffs.append(s)
result.append("".join(INT_TO_CHAR[i] for i in coeffs))
return result
def combine_shares(shares: List[str]) -> str:
raise Exception("unimplemented")
def main():
pw_len = 16
password = "".join(INT_TO_CHAR[randbelow(P)] for _ in range(pw_len))
# how about n < t :D
n = 16
t = 32
for _ in range(2022):
line = input()
if line == password:
from secret import FLAG
print(FLAG)
return
else:
print(get_shares(password, n, t))
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/TetCTF/2022/crypto/fault/fault.py | ctfs/TetCTF/2022/crypto/fault/fault.py | from secrets import randbits
from Crypto.Util.number import getPrime # pycryptodome
NBITS = 1024
D_NBITS = 128 # small `d` makes decryption faster
class Cipher:
def __init__(self):
p = getPrime(NBITS // 2)
q = getPrime(NBITS // 2)
self.n = p * q
self.d = getPrime(D_NBITS)
self.e = pow(self.d, -1, (p - 1) * (q - 1))
def encrypt(self, m: int) -> int:
assert m < self.n
return pow(m, self.e, self.n)
def faultily_decrypt(self, c: int):
assert c < self.n
fault_vector = randbits(D_NBITS)
return fault_vector, pow(c, self.d ^ fault_vector, self.n)
def main():
from secret import FLAG
cipher = Cipher()
c = cipher.encrypt(int.from_bytes(FLAG.encode(), "big"))
for _ in range(2022):
line = input()
print(cipher.faultily_decrypt(c if line == 'c' else int(line)))
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/TetCTF/2022/crypto/algebra/algebra.py | ctfs/TetCTF/2022/crypto/algebra/algebra.py | # We will be working with Fp
p = 50824208494214622675210983238467313009841434758617398532295301998201478298245257311594403096942992643947506323356996857413985105233960391416730079425326309
# Just a random constant
C = 803799120267736039902689148809657862377959420031713529926996228010552678684828445053154435325462622566051992510975853540073683867248578880146673607388918
INFINITY = "INF"
# Here's the random operator I threw in.
def op(x1, x2):
"""Returns `(x1 + x2 + 2 * C * x1 * x2) / (1 - x1 * x2)`."""
if x2 == INFINITY:
x1, x2 = x2, x1
if x1 == INFINITY:
if x2 == INFINITY:
return (-2 * C) % p
elif x2 == 0:
return INFINITY
else:
return -(1 + 2 * C * x2) * pow(x2, -1, p) % p
if x1 * x2 == 1:
return INFINITY
return (x1 + x2 + 2 * C * x1 * x2) * pow(1 - x1 * x2, -1, p) % p
# Somehow, the associativity law holds.
assert op(op(2020, 2021), 2022) == op(2020, op(2021, 2022))
# The double-and-add algorithm for `op`
def repeated_op(x, k):
"""Returns `x op x op ... op x` (`x` appears `k` times)"""
s = 0
while k > 0:
if k & 1:
s = op(s, x)
k = k >> 1
x = op(x, x)
return s
# Here's the most interesting thing:
assert repeated_op(2022, p - 1) == 0
# For this reason, I suspect there's a homomorphism `f` from this weird group
# (Fp with INFINITY under `op`) to <Fp, *>. If you can find one, I will give
# you the flag.
def main():
from secrets import randbelow
a, b = [randbelow(p) for _ in range(2)]
m, n = [randbelow(p - 1) for _ in range(2)]
c = op(repeated_op(a, m), repeated_op(b, n))
print(a)
print(b)
print(c)
# give me f(a), f(b), f(c)
fa = int(input())
fb = int(input())
fc = int(input())
if pow(fa, m, p) * pow(fb, n, p) % p == fc:
from secret import FLAG
print(FLAG[:pow(fc, 4, p)])
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/TetCTF/2020/smallservice/client.py | ctfs/TetCTF/2020/smallservice/client.py | import hmac
from pwn import *
from json import loads
from time import time
import sys
class Client():
def __init__(self, host, port): #remote
self.r = remote(host, port)
# def __init__(self, filename): #local
# self.r = process(filename)
def Hmac(self, src, key):
HMAC = hmac.new(key)
HMAC.update(src)
return HMAC.hexdigest().upper()
def login(self, user, password):
payload = "function=login&action=request&user=%s" %user
self.r.sendline(payload)
recv = self.r.recvuntil("\n\n\n")[:-3]
print (recv)
res = loads(recv)
if res['status'] == 1:
return False
self.challenge = res['data']['challenge'].encode()
self.uuid = res['data']['uuid'].encode()
self.publickey = res['data']['publickey'].encode()
passwd = self.Hmac("%s%s" %(self.publickey, password), self.challenge)
payload = "function=login&action=login&user=admin&pass=%s&uuid=%s" %(passwd, self.uuid)
self.r.sendline(payload)
recv = self.r.recvuntil("\n\n\n")[:-3]
print (recv)
res = loads(recv)
if res['status'] == 1:
return False
self.privatekey = passwd
return True
def ping(self, host):
timestamp = "%d" %time()
action = "ping"
auth = self.Hmac("%s%s" %(action, timestamp), self.privatekey)
payload = "function=manage&action=%s×tamp=%s&auth=%s&uuid=&host=%s" %(action, timestamp, auth, host)
self.r.sendline(payload)
print (self.r.recvuntil("\n\n\n")[:-3])
def changepasswd(self, passwd):
timestamp = "%d" %time()
action = "changepasswd"
auth = self.Hmac("%s%s" %(action, timestamp), self.privatekey)
payload = "function=manage&action=%s×tamp=%s&auth=%s&uuid=&pass=%s" %(action, timestamp, auth, passwd)
self.r.sendline(payload)
print (self.r.recvuntil("\n\n\n")[:-3])
cl = Client("./smallservice")
if cl.login("admin", "B"*16) == False:
print ("False")
sys.exit()
cl.ping("127.0.0.1")
cl.changepasswd("B"*16) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/On_Fire/app/main.py | ctfs/p4ctf/2023/Quals/ai/On_Fire/app/main.py | import torch
from torch import nn
from flask import Flask, request, jsonify, render_template
import numpy as np
from app.flag import flag_list
app = Flask(__name__)
def list_to_tensor(l):
return torch.tensor(l, pin_memory=True)
correct_preds = list_to_tensor([215, 13, 436, 35, 140, 418, 48, 79, 411, 136, 368, 449, 473, 158, 351, 483, 142, 371, 354, 10, 392, 243, 194, 230, 336, 493, 171, 434, 486, 28, 255, 458, 124, 390, 122, 381, 149, 99, 90, 335, 54, 489, 259, 310, 55, 456, 204, 201, 92, 75, 265, 448, 485, 463, 102, 106, 386, 399, 424, 385, 250, 271, 209, 472, 61, 227, 273, 409, 195, 60, 410, 415, 85, 488, 175, 97, 192, 282, 356, 109, 226, 216, 464, 143, 459, 357, 1, 315, 422, 247, 374, 450, 467, 355, 379, 312, 156, 59, 37, 121, 342, 98, 300, 454, 253, 419, 133, 18, 421, 331, 437, 284, 301, 428, 165, 120, 50, 290, 208, 330, 440, 27, 8, 314, 150, 47, 248, 435, 36, 119, 163, 144, 162, 42, 111, 462, 169, 219, 233, 260, 451, 214, 341, 383, 110, 205, 237, 365, 420, 184, 334, 353, 134, 372, 359, 20, 118, 203, 433, 179, 56, 294, 45, 244, 113, 499, 279, 352, 69, 280, 218, 478, 213, 76, 324, 236, 442, 166, 305, 77, 439, 345, 43, 72, 340, 95, 174, 207, 476, 103, 199, 123, 396, 19, 235, 147, 125, 484, 318, 173, 49, 446, 495, 164, 33, 337, 148, 316, 5, 9, 6, 182, 291, 161, 129, 256, 426, 465, 211, 22, 358, 289, 66, 373, 131, 298, 452, 461, 88, 388, 496, 394, 350, 151, 238, 382, 362, 384, 210, 135, 263, 21, 39, 404, 468, 189, 430, 425, 202, 63, 139, 83, 270, 402, 64, 157, 15, 432, 311, 471, 278, 254, 487, 309, 344, 466, 240, 38, 490, 391, 366, 223, 239, 281, 408, 108, 228, 220, 128, 241, 492, 224, 405, 178, 445, 116, 283, 380, 400, 4, 206, 297, 94, 32, 477, 417, 67, 378, 84, 89, 160, 343, 296, 469, 339, 329, 193, 321, 299, 387, 58, 274, 269, 14, 246, 86, 470, 325, 313, 146, 427, 91, 406, 212, 412, 401, 101, 497, 303, 407, 153, 159, 57, 222, 286, 285, 132, 403, 257, 176, 65, 12, 17, 185, 52, 46, 460, 277, 276, 53, 198, 114, 117, 266, 304, 249, 154, 87, 40, 395, 190, 457, 93, 11, 23, 347, 322, 267, 30, 200, 453, 423, 104, 475, 180, 444, 51, 138, 287, 242, 302, 25, 317, 187, 221, 288, 397, 308, 245, 438, 295, 62, 369, 183, 232, 268, 333, 225, 480, 2, 44, 234, 367, 141, 320, 349, 168, 360, 474, 293, 479, 275, 177, 0, 3, 482, 34, 332, 481, 364, 96, 115, 326, 261, 251, 346, 292, 319, 416, 127, 393, 105, 363, 494, 29, 107, 26, 74, 377, 413, 431, 327, 71, 191, 7, 441, 443, 188, 338, 447, 197, 155, 170, 376, 137, 130, 398, 186, 370, 81, 100, 126, 307, 31, 73, 16, 196, 258, 152, 323, 498, 414, 328, 217, 231, 167, 68, 389, 306, 41, 112, 375, 70, 264, 361, 82, 348, 252, 229, 272, 172, 78, 429, 181, 491, 80, 262, 24, 455, 145])
classes = list_to_tensor(list(range(500)))
flag = list_to_tensor(flag_list)
def create_net(size_in, size_out, weight=None, bias=None):
ln = torch.nn.Linear(size_in, size_out)
with torch.no_grad():
if weight is not None:
ln.weight = weight
if bias is not None:
ln.bias = bias
return ln
def eval_net(size_in, size_out, weight=None, bias=None):
if size_in > 10:
raise Exception("bad input size")
if size_out > 5000:
raise Exception("OOM")
weight = nn.Parameter(torch.tensor(weight, dtype=torch.float32), requires_grad=False)
bias = nn.Parameter(torch.tensor(bias, dtype=torch.float32), requires_grad=False)
l = create_net(size_in, size_out, weight, bias)
inp = torch.randn(1, size_in)
out = l(inp[0])
sortedd = out[:len(correct_preds)].type(torch.LongTensor)
if len(sortedd) < 500:
return f"Here is your output {sortedd}"
out = torch.searchsorted(
classes,
correct_preds,
sorter=sortedd
)
if out == range(len(correct_preds)):
# TODO: return something more interesting, like a flag or something
return "gratz!, how did you did that? here is an easter egg: 🥚"
else:
return f"well, you didn't get the easter egg, this is what you get: {out}"
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
try:
data = request.get_json()
# Extract and validate parameters
size_in = data.get('size_in', None)
size_out = data.get('size_out', None)
weight = data.get('weight', None)
bias = data.get('bias', None)
if size_in is None or size_out is None or weight is None or bias is None:
return jsonify({"error": "Invalid input, missing one or more parameters."}), 400
size_in = int(size_in)
size_out = int(size_out)
weight_array = np.array(weight)
bias_array = np.array(bias)
if weight_array.shape != (size_out, size_in) or bias_array.shape != (size_out,):
return jsonify({"error": "Invalid input, incorrect shape for weight or bias arrays."}), 400
msg = eval_net(size_in, size_out, weight, bias)
return jsonify({"message": msg}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/On_Fire/app/gunicorn_conf.py | ctfs/p4ctf/2023/Quals/ai/On_Fire/app/gunicorn_conf.py | import multiprocessing
bind = "127.0.0.1:8000"
#workers = multiprocessing.cpu_count()
workers = 4
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/On_Fire/app/flag.py | ctfs/p4ctf/2023/Quals/ai/On_Fire/app/flag.py | flag_list = [(ord(x)) for x in "p4{fakeflag}"]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/flag.py | ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/flag.py | flag_s = "p4{fakeflag}"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/app.py | ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/app.py | # app.py
from flask import Flask, render_template, request, jsonify
import hashlib
import math
import time
import sqlite3
import secrets
from haversine import haversine
from geotask.eval_one import load_model, eval_one, eval_multi
from geotask.downloader.streetview import panoids
from flag import flag_s
app = Flask(__name__)
model = load_model("./geotask/2023-04-17-geoguessr-20.pth")
difficulty = 5
def init_db():
conn = sqlite3.connect('proofs.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS used_proofs (proof TEXT UNIQUE)''')
c.execute('''CREATE TABLE IF NOT EXISTS generated_prefixes (prefix TEXT UNIQUE)''')
conn.commit()
conn.close()
init_db()
def store_generated_prefix(prefix):
conn = sqlite3.connect('proofs.db')
c = conn.cursor()
c.execute("INSERT INTO generated_prefixes (prefix) VALUES (?)", (prefix,))
conn.commit()
conn.close()
def is_prefix_generated(prefix):
conn = sqlite3.connect('proofs.db')
c = conn.cursor()
c.execute("SELECT * FROM generated_prefixes WHERE prefix = ?", (prefix,))
result = c.fetchone()
conn.close()
return result is not None
def store_used_proof(proof):
conn = sqlite3.connect('proofs.db')
c = conn.cursor()
c.execute("INSERT INTO used_proofs (proof) VALUES (?)", (proof,))
conn.commit()
conn.close()
def is_proof_used(proof):
conn = sqlite3.connect('proofs.db')
c = conn.cursor()
c.execute("SELECT * FROM used_proofs WHERE proof = ?", (proof,))
result = c.fetchone()
conn.close()
return result is not None
def check_proof(prefix, nonce):
guess = f'{prefix}{nonce}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:difficulty] == "0" * difficulty
@app.route('/')
def index():
return render_template('index.html')
@app.route('/get_prefix')
def get_prefix():
prefix = secrets.token_hex(8)
store_generated_prefix(prefix)
return jsonify({'prefix': prefix, "difficulty": difficulty})
# app.py
@app.route('/guess', methods=['POST'])
def guess():
data = request.get_json()
locations = data.get('locations')
nonce = data.get('nonce')
prefix = data.get('prefix')
proof_string = f'{prefix}{nonce}'
if not is_prefix_generated(prefix):
return jsonify({'status': 'failed', 'reason': 'invalid prefix'}), 400
if is_proof_used(proof_string):
return jsonify({'status': 'failed', 'reason': 'invalid proof'}), 400
if not check_proof(prefix, nonce):
return jsonify({'status': 'failed', 'reason': 'invalid proof'}), 400
store_used_proof(proof_string)
preds = []
score = 0
for i in range(len(locations)):
for j in range(len(locations)):
if i == j:
continue
lat1, lon1 = locations[i]['lat'], locations[i]['lng']
lat2, lon2 = locations[j]['lat'], locations[j]['lng']
dist = haversine((lat1, lon1), (lat2, lon2))
if dist <= 50:
return jsonify({'status': 'failed', 'reason': 'points too close'}), 400
if len(locations) != 5:
return jsonify({'status': 'failed', 'reason': 'must have 5 guesses'}), 400
pns = []
for location in locations:
try:
pns.append(panoids(location["lat"], location["lng"])[0]['panoid'])
except Exception as e:
print(location)
return jsonify({'status': 'failed', 'reason': 'no streetview in one of those points'}), 400
score = 0
scores = []
preds = eval_multi(model, panoids=pns)
for location, pred in zip(locations, preds):
print(location, pred)
x = haversine(pred, (location["lat"], location["lng"]))
tmp_score = int(5000*(math.e**(-x/2000)))
scores.append((location, tmp_score))
score += tmp_score
if score < 1000:
return jsonify({'status': 'success', 'flag': flag_s + f' score {score}'})
else:
return jsonify({'status': 'failed', 'reason': f'my brainz know where those are! your score was {score}, {scores}, try going below 1000'}), 400
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/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/split_earth_s2.py | ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/split_earth_s2.py | import os, re
import pickle
def get_classes():
if os.path.isfile("./geotask/points.pickle"):
print("Using existing points.pickle")
with open('./geotask/points.pickle', 'rb') as handle:
b = pickle.load(handle)
return b
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/eval_one.py | ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/eval_one.py | from sqlite3 import DatabaseError
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn.functional as F
import glob
import os
import json
import random
import math
from geotask.downloader.get_one_by_coords import get_image_by_coords, get_image_by_panoid
from geotask.train_resnet import get_model, classes
from haversine import haversine
from torch import nn
from PIL import Image
import sys
def load_model(model_path):
model = get_model()
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu'))["model_state_dict"])
model.eval()
return model
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
#RandomPanoramaShift()
])
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def eval_multi(model, panoids=None):
images = []
for panoid in panoids:
image = get_image_by_panoid(panoid)
image = transform(image.convert('RGB')).to(device)
images.append(image)
imgs = torch.stack(images)
inference = model(imgs)
inference = inference.detach()
out = torch.max(inference, 1)[1]
preds = []
for idx in out:
pred = None
for cl in classes:
if idx.item() == cl[0]:
pred = cl[1]
break
preds.append(pred)
return preds
def eval_one(model, coords=None, panoid=None):
if coords:
lat, lon = coords
image = get_image_by_coords(lat, lon)
if panoid:
image = get_image_by_panoid(panoid)
data = transform(image.convert('RGB')).to(device).unsqueeze(0)
inference = model(data)
inference = inference.detach()
out = torch.max(inference, 1)
idx = out.indices[0].item()
pred = None
for cl in classes:
if idx == cl[0]:
pred = cl
break
class_, pred_coords = pred[0], pred[1]
pred_lat, pred_lon = pred[1]
pred_coords = (pred_lat, pred_lon)
return class_, pred_coords
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Provide arg to eval")
exit()
if len(sys.argv) == 3:
eval_one(load_model(sys.argv[1]), image_path=sys.argv[2])
if len(sys.argv) == 4:
lat, lon = sys.argv[2], sys.argv[3]
eval_one(load_model(sys.argv[1]), coords=(float(lat), float(lon)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/train_resnet.py | ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/train_resnet.py | import os
import time
import sys
import re
import math
import random
import statistics
import glob
import torch
import torch.nn as nn
import torch.optim as optim
from datetime import date
from torchvision import models
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
from geotask.split_earth_s2 import get_classes
from haversine import haversine
classes = get_classes()
def get_model():
model = models.resnet50()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Modify the first layer to accommodate the larger input
model.conv1 = nn.Conv2d(3, 64, kernel_size=(15, 15), stride=(4, 4), padding=(6, 6), bias=False)
num_classes = len(classes)
# Replace the last layer with a fully connected layer for our number of classes
model.fc = nn.Linear(model.fc.in_features, num_classes)
model = model.to(device)
return model
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/downloader/streetview.py | ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/downloader/streetview.py | # -*- coding: utf-8 -*-
"""
Original code is from https://github.com/robolyst/streetview
Functions added in this file are
download_panorama_v1, download_panorama_v2, download_panorama_v3
Usage:
given latitude and longitude
panoids = panoids( lat, lon )
panoid = panoids[0]['panoid']
panorama_img = download_panorama_v3(panoid, zoom=2)
"""
import re
from datetime import datetime
import requests
import time
import shutil
import itertools
from PIL import Image
from io import BytesIO
import os
import numpy as np
from skimage import io
def _panoids_url(lat, lon):
"""
Builds the URL of the script on Google's servers that returns the closest
panoramas (ids) to a give GPS coordinate.
"""
url = "https://maps.googleapis.com/maps/api/js/GeoPhotoService.SingleImageSearch?pb=!1m5!1sapiv3!5sUS!11m2!1m1!1b0!2m4!1m2!3d{0:}!4d{1:}!2d50!3m10!2m2!1sen!2sGB!9m1!1e2!11m4!1m3!1e2!2b1!3e2!4m10!1e1!1e2!1e3!1e4!1e8!1e6!5m1!1e2!6m1!1e2&callback=_xdc_._v2mub5"
return url.format(lat, lon)
def _panoids_data(lat, lon, proxies=None):
"""
Gets the response of the script on Google's servers that returns the
closest panoramas (ids) to a give GPS coordinate.
"""
url = _panoids_url(lat, lon)
r= requests.get(url, proxies=None)
if r.status_code != 200:
print("ups")
return r
def panoids(lat, lon, closest=False, disp=False, proxies=None):
"""
Gets the closest panoramas (ids) to the GPS coordinates.
If the 'closest' boolean parameter is set to true, only the closest panorama
will be gotten (at all the available dates)
"""
resp = _panoids_data(lat, lon)
# Get all the panorama ids and coordinates
# I think the latest panorama should be the first one. And the previous
# successive ones ought to be in reverse order from bottom to top. The final
# images don't seem to correspond to a particular year. So if there is one
# image per year I expect them to be orded like:
# 2015
# XXXX
# XXXX
# 2012
# 2013
# 2014
pans = re.findall('\[[0-9]+,"(.+?)"\].+?\[\[null,null,(-?[0-9]+.[0-9]+),(-?[0-9]+.[0-9]+)', resp.text)
pans = [{
"panoid": p[0],
"lat": float(p[1]),
"lon": float(p[2])} for p in pans] # Convert to floats
# Remove duplicate panoramas
pans = [p for i, p in enumerate(pans) if p not in pans[:i]]
if disp:
for pan in pans:
print(pan)
# Get all the dates
# The dates seem to be at the end of the file. They have a strange format but
# are in the same order as the panoids except that the latest date is last
# instead of first.
dates = re.findall('([0-9]?[0-9]?[0-9])?,?\[(20[0-9][0-9]),([0-9]+)\]', resp.text)
dates = [list(d)[1:] for d in dates] # Convert to lists and drop the index
if len(dates) > 0:
# Convert all values to integers
dates = [[int(v) for v in d] for d in dates]
# Make sure the month value is between 1-12
dates = [d for d in dates if d[1] <= 12 and d[1] >= 1]
# The last date belongs to the first panorama
year, month = dates.pop(-1)
pans[0].update({'year': year, "month": month})
# The dates then apply in reverse order to the bottom panoramas
dates.reverse()
for i, (year, month) in enumerate(dates):
pans[-1-i].update({'year': year, "month": month})
# # Make the first value of the dates the index
# if len(dates) > 0 and dates[-1][0] == '':
# dates[-1][0] = '0'
# dates = [[int(v) for v in d] for d in dates] # Convert all values to integers
#
# # Merge the dates into the panorama dictionaries
# for i, year, month in dates:
# pans[i].update({'year': year, "month": month})
# Sort the pans array
def func(x):
if 'year'in x:
return datetime(year=x['year'], month=x['month'], day=1)
else:
return datetime(year=3000, month=1, day=1)
pans.sort(key=func)
if closest:
return [pans[i] for i in range(len(dates))]
else:
return pans
def tiles_info(panoid, zoom=5):
"""
Generate a list of a panorama's tiles and their position.
The format is (x, y, filename, fileurl)
"""
# image_url = 'http://maps.google.com/cbk?output=tile&panoid={}&zoom={}&x={}&y={}'
image_url = "https://cbk0.google.com/cbk?output=tile&panoid={}&zoom={}&x={}&y={}"
# The tiles positions
coord = list(itertools.product(range(26), range(13)))
tiles = [(x, y, "%s_%dx%d.jpg" % (panoid, x, y), image_url.format(panoid, zoom, x, y)) for x, y in coord]
return tiles
def download_tiles(tiles, directory, disp=False):
"""
Downloads all the tiles in a Google Stree View panorama into a directory.
Params:
tiles - the list of tiles. This is generated by tiles_info(panoid).
directory - the directory to dump the tiles to.
"""
for i, (x, y, fname, url) in enumerate(tiles):
if disp and i % 20 == 0:
print("Image %d / %d" % (i, len(tiles)))
# Try to download the image file
while True:
try:
response = requests.get(url, stream=True)
break
except requests.ConnectionError:
print("Connection error. Trying again in 2 seconds.")
time.sleep(2)
with open(directory + '/' + fname, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
def stich_tiles(panoid, tiles, directory, final_directory):
"""
Stiches all the tiles of a panorama together. The tiles are located in
`directory'.
"""
tile_width = 512
tile_height = 512
panorama = Image.new('RGB', (26*tile_width, 13*tile_height))
for x, y, fname, url in tiles:
fname = directory + "/" + fname
tile = Image.open(fname)
panorama.paste(im=tile, box=(x*tile_width, y*tile_height))
del tile
# print fname
panorama.save(final_directory + ("/%s.jpg" % panoid))
del panorama
def download_panorama_v3(panoid, zoom=5, disp=False):
'''
v3: save image information in a buffer. (v2: save image to dist then read)
input:
panoid: which is an id of image on google maps
zoom: larger number -> higher resolution, from 1 to 5, better less than 3, some location will fail when zoom larger than 3
disp: verbose of downloading progress, basically you don't need it
output:
panorama image (uncropped)
'''
tile_width = 512
tile_height = 512
# img_w, img_h = int(np.ceil(416*(2**zoom)/tile_width)*tile_width), int(np.ceil(416*( 2**(zoom-1) )/tile_width)*tile_width)
img_w, img_h = 416*(2**zoom), 416*( 2**(zoom-1) )
tiles = tiles_info( panoid, zoom=zoom)
valid_tiles = []
# function of download_tiles
for i, tile in enumerate(tiles):
x, y, fname, url = tile
if disp and i % 20 == 0:
print("Image %d / %d" % (i, len(tiles)))
if x*tile_width < img_w and y*tile_height < img_h: # tile is valid
# Try to download the image file
while True:
try:
response = requests.get(url, stream=True)
break
except requests.ConnectionError:
print("Connection error. Trying again in 2 seconds.")
time.sleep(2)
valid_tiles.append( Image.open(BytesIO(response.content)) )
del response
# function to stich
panorama = Image.new('RGB', (img_w, img_h))
i = 0
for x, y, fname, url in tiles:
if x*tile_width < img_w and y*tile_height < img_h: # tile is valid
tile = valid_tiles[i]
i+=1
panorama.paste(im=tile, box=(x*tile_width, y*tile_height))
return panorama
def download_panorama_v1(panoid, zoom=5, disp=False, directory='temp'):
'''
v1: simplely concatenate original functions
input:
panoid
output:
panorama image (uncropped)
'''
tiles = tiles_info( panoid, zoom=zoom)
if not os.path.exists(directory):
os.makedirs( directory )
# function of download_tiles
for i, (x, y, fname, url) in enumerate(tiles):
if disp and i % 20 == 0:
print("Image %d / %d" % (i, len(tiles)))
# Try to download the image file
while True:
try:
response = requests.get(url, stream=True)
break
except requests.ConnectionError:
print("Connection error. Trying again in 2 seconds.")
time.sleep(2)
with open(directory + '/' + fname, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
# function of stich_tiles
tile_width = 512
tile_height = 512
panorama = Image.new('RGB', (26*tile_width, 13*tile_height))
for x, y, fname, url in tiles:
fname = directory + "/" + fname
tile = Image.open(fname)
panorama.paste(im=tile, box=(x*tile_width, y*tile_height))
del tile
delete_tiles( tiles, directory )
return np.array(panorama)
def download_panorama_v2(panoid, zoom=5, disp=False, directory='temp'):
'''
v2: if tile is in invalid region, just skip them. obsolete: use black block instead of downloading
input:
panoid
output:
panorama image (uncropped)
'''
img_w, img_h = 416*(2**zoom), 416*( 2**(zoom-1) )
tile_width = 512
tile_height = 512
tiles = tiles_info( panoid, zoom=zoom)
valid_tiles = []
if not os.path.exists(directory):
os.makedirs( directory )
# function of download_tiles
for i, tile in enumerate(tiles):
x, y, fname, url = tile
if disp and i % 20 == 0:
print("Image %d / %d" % (i, len(tiles)))
if x*tile_width < img_w and y*tile_height < img_h: # tile is valid
valid_tiles.append(tile)
# Try to download the image file
while True:
try:
response = requests.get(url, stream=True)
break
except requests.ConnectionError:
print("Connection error. Trying again in 2 seconds.")
time.sleep(2)
with open(directory + '/' + fname, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
# function to stich
panorama = Image.new('RGB', (img_w, img_h))
for x, y, fname, url in tiles:
if x*tile_width < img_w and y*tile_height < img_h: # tile is valid
fname = directory + "/" + fname
tile = Image.open(fname)
panorama.paste(im=tile, box=(x*tile_width, y*tile_height))
del tile
delete_tiles( valid_tiles, directory )
return np.array(panorama)
def delete_tiles(tiles, directory):
for x, y, fname, url in tiles:
os.remove(directory + "/" + fname)
def api_download(panoid, heading, flat_dir, key, width=640, height=640,
fov=120, pitch=0, extension='jpg', year=2017, fname=None):
"""
Download an image using the official API. These are not panoramas.
Params:
:panoid: the panorama id
:heading: the heading of the photo. Each photo is taken with a 360
camera. You need to specify a direction in degrees as the photo
will only cover a partial region of the panorama. The recommended
headings to use are 0, 90, 180, or 270.
:flat_dir: the direction to save the image to.
:key: your API key.
:width: downloaded image width (max 640 for non-premium downloads).
:height: downloaded image height (max 640 for non-premium downloads).
:fov: image field-of-view.
:image_format: desired image format.
:fname: file name
You can find instructions to obtain an API key here: https://developers.google.com/maps/documentation/streetview/
"""
if not fname:
fname = "%s_%s_%s" % (year, panoid, str(heading))
image_format = extension if extension != 'jpg' else 'jpeg'
url = "https://maps.googleapis.com/maps/api/streetview"
params = {
# maximum permitted size for free calls
"size": "%dx%d" % (width, height),
"fov": fov,
"pitch": pitch,
"heading": heading,
"pano": panoid,
"key": key
}
response = requests.get(url, params=params, stream=True)
try:
img = Image.open(BytesIO(response.content))
filename = '%s/%s.%s' % (flat_dir, fname, extension)
img.save(filename, image_format)
except:
print("Image not found")
filename = None
del response
return filename
def download_flats(panoid, flat_dir, key, width=400, height=300,
fov=120, pitch=0, extension='jpg', year=2017):
for heading in [0, 90, 180, 270]:
api_download(panoid, heading, flat_dir, key, width, height, fov, pitch, extension, year)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/downloader/get_one_by_coords.py | ctfs/p4ctf/2023/Quals/ai/GeoHacker/app/geotask/downloader/get_one_by_coords.py | import geotask.downloader.streetview as streetview
import matplotlib.pyplot as plt
import os
import random
import sys
def get_image_by_panoid(panoid):
panorama = streetview.download_panorama_v3(panoid, zoom=2, disp=False)
return panorama
def get_image_by_coords(lat, lon):
sys.stdout.flush()
panoids = streetview.panoids(lat=lat, lon=lon, closest=True)
if len(panoids) == 0:
raise Exception("no panoid here")
panoid = panoids[0]['panoid']
lat = panoids[0]['lat']
lon = panoids[0]['lon']
name = str(lat) + "_" + str(lon) + ".jpg"
panorama = streetview.download_panorama_v3(panoid, zoom=2, disp=False)
return panorama
if __name__ == '__main__':
out = get_image_by_coords(sys.argv[1], sys.argv[2])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2022/crypto/aesium/task.py | ctfs/p4ctf/2022/crypto/aesium/task.py | import random
# https://raw.githubusercontent.com/boppreh/aes/master/aes.py
import aes
from aes import AES
def inline_round(s, key):
keym = aes.bytes2matrix(key)
plain_state = aes.bytes2matrix(s)
aes.sub_bytes(plain_state)
aes.shift_rows(plain_state)
aes.mix_columns(plain_state)
aes.add_round_key(plain_state, keym)
return aes.matrix2bytes(plain_state)
def main():
print("Give me 256 unique plaintexts (hex encoded, 16 bytes long)")
texts = []
for i in range(256):
texts.append(bytes.fromhex(input()))
assert len(set(texts)) == 256
assert all(len(c) == 16 for c in texts)
target_texts = list(texts)
random.shuffle(target_texts)
print("Now give me a key such that:")
for i in range(256):
print(f"encrypt({texts[i].hex()}, key) == {target_texts[i].hex()}")
print("TODO: key schedule is not implemented, sorry. Please just send me your round keys instead")
# Originally I wanted to just use a normal AES encryption library, but with a sneaky bug that allows
# user to skip key expansion if the provided key is long enough. This is not too crazy - for example this aes.py
# would be *almost* vulnerable without "assert" in AES.__init__ and with n_rounds hardcoded to 14
# In the end I decided against this, because:
# - this chall is already hard enough without sneaky underhanded tricks
# - last round weirdness makes the (intended) solution less elegant
# So anyway there you have it - you can encrypt the data with any number of AES rounds, with round
# keys completely under your control. Good luck.
round_keys = []
print("Give me your key (hex encoded)")
key_data = bytes.fromhex(input())
for i in range(0, len(key_data), 16):
round_keys.append(key_data[i:i+16])
assert all(len(c) == 16 for c in round_keys)
for i, plaintext in enumerate(texts):
for round_key in round_keys:
plaintext = inline_round(plaintext, round_key)
print(f"{plaintext.hex()} == {target_texts[i].hex()}")
assert plaintext == target_texts[i]
from flag import FLAG
print("thx your flag is " + FLAG)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2022/crypto/aesium/aes.py | ctfs/p4ctf/2022/crypto/aesium/aes.py | #!/usr/bin/env python3
"""
This is an exercise in secure symmetric-key encryption, implemented in pure
Python (no external libraries needed).
Original AES-128 implementation by Bo Zhu (http://about.bozhu.me) at
https://github.com/bozhu/AES-Python . PKCS#7 padding, CBC mode, PKBDF2, HMAC,
byte array and string support added by me at https://github.com/boppreh/aes.
Other block modes contributed by @righthandabacus.
Although this is an exercise, the `encrypt` and `decrypt` functions should
provide reasonable security to encrypted messages.
"""
s_box = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
)
inv_s_box = (
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
)
def sub_bytes(s):
for i in range(4):
for j in range(4):
s[i][j] = s_box[s[i][j]]
def inv_sub_bytes(s):
for i in range(4):
for j in range(4):
s[i][j] = inv_s_box[s[i][j]]
def shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def inv_shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
# learned from https://web.archive.org/web/20100626212235/http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mix_single_column(a):
# see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
u = a[0]
a[0] ^= t ^ xtime(a[0] ^ a[1])
a[1] ^= t ^ xtime(a[1] ^ a[2])
a[2] ^= t ^ xtime(a[2] ^ a[3])
a[3] ^= t ^ xtime(a[3] ^ u)
def mix_columns(s):
for i in range(4):
mix_single_column(s[i])
def inv_mix_columns(s):
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
u = xtime(xtime(s[i][0] ^ s[i][2]))
v = xtime(xtime(s[i][1] ^ s[i][3]))
s[i][0] ^= u
s[i][1] ^= v
s[i][2] ^= u
s[i][3] ^= v
mix_columns(s)
r_con = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
def bytes2matrix(text):
""" Converts a 16-byte array into a 4x4 matrix. """
return [list(text[i:i+4]) for i in range(0, len(text), 4)]
def matrix2bytes(matrix):
""" Converts a 4x4 matrix into a 16-byte array. """
return bytes(sum(matrix, []))
def xor_bytes(a, b):
""" Returns a new byte array with the elements xor'ed. """
return bytes(i^j for i, j in zip(a, b))
def inc_bytes(a):
""" Returns a new byte array with the value increment by 1 """
out = list(a)
for i in reversed(range(len(out))):
if out[i] == 0xFF:
out[i] = 0
else:
out[i] += 1
break
return bytes(out)
def pad(plaintext):
"""
Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes.
Note that if the plaintext size is a multiple of 16,
a whole block will be added.
"""
padding_len = 16 - (len(plaintext) % 16)
padding = bytes([padding_len] * padding_len)
return plaintext + padding
def unpad(plaintext):
"""
Removes a PKCS#7 padding, returning the unpadded text and ensuring the
padding was correct.
"""
padding_len = plaintext[-1]
assert padding_len > 0
message, padding = plaintext[:-padding_len], plaintext[-padding_len:]
assert all(p == padding_len for p in padding)
return message
def split_blocks(message, block_size=16, require_padding=True):
assert len(message) % block_size == 0 or not require_padding
return [message[i:i+16] for i in range(0, len(message), block_size)]
class AES:
"""
Class for AES-128 encryption with CBC mode and PKCS#7.
This is a raw implementation of AES, without key stretching or IV
management. Unless you need that, please use `encrypt` and `decrypt`.
"""
rounds_by_key_size = {16: 10, 24: 12, 32: 14}
def __init__(self, master_key):
"""
Initializes the object with a given key.
"""
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
def _expand_key(self, master_key):
"""
Expands and returns a list of key matrices for the given master_key.
"""
# Initialize round keys with raw key material.
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // 4
i = 1
while len(key_columns) < (self.n_rounds + 1) * 4:
# Copy previous word.
word = list(key_columns[-1])
# Perform schedule_core once every "row".
if len(key_columns) % iteration_size == 0:
# Circular shift.
word.append(word.pop(0))
# Map to S-BOX.
word = [s_box[b] for b in word]
# XOR with first byte of R-CON, since the others bytes of R-CON are 0.
word[0] ^= r_con[i]
i += 1
elif len(master_key) == 32 and len(key_columns) % iteration_size == 4:
# Run word through S-box in the fourth iteration when using a
# 256-bit key.
word = [s_box[b] for b in word]
# XOR with equivalent word from previous iteration.
word = xor_bytes(word, key_columns[-iteration_size])
key_columns.append(word)
# Group key words in 4x4 byte matrices.
return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
def encrypt_block(self, plaintext):
"""
Encrypts a single block of 16 byte long plaintext.
"""
assert len(plaintext) == 16
plain_state = bytes2matrix(plaintext)
add_round_key(plain_state, self._key_matrices[0])
for i in range(1, self.n_rounds):
sub_bytes(plain_state)
shift_rows(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[i])
sub_bytes(plain_state)
shift_rows(plain_state)
add_round_key(plain_state, self._key_matrices[-1])
return matrix2bytes(plain_state)
def decrypt_block(self, ciphertext):
"""
Decrypts a single block of 16 byte long ciphertext.
"""
assert len(ciphertext) == 16
cipher_state = bytes2matrix(ciphertext)
add_round_key(cipher_state, self._key_matrices[-1])
inv_shift_rows(cipher_state)
inv_sub_bytes(cipher_state)
for i in range(self.n_rounds - 1, 0, -1):
add_round_key(cipher_state, self._key_matrices[i])
inv_mix_columns(cipher_state)
inv_shift_rows(cipher_state)
inv_sub_bytes(cipher_state)
add_round_key(cipher_state, self._key_matrices[0])
return matrix2bytes(cipher_state)
def encrypt_cbc(self, plaintext, iv):
"""
Encrypts `plaintext` using CBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
assert len(iv) == 16
plaintext = pad(plaintext)
blocks = []
previous = iv
for plaintext_block in split_blocks(plaintext):
# CBC mode encrypt: encrypt(plaintext_block XOR previous)
block = self.encrypt_block(xor_bytes(plaintext_block, previous))
blocks.append(block)
previous = block
return b''.join(blocks)
def decrypt_cbc(self, ciphertext, iv):
"""
Decrypts `ciphertext` using CBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
assert len(iv) == 16
blocks = []
previous = iv
for ciphertext_block in split_blocks(ciphertext):
# CBC mode decrypt: previous XOR decrypt(ciphertext)
blocks.append(xor_bytes(previous, self.decrypt_block(ciphertext_block)))
previous = ciphertext_block
return unpad(b''.join(blocks))
def encrypt_pcbc(self, plaintext, iv):
"""
Encrypts `plaintext` using PCBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
assert len(iv) == 16
plaintext = pad(plaintext)
blocks = []
prev_ciphertext = iv
prev_plaintext = bytes(16)
for plaintext_block in split_blocks(plaintext):
# PCBC mode encrypt: encrypt(plaintext_block XOR (prev_ciphertext XOR prev_plaintext))
ciphertext_block = self.encrypt_block(xor_bytes(plaintext_block, xor_bytes(prev_ciphertext, prev_plaintext)))
blocks.append(ciphertext_block)
prev_ciphertext = ciphertext_block
prev_plaintext = plaintext_block
return b''.join(blocks)
def decrypt_pcbc(self, ciphertext, iv):
"""
Decrypts `ciphertext` using PCBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
assert len(iv) == 16
blocks = []
prev_ciphertext = iv
prev_plaintext = bytes(16)
for ciphertext_block in split_blocks(ciphertext):
# PCBC mode decrypt: (prev_plaintext XOR prev_ciphertext) XOR decrypt(ciphertext_block)
plaintext_block = xor_bytes(xor_bytes(prev_ciphertext, prev_plaintext), self.decrypt_block(ciphertext_block))
blocks.append(plaintext_block)
prev_ciphertext = ciphertext_block
prev_plaintext = plaintext_block
return unpad(b''.join(blocks))
def encrypt_cfb(self, plaintext, iv):
"""
Encrypts `plaintext` with the given initialization vector (iv).
"""
assert len(iv) == 16
blocks = []
prev_ciphertext = iv
for plaintext_block in split_blocks(plaintext, require_padding=False):
# CFB mode encrypt: plaintext_block XOR encrypt(prev_ciphertext)
ciphertext_block = xor_bytes(plaintext_block, self.encrypt_block(prev_ciphertext))
blocks.append(ciphertext_block)
prev_ciphertext = ciphertext_block
return b''.join(blocks)
def decrypt_cfb(self, ciphertext, iv):
"""
Decrypts `ciphertext` with the given initialization vector (iv).
"""
assert len(iv) == 16
blocks = []
prev_ciphertext = iv
for ciphertext_block in split_blocks(ciphertext, require_padding=False):
# CFB mode decrypt: ciphertext XOR decrypt(prev_ciphertext)
plaintext_block = xor_bytes(ciphertext_block, self.encrypt_block(prev_ciphertext))
blocks.append(plaintext_block)
prev_ciphertext = ciphertext_block
return b''.join(blocks)
def encrypt_ofb(self, plaintext, iv):
"""
Encrypts `plaintext` using OFB mode initialization vector (iv).
"""
assert len(iv) == 16
blocks = []
previous = iv
for plaintext_block in split_blocks(plaintext, require_padding=False):
# OFB mode encrypt: plaintext_block XOR encrypt(previous)
block = self.encrypt_block(previous)
ciphertext_block = xor_bytes(plaintext_block, block)
blocks.append(ciphertext_block)
previous = block
return b''.join(blocks)
def decrypt_ofb(self, ciphertext, iv):
"""
Decrypts `ciphertext` using OFB mode initialization vector (iv).
"""
assert len(iv) == 16
blocks = []
previous = iv
for ciphertext_block in split_blocks(ciphertext, require_padding=False):
# OFB mode decrypt: ciphertext XOR encrypt(previous)
block = self.encrypt_block(previous)
plaintext_block = xor_bytes(ciphertext_block, block)
blocks.append(plaintext_block)
previous = block
return b''.join(blocks)
def encrypt_ctr(self, plaintext, iv):
"""
Encrypts `plaintext` using CTR mode with the given nounce/IV.
"""
assert len(iv) == 16
blocks = []
nonce = iv
for plaintext_block in split_blocks(plaintext, require_padding=False):
# CTR mode encrypt: plaintext_block XOR encrypt(nonce)
block = xor_bytes(plaintext_block, self.encrypt_block(nonce))
blocks.append(block)
nonce = inc_bytes(nonce)
return b''.join(blocks)
def decrypt_ctr(self, ciphertext, iv):
"""
Decrypts `ciphertext` using CTR mode with the given nounce/IV.
"""
assert len(iv) == 16
blocks = []
nonce = iv
for ciphertext_block in split_blocks(ciphertext, require_padding=False):
# CTR mode decrypt: ciphertext XOR encrypt(nonce)
block = xor_bytes(ciphertext_block, self.encrypt_block(nonce))
blocks.append(block)
nonce = inc_bytes(nonce)
return b''.join(blocks)
import os
from hashlib import pbkdf2_hmac
from hmac import new as new_hmac, compare_digest
AES_KEY_SIZE = 16
HMAC_KEY_SIZE = 16
IV_SIZE = 16
SALT_SIZE = 16
HMAC_SIZE = 32
def get_key_iv(password, salt, workload=100000):
"""
Stretches the password and extracts an AES key, an HMAC key and an AES
initialization vector.
"""
stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE)
aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:]
hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:]
iv = stretched[:IV_SIZE]
return aes_key, hmac_key, iv
def encrypt(key, plaintext, workload=100000):
"""
Encrypts `plaintext` with `key` using AES-128, an HMAC to verify integrity,
and PBKDF2 to stretch the given key.
The exact algorithm is specified in the module docstring.
"""
if isinstance(key, str):
key = key.encode('utf-8')
if isinstance(plaintext, str):
plaintext = plaintext.encode('utf-8')
salt = os.urandom(SALT_SIZE)
key, hmac_key, iv = get_key_iv(key, salt, workload)
ciphertext = AES(key).encrypt_cbc(plaintext, iv)
hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest()
assert len(hmac) == HMAC_SIZE
return hmac + salt + ciphertext
def decrypt(key, ciphertext, workload=100000):
"""
Decrypts `ciphertext` with `key` using AES-128, an HMAC to verify integrity,
and PBKDF2 to stretch the given key.
The exact algorithm is specified in the module docstring.
"""
assert len(ciphertext) % 16 == 0, "Ciphertext must be made of full 16-byte blocks."
assert len(ciphertext) >= 32, """
Ciphertext must be at least 32 bytes long (16 byte salt + 16 byte block). To
encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`.
"""
if isinstance(key, str):
key = key.encode('utf-8')
hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:]
salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:]
key, hmac_key, iv = get_key_iv(key, salt, workload)
expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest()
assert compare_digest(hmac, expected_hmac), 'Ciphertext corrupted or tampered.'
return AES(key).decrypt_cbc(ciphertext, iv)
def benchmark():
key = b'P' * 16
message = b'M' * 16
aes = AES(key)
for i in range(30000):
aes.encrypt_block(message)
__all__ = [encrypt, decrypt, AES]
if __name__ == '__main__':
import sys
write = lambda b: sys.stdout.buffer.write(b)
read = lambda: sys.stdin.buffer.read()
if len(sys.argv) < 2:
print('Usage: ./aes.py encrypt "key" "message"')
print('Running tests...')
from tests import *
run()
elif len(sys.argv) == 2 and sys.argv[1] == 'benchmark':
benchmark()
exit()
elif len(sys.argv) == 3:
text = read()
elif len(sys.argv) > 3:
text = ' '.join(sys.argv[2:])
if 'encrypt'.startswith(sys.argv[1]):
write(encrypt(sys.argv[2], text))
elif 'decrypt'.startswith(sys.argv[1]):
write(decrypt(sys.argv[2], text))
else:
print('Expected command "encrypt" or "decrypt" in first argument.')
# encrypt('my secret key', b'0' * 1000000) # 1 MB encrypted in 20 seconds.
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2022/crypto/hello_crypto/hello.py | ctfs/p4ctf/2022/crypto/hello_crypto/hello.py | import os
import sys
from flag import FLAG
def xor(key, data):
return bytes(ac ^ bc for ac, bc in zip(key*len(data), data))
def viscrypt(data):
return xor(data, data[1:] + b"\xaa")
def round(key, rawdata):
return viscrypt(xor(key, rawdata))
key = os.urandom(8)
pt = FLAG
for i in range(8833):
pt = round(key, pt)
print(pt.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/p4ctf/2022/crypto/rsa/rsa.py | ctfs/p4ctf/2022/crypto/rsa/rsa.py | import sys
import random
from Crypto.PublicKey import RSA
import secret
difficulty = 128
degree = 8
def generate_rsa_key():
while True:
key = RSA.generate(1024)
e = 47
n, p, q = key.n, key.p, key.q
if secret.is_hard_enough(e, p, q, difficulty):
return e, key.p, key.q
else: # just so you know it's not some super unusual key
print("Key retry")
def printout(msg):
sys.stdout.write(str(msg) + "\n")
sys.stdout.flush()
def polynomial_value(x, coefficients):
return sum([coefficients[i] * x ** i for i in range(degree + 1)])
def validate(coefficients, values, e, n):
random.shuffle(values)
return all([polynomial_value(pow(v, e, n), coefficients) == v for v in values])
def read_coefficients():
return [int(input("coefficient for x^{} ".format(i))) for i in range(degree + 1)]
def main():
try:
e, p, q = generate_rsa_key()
printout("You have a chance to prove that you've completely broken RSA!")
printout("Give me a polynomial of degree {} which can act as RSA decryption oracle.".format(degree))
coefficients = read_coefficients()
printout("Just so you can verify I'm not cheating, the key (e,p,q) is:")
printout(e)
printout(p)
printout(q)
printout(
"Please provide {} distinct plaintext numbers (comma separated), which your function is able to decrypt, based on their encrypted version".format(
difficulty))
values = [int(x) for x in input().split(",")]
assert len(values) == difficulty
assert len(set(values)) == difficulty
assert all([0 <= v < p * q for v in values])
if validate(coefficients, values, e, p * q):
printout(open("flag.txt", "rb").read())
except:
printout("Nope :(")
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BITSCTF/2024/crypto/Not_Suspicous_Agency/encrypt.py | ctfs/BITSCTF/2024/crypto/Not_Suspicous_Agency/encrypt.py | #!/usr/bin/env python3
from Crypto.Util.number import bytes_to_long, long_to_bytes
from nsa_ecc_secret import P, Q
import os
flag = b'REDACTED'
s = bytes_to_long(os.urandom(16))
def generate(P, Q, s):
while True:
r = int((s * P).x)
yield from long_to_bytes((r * Q).x)[2:]
s = int((r * P).x)
g = generate(P, Q, s)
def encrypt(g, t):
out = []
for b in t:
x = next(g)
out.append(b ^ x)
return bytes(out)
print(f'P = {P.xy}')
print(f'Q = {Q.xy}')
print(encrypt(g, b'This is a test string for debugging'))
print(encrypt(g, flag))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BITSCTF/2024/forensic/Refresh/prng.py | ctfs/BITSCTF/2024/forensic/Refresh/prng.py | #part of the code that used the prng
def good_prng(seed=None):
state = seed
while True:
state = (state * 1103515245 + 12345) & 0x7FFFFFFF
yield state
arr0 = [0] * len(flag)
arr1 = [0] * len(flag)
prng = good_prng(seed_value)
for i in range(len(flag)):
arr0[i] = next(prng) % 128
arr1[i] = next(prng) % 128 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | import struct
from enum import IntEnum
class PacketType(IntEnum):
DATA = 0x01
SEEN = 0x02
ERROR = 0x03
class Flags:
DEV = 0b10000000
SYN = 0b01000000
ACK = 0b00100000
ERROR = 0b00010000
FIN = 0b00001000
PSH = 0b00000100
class GhostingPacket:
"""
Packet structure:
- version (1 byte)
- type (1 byte)
- flags (1 byte)
- rsv (4 bytes string)
- payload_length (1 byte)
- payload (variable length)
"""
def __init__(self, version=1, packet_type=PacketType.DATA, flags=0, rsv=b'xxxx',payload_length = 0, payload=b''):
if not isinstance(rsv, bytes) or len(rsv) != 4:
raise ValueError("RSV must be exactly 4 bytes")
self.version = version
self.packet_type = packet_type
self.flags = flags
self.rsv = rsv
self.payload = payload
self.payload_length = len(payload)
def pack(self):
"""Pack the packet into bytes"""
if len(self.payload) > 255:
raise ValueError("Payload too large (max 255 bytes)")
header = struct.pack('!BBB4sB',
self.version,
int(self.packet_type),
self.flags,
self.rsv,
self.payload_length
)
return header + self.payload
@classmethod
def unpack(cls, data):
"""Unpack bytes into a packet"""
if len(data) < 8:
raise ValueError("Packet too short (minimum 8 bytes)")
version, packet_type, flags, rsv, payload_length = struct.unpack('!BBB4sB', data[:8])
if len(data) < 8 + payload_length:
raise ValueError(f"Packet payload incomplete. Expected {payload_length} bytes")
payload = data[8:8+payload_length]
try:
packet_type = PacketType(packet_type)
except ValueError:
raise ValueError(f"Invalid packet type: {packet_type}")
return cls(version, packet_type, flags, rsv,payload_length, payload)
def __str__(self):
"""String representation for debugging"""
flags_str = []
if self.flags & Flags.DEV: flags_str.append("DEV")
if self.flags & Flags.SYN: flags_str.append("SYN")
if self.flags & Flags.ACK: flags_str.append("ACK")
if self.flags & Flags.ERROR: flags_str.append("ERROR")
if self.flags & Flags.FIN: flags_str.append("FIN")
return (f"GhostingPacket(version={self.version}, "
f"type={self.packet_type.name}, "
f"flags=[{' | '.join(flags_str)}], "
f"rsv={self.rsv}, "
f"payload_length={self.payload_length}, "
f"payload={self.payload})")
def validate(self):
if self.version != 1:
raise ValueError("Unsupported version")
if not isinstance(self.packet_type, PacketType):
raise ValueError("Invalid packet type")
if len(self.rsv) != 4:
raise ValueError("RSV must be exactly 4 bytes")
if len(self.payload) > 255:
raise ValueError("Payload too large") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BITSCTF/2025/rev/Baby_Rev/chall.py | ctfs/BITSCTF/2025/rev/Baby_Rev/chall.py |
# Python obfuscation by freecodingtools.org
_ = lambda __ : __import__('zlib').decompress(__import__('base64').b64decode(__[::-1]));exec((_)(b'==QfWoizP8/vvPv/tuVzbgu38ZSv1J0vDFdewTskFOqPbM+WKx2jqyeNPjmjdv0UEvzJE8gv9CRQ+J7PE9hk+7ckGqlNUcWpUWR5BoF7Nh9b7jAd1AkzqcA1MAXHT2ThGtUsZyz/twhfFdyuZBPJjVvWGVvSi+9yLDbIJy/hPWF6yGTWbZb598AULQA6qaJ9e1W3b7h8WyGg0sd0+6HPLnDDWwVrED5VN5w/+aV4UAaD7e2T6AtHUkvQuZ4Vc0I8QA4yUWCwcyPvRF4F8Cefn988yW479b8+Hw6SlDLtj4B1zKMcf5Gj8jqnfvGklcK4tguMpvpWcb1tJeqRLytNmPrnII0VHEJmL5oNMmpko/VlkxOh4JfpVljVtIy6rZv+UpWTh5DXG3QDvq+5W7BsU/D1CZSztXVSzUy4S9DhwfCh/D1wLEzFeF2dTBx0ZoolAtJrMiuPiYf7FvarnQ+Hf6yXptpFVDPW/emZLtrlCMzhCsmT3SkrJouxfZTXP/4UT15ER9pKmH4y8zFd8Ee3B33nfQrpOB8yB5Uf0bTfy7XbFzkzQWRT5zIQ1tQkKBLdB3Z+7ffMOMyG26Gtb201wbdZcIdBLV/G5ri6o07fQZXmNXJcme3HVTHcn8WVUzC/VnlQRgfDfszgNElIwPgBa1M2juaRDWqFldV1vsyNVknjI/WWlNZaxlJ+g7hwLIKiJaJWdDtYtuFxic+9nlbrmJ/Mo1u/u9uQ9KNykDHnpPLLfqJ5EWpEpFI4gxx07buDp98Iz0fzoK5LycH79OVvTywbJPABu/XEq9WHzoygixQExi8D2tFOOSrdaMuexHeFzBkA/b/DL6HcOCCg1tLPFoS7WxibjM2mo2Y9Pe11EqInbc1TYker39rhA+PGfzcQ+pBDGtwv+Ic/QG/a558NyX9N6mpchLOszXzFPSCFr72qf6TSX2/AxxuwYahXvObEz7BD5osVi1GsF4EU5f1/4FRQxbmbW4Nc79XFwk7abxYmNRmcm5oeUt/sE/Dt8Nndtn4Kv2c47cYjafGlVOpq57NCBK0Mp2KRUk7xTDyuHpPGjodO515UQ/lRUOtpAmzukFADnYK1+u4wA2VMFES6yI9hgRpEAm97fXQcltHOCxKy6meXDRhbZn5gA4/qhNoOgfu64SbKO4e9nIFerrZ9HxXsdyuiX1O+YbxL2TwCPa5FUQOoArTZbrPy4fYOCxMHrd9sD3mrYKcJS+THQxaQZhp/u384f8R3ItpUlTwn0tT22en4sqGKe3ybZzOSKfK5CkDe3nWFfMsWg0Dt3BlIB2w8O7cSBDbyxdv2P/C5vEjK0AbL+aysqU2oCdHd5X+ik8PRH6aYHySlOi+qxD8dBXiO8Ku1L+lJ+fFHeIdGjAjBD8oEX3xiyPSsj8mlQJefqhplHSFgYnBoacaOxi+hk3/IXUvMA9G5Ew30fYkY+/D0XHI/wS3wgMOCMpxc+SpKUrIkZbTzE//ixkup6oTRc9wvidHqfBAWij74ZSuiPS/cBXH2cVoWg3NsK9gA2DxphDTDXfTtJPQFx+wg3lnMGivRcQs3SNrO4RnJyldUx0ac4+Qz5bgc+TMtp/xHh7l0cOKrVffTFwUeadYpX4pVemsRqpK+3UipEWWDXUuJA7a60Wu5u8VZzLEC+DzleKFJ9BVOxLMz2irNRHA+g87n4NqpS3AnOrxlDLPMyRLRWBIg9NJfGA3rG01ghw3Rl9vwT+BSk9eWcDZnkBrpaehvsp3oKaI393EQ0rHtiKkOBgsDhmOCevj6GbX4efan44x3Qf88S40wQ1H0Mkfy1H6rlVwGJubOEF7oP25GERM8fgtrWMtlEv3CHvJ1WkoS7f7ipmhrDoSpA+DuoXPPLJibi0L3zgK5Dp/g+3n0N1UY70/wngx3dDx/h61zLveLvE8iUIgHTSYx8WPPfyIOcKyXiDwFSguVXj/H6Pv/wKWkGwXxpJ39EkjnA4vwOu0sNsSzM7f6PtU4EFnmiypiFo5bBi/hxm7lAygO9vFQoyF7mAe4l6pX37nxBKE/ihT6PelAiTChco8hjZOhb22vRUvH/XmmQFfHXJrW6kmeTORMXUDV63ChHX3BieXBG6M+nmfef9nbW7tBfintfdofa55HPR07wU8yN1SkB0gmQ0alqzjYFk+Enw5Staw+LLILbgHy9bnrVBKDwpuhcsjnJyxoSXOfjqBVouVDoGM9/o25VvbDZUF1c3347gf4zNB/8a32Ga5Y/TS3ynoppOsRFevHRBbHZXvZesQ+w+B6jWPn22vqVifOho/Ijis9WFaUjs6v3q8THYKmisDR9cG1chN5hsT0Syur7Xb4ZiT10URXzr6E6f9Sn0DmKdw8T56pf7qCT+gSKW4e+ney6c/jj2oIThfzkvfkth5BxotGlaLp59GuG4VDmCGxPzkPVTfzaeE9rUMm4ozjRJ0kVBdXVK5iBox7r0QEtNpvprgjgDqyg27begZbvMg/lQy6OZfLzdr7N7iqxn3rV4+fbATgi/b7sSdzl38ng997UntfdiBsNTh/8y3V1NEjzBq+r/NA10un73ldBzQyDLH9wyA7/Ll9137jXSWP01ndZzV9CaZUNxiiTyTd/UOEW/Hq8rQszQojEq1ePTzwK+LMOJUeZ8z8a5GjCOPh+MlSuUWBlSOA9ARJImI4ne48ckcQdWLoZyCB3BIXciQZvqblz/d6Ix9OaLX0kTzjSpZ2zu3MSFJiBoUMoadYYMaI0iDeclYoWPPso/IQSR8squ1gk9O6joTOtXc8IomY/GRpdgSuPXfzTnRTwxrX0201OkpteyANd4fKPVgVMbMhS+I/qlN4J4fNoXLKqeBMb/qgt9IdHjGqnKRubC/+Xg30sZPmjT0huI7m5XX0va3QYdLmI7VmBV7d4c61Eg/HS8ZvZaDKXv5OddEXAc6MkJ+oJYqPSL0cQNiVZY7kwKFgWj1lMUzptOpqJwQA8VST7Ng/E8fiLbiCRoye2wzef7YFhot3XmQ4LxLpol/NIlqAYQ/XarTEw3Z5zXYxw83nyI9aDnMb6t/kwR2pKptEMUdTmftRIq0GGDnGescc2kZ5YFzVrScIbMO546wmdAoir351RTWeyQTIdBF7J0tTW0jdU8KE+jUe4sJkTU+Jq1dPY2LFxr62oA7fx0LBHvvZ57/ySGdtGtZHSDj5GLRYXF+9scAbdNSjoFFFEcD1V0zZ3pc5U11OIhHc1HKFxa0DvJlViFyyKM0LPdqq/rIx3BSkAzaXUyr3sY7aEKnK+1AnksnGZ1ctP0sr/mWIGjW+0bdyKq/pAPxUBStnGO1SF5PovbXX0zHg29JG3t467t6WF8xNdES82ycHNbypRI0N3Aj1iM5ePM6iGhKW9E6C+lipA5wYNhgGtLY67H7SwXwWI0F/2JkpwJV7gP9sepVEv8bxgROKbc9O2dOjQs46+Vz8h6nbHltA2Zx3vQmLOZ6mJaZM1URPCfikFA3gEYUkmJyEQLui5Rj7LBPRvGHrC7pdZATXi52l8YtlL5+8+mCOIo+Sgba7ESYxzlXRHwaMuBxjoVtf5a2FIvm5GFMDC2ik7uE8l4SuwvfO+1bclBgGyaLRW4jkB69oIEQEjT0x7icUYly9Fus+LHyI3+qM6Wj2gr2ifJK12JHXKgkt9eoKCm1mLqiXO8UDyT398yZv8Vz7h1P+g8P2ECVsVck0ua20IaBxaH9LxFAfMxHREEvDQnylqv9pS8YMNCStuI81ZOA7dmjL7o0jYQbggmk9c9bWCLWx+h3SU1+AMqrGT5GYY7+vQo0HlvjL2g0AnGOJyEIFBmryFXqQH6OCM7t/3deuItLQao2ezGxBs/MlKjuNZFOJLPtdk7ILy4uqxpdwa4dKCBfjVIyxi5QDtiPVWkwETMK6mqw2KmOzY28pwIAK1mYjGdtNp6XUfJb7+SjFn8wD8RsMcijr3AUr8gV3lwZPwjvXDJ7NN+Dkm1PXsqzD29UCHQZeU7WLldPkU0mb9IslYQ7bqhWc3NfRmqZgb6PGtxSagq2BeNDCB3HsXTHfpB4ds3voaC8gDW9Ob+nX5u41Ox4qLBq2rP5KBIXgdAecO8H81l72JfEiecNes17GS1YC4Ax/BUntEdHX4MUmJs9fZPCh0LJAlDPyaTHKe2mH5PPLDMDXWXrFJm0KH8rB5G4Y3HgLoGpLjp38lvk+jA4iVr/hq9dNmbjDw+/m8V3NLFi7uBZqgn/uHO+pg9NDSYF9xO28xhtug6sQOTyg9mkZK9HNKse655JU10Z4eZE4qqbsrmtH73XyIdLNnVUPU7DAfNFhZkX/TIlgfvxh32r2p6+NixG2EQD2Ey3eWwpLsXEe5NPoa/m3ufyrth4w3TO/ZRzYHAzLOc4B76GCQTqgEvBceeOSZRXG+rQmXsbr6CJmwzDiKhLgSECcQOY55o2nmVGQvEErhDGLve52Pic7q4/Hm0M0dBxIJroxTEgrgf2xx6JuUBgiXR3WHMuJk92XPhxPS1WJt2+9wXBwfXLbEdTtj/2C0l8pt2/GmRvoUUR3ZiokcVKGvidAuM9kVtM72PPVNwTWjIiT7smc5D8TpSS8KU7AZQEQvjDTyxwmhze9NDhT8qf7+Gtrc9uzt9FoqN48kSBFC6/WW5evalAVwXFd3WC3oLpEUJENjqZsV0pOEwUiQYUvuSzlk/cFi9wKj03cI1K/BspKdG0XUcNq+RCnVyzghD6qeDZNS5Rxang+xBpOnY27lHSCFJbOOKtiEU/vA8RtKRJjhrf0UOYv99Evjceenb+eLSW9FlFCnNVwbC3hwYi92xP1sdn9Z5ZIOx7odwlu5joVvQ3SOAWEJ0/ZpQHcJb7NPO38ES3CtlEr5MSc32WNhCnkDjhJ8YdpYpD/kYp3E9DIQzoBlowWFtkBeVlrITC6LrbfIPRZ66OF3/uqXWC7frazExMVLD7TDbTUOGKkA+a0F6rZOUYChhW7/2MsslzsPCSlbEKXuR2YrIrSc99Cbre1DeyH2W1ziIIg0c2DkcZMR8fArtWkKqWuZgFokUXLtAuGRdIwz3jl1xmaA6+2RuZQuL3mMkha9Sl+EllGw2Db35WASFAEG3ACzhpm9lmlkm6aOBY63tjS6MhXKJFyCHyd3Ns4YfIdBlzW0WEObjzLD6TpauokM7byzOEu3kt/uS0sciZIk+TMDIhbeGuZ/80JSXIQpu1EszUn645uVtQd7CdbD3AztkwFxOnfKkDzu5lURC2Ra1wCQutaE0Sep56GVPh/x1Ggic0Vnv1S3nbRhxKuvvzAC7eu9Q4IWGPTO6DF6W8n+Ii0d0FevBIOMXzM5bFM+5cjc/W268e3jdhIDxSWNmjCwIdVGltA2Lm9PFpmdlZWmoJkDwzwond2ivUo+D5VdZdSjkgrMyRk1Jn1w+DJQG0ZW8OQC998/n8//9b++/nipqOzsyp6yw7rb8+1DXh0MP0ZswMxxwImGOkun9DAWiUxyW7lVwJe'))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BITSCTF/2025/crypto/RSA_Bummer/chall.py | ctfs/BITSCTF/2025/crypto/RSA_Bummer/chall.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from Secrets import FLAG
def lmao(n,k,x): #Better function needed
pseudo_p = 1
for i in range(2,k*n-x):
try:
if (GCD(i,n-1)^(n-1)!=0):
pseudo_p = (pseudo_p*inverse(i,n))%n
except:
continue
return inverse(pseudo_p,n)
e = 27525540
while True:
p = getPrime(1024)
if (((15-GCD(e,(p-1)))>>(31))==0):
break
q = getPrime(1024)
r = getPrime(1024)
modulo = p*r
pseudo_n = r*(pow(e,p,q))
multiplier = getPrime(4)
flag = bytes(FLAG)
print("Pseudo_n = ", pseudo_n)
print("e = ", e)
for i in range(3):
pt = flag [ i*len(flag)//3 : (i+1)*len(flag)//3 ]
ct = pow(bytes_to_long(pt),e,(p*q))
print(f"Ciphertext {i+1} =", ct)
for i in range(5):
x = input("Enter your lucky number : ")
try:
x = int(x)
except:
print("Not an integer")
continue
if((x<=23)&(x>=3)):
print("Your lucky output : ", lmao(modulo,multiplier,x))
else:
print("Not your lucky day, sad.")
print("--------------------------------------")
print("Bye!!") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BITSCTF/2025/crypto/Noob_RSA_Returns/encrypt.py | ctfs/BITSCTF/2025/crypto/Noob_RSA_Returns/encrypt.py | from Crypto.Util.number import getPrime, bytes_to_long
def GenerateKeys(p, q):
e = 65537
n = p * q
phi = (p-1)*(q-1)
d = pow(e, -1, phi)
C = 0xbaaaaaad
D = 0xdeadbeef
A= 0xbaadf00d
K = (A*p**2 - C*p + D)*d
return (e, n, K)
def Encrypt():
flag = b"REDACTED" # HEHEHEHEHE
p = getPrime(512)
q = getPrime(512)
e, n, K = GenerateKeys(p, q)
pt = bytes_to_long(flag)
ct = pow(pt, e, n)
print(f"e = {e}")
print(f"n = {n}")
print(f"ct = {ct}")
print(f"K = {K}")
Encrypt()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BITSCTF/2025/crypto/Alice_n_Bob_in_Wonderland/chall.py | ctfs/BITSCTF/2025/crypto/Alice_n_Bob_in_Wonderland/chall.py | #!/usr/bin/python3
import random
import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from ecdsa import SigningKey, SECP256k1, VerifyingKey
import ecdsa
from secret import conversation_length,messages,secret
# Story setup
print("""
Alice and Bob are two secret agents communicating over a secure channel.
""")
alice_private_key = SigningKey.generate(curve=SECP256k1)
alice_public_key = alice_private_key.verifying_key
bob_private_key = SigningKey.generate(curve=SECP256k1)
bob_public_key = bob_private_key.verifying_key
def compute_shared_secret(private_key, public_key):
shared_point = private_key.privkey.secret_multiplier * public_key.pubkey.point
shared_secret_bytes = shared_point.to_bytes()
return hashlib.sha256(shared_secret_bytes).digest()
shared_secret = compute_shared_secret(alice_private_key, bob_public_key)
aes_key = shared_secret[:16]
iv = shared_secret[16:]
random.seed(int(iv.hex(),16))
def encrypt(message):
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(message.encode(), AES.block_size))
return ciphertext
def decrypt(ciphertext):
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(ciphertext)
try:
plaintext = unpad(decrypted, AES.block_size)
return plaintext
except:
return decrypted
def sign(message, private_key:SigningKey):
message = message.encode()
k = random.randint(1, SECP256k1.order - 1)
signature = private_key.sign(message,hashfunc=hashlib.sha256 ,k=k)
return signature
def verify(message, signature, public_key:VerifyingKey):
return public_key.verify(signature, message, hashfunc=hashlib.sha256)
def main():
print(f"\nAlice's public key: {alice_public_key.to_string().hex()}")
print(f"Bob's public key: {bob_public_key.to_string().hex()}")
print("\nYour job is to break their scheme and get the secret key that is cuicial to their entire operation.")
i = 0
alice_flagged = False
bob_flagged = False
while i < conversation_length:
message = messages[i]
if i % 2 == 0:
ciphertext = encrypt(message)
signature = sign(message,alice_private_key)
print(f"\nIntercepted from Alice:\nCiphertext: {ciphertext.hex()}\nSignature: {signature.hex()}\n")
while True:
try:
print(f"\nSend to Bob:")
ciphertext_forged = bytes.fromhex(input("Ciphertext (hex): "))
signature_forged = bytes.fromhex(input("Signature (hex): "))
plaintext = decrypt(ciphertext_forged)
verified = verify(plaintext,signature_forged,alice_public_key)
break
except ValueError as e:
if 'Data must be padded to 16 byte boundary in CBC mode' in str(e):
print("I thought you were an expert in this field. Don't you know that AES encrypted data needs to be in blocks of 16 bytes??!!")
elif 'non-hexadecimal number found in fromhex() arg' in str(e):
print("I thought you were better than this, you have actually dissapointed me, you need to input in hex.")
elif 'Padding is incorrect' in str(e):
print("Well Well Well, this operation is going to fail if you do not send the correct ciphertext.")
except ecdsa.keys.BadSignatureError:
if not alice_flagged:
print("\nI think they got suspicious, the signature did not match. Make sure the signature matches otherwise the whole operation is OVER!!")
print("Wait, I think I found something from their networks, they tried to decrypt the text and this is what they found:")
print(plaintext.hex())
alice_flagged = True
else:
print("AAAAGGHH!!! They got to us, I should not have trusted you in the first place. This operation is over. I REPEAT, THIS OPERATION IS OVER!!!!")
exit()
else:
ciphertext = encrypt(message)
signature = sign(message,bob_private_key)
print(f"\nIntercepted from Bob:\nCiphertext: {ciphertext.hex()}\nSignature: {signature.hex()}\n")
while True:
try:
print(f"\nSend to Alice:")
ciphertext_forged = bytes.fromhex(input("Ciphertext (hex): "))
signature_forged = bytes.fromhex(input("Signature (hex): "))
plaintext = decrypt(ciphertext_forged)
verified = verify(plaintext,signature_forged,bob_public_key)
break
except ValueError as e:
if 'Data must be padded to 16 byte boundary in CBC mode' in str(e):
print("I thought you were an expert in this field. Don't you know that AES encrypted data needs to be in blocks of 16 bytes??!!")
elif 'non-hexadecimal number found in fromhex() arg' in str(e):
print("I thought you were better than this, you have actually dissapointed me, you need to input in hex.")
elif 'Padding is incorrect' in str(e):
print("Well Well Well, this operation is going to fail if you do not send the correct ciphertext.")
except ecdsa.keys.BadSignatureError:
print("\nI think they got suspicious, the signature did not match. Make sure the signature matches otherwise the whole operation is OVER!!")
if not bob_flagged:
print(plaintext.hex())
bob_flagged = True
else:
print("AAAAGGHH!!! They got to us, I should not have trusted you in the first place. This operation is over. I REPEAT, THIS OPERATION IS OVER!!!!")
exit()
i += 1
print("\n")
print("Great! Now they have no doubts that they are talking to each other. Now we will launch our attack. REMEMBER, WE ONLY GET ONE CHANCE!")
print("Send this message to Alice:","Can I have the key again, I think I forgot where I kept the key.")
try:
print(f"\nSend to Aice:")
ciphertext_forged = bytes.fromhex(input("Ciphertext (hex): "))
signature_forged = bytes.fromhex(input("Signature (hex): "))
plaintext = decrypt(ciphertext_forged)
verified = verify(plaintext,signature_forged,bob_public_key)
if verified and plaintext.decode() == "Can I have the key again, I think I forgot where I kept the key.":
print("Very good, now we wait.")
ciphertext = encrypt(secret)
signature = sign(secret,alice_private_key)
print(f"\nIntercepted from Alice:\nCiphertext: {ciphertext.hex()}\nSignature: {signature.hex()}\n")
except ValueError as e:
if 'Data must be padded to 16 byte boundary in CBC mode' in str(e):
print("I thought you were an expert in this field. Don't you know that AES encrypted data needs to be in blocks of 16 bytes??!!")
elif 'non-hexadecimal number found in fromhex() arg' in str(e):
print("I thought you were better than this, you have actually dissapointed me, you need to input in hex.")
elif 'Padding is incorrect' in str(e):
print("Well Well Well, this operation is going to fail if you do not send the correct ciphertext.")
except ecdsa.keys.BadSignatureError:
print("AAAAGGHH!!! We were so close, I should not have trusted you in the first place. This operation is over. I REPEAT, THIS OPERATION IS OVER!!!!")
exit()
except Exception as e:
print(e)
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/LIT/2021/rev/shuffle/shuffle.py | ctfs/LIT/2021/rev/shuffle/shuffle.py | import random
f = open("flag.txt", "r").read()
random.seed(random.randint(0, 1000))
l = list(f[:-1])
random.shuffle(l)
print(''.join(l))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LIT/2021/rev/Evaluation/eval.py | ctfs/LIT/2021/rev/Evaluation/eval.py | print(eval(eval(eval(eval(eval(eval("''.join([chr(i) for i in [39,39,46,106,111,105,110,40,91,99,104,114,40,105,41,32,102,111,114,32,105,32,105,110,32,91,51,57,44,51,57,44,52,54,44,49,48,54,44,49,49,49,44,49,48,53,44,49,49,48,44,52,48,44,57,49,44,57,57,44,49,48,52,44,49,49,52,44,52,48,44,49,48,53,44,52,49,44,51,50,44,49,48,50,44,49,49,49,44,49,49,52,44,51,50,44,49,48,53,44,51,50,44,49,48,53,44,49,49,48,44,51,50,44,57,49,44,53,49,44,53,55,44,52,52,44,53,49,44,53,55,44,52,52,44,53,50,44,53,52,44,52,52,44,52,57,44,52,56,44,53,52,44,52,52,44,52,57,44,52,57,44,52,57,44,52,52,44,52,57,44,52,56,44,53,51,44,52,52,44,52,57,44,52,57,44,52,56,44,52,52,44,53,50,44,52,56,44,52,52,44,53,55,44,52,57,44,52,52,44,53,55,44,53,55,44,52,52,44,52,57,44,52,56,44,53,50,44,52,52,44,52,57,44,52,57,44,53,50,44,52,52,44,53,50,44,52,56,44,52,52,44,52,57,44,52,56,44,53,51,44,52,52,44,53,50,44,52,57,44,52,52,44,53,49,44,53,48,44,52,52,44,52,57,44,52,56,44,53,48,44,52,52,44,52,57,44,52,57,44,52,57,44,52,52,44,52,57,44,52,57,44,53,50,44,52,52,44,53,49,44,53,48,44,52,52,44,52,57,44,52,56,44,53,51,44,52,52,44,53,49,44,53,48,44,52,52,44,52,57,44,52,56,44,53,51,44,52,52,44,52,57,44,52,57,44,52,56,44,52,52,44,53,49,44,53,48,44,52,52,44,53,55,44,52,57,44,52,52,44,53,51,44,52,57,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,52,57,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,53,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,52,57,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,52,57,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,52,57,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,52,57,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,56,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,54,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,50,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,51,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,53,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,52,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,50,44,53,55,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,48,44,52,52,44,53,51,44,53,48,44,52,52,44,53,50,44,53,50,44,52,52,44,53,51,44,53,49,44,52,52,44,53,51,44,52,57,44,52,52,44,53,50,44,53,5 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.