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/RaRCTF/2021/web/MAAS/app/app.py | ctfs/RaRCTF/2021/web/MAAS/app/app.py | from flask import Flask, render_template, request, session, redirect, jsonify
import requests
import jsonschema
import os
import json
import sys
app = Flask(__name__)
ERR_MISSING = "Missing required parameters"
@app.route('/')
def index():
html = """<html><head><title>MAAS</title></head>
<body><a href=/calculator>Calculator</a><br>
<a href=/notes>Notes</a><br>
<a href=/manager>Manager</a>"""
return html
@app.route('/calculator', methods=["POST", "GET"])
def calculator():
if request.method == "GET":
return render_template('calculator.html')
mode = request.form.get('mode')
if not mode:
return ERR_MISSING, 422
if mode == 'checkers':
value = request.form.get('value')
if not value:
return ERR_MISSING, 422
body = {"value": value}
if request.form.get('even'):
body['even'] = True
elif request.form.get('odd'):
body['odd'] = True
elif request.form.get('number'):
body['number'] = True
else:
return ERR_MISSING, 422
r = requests.post('http://calculator:5000/checkers', data=body)
return render_template('calculator.html', tab='checkers', result=r.text)
elif mode == 'arithmetic':
n1 = request.form.get('n1')
n2 = request.form.get('n2')
if not n1 or not n2:
return ERR_MISSING, 422
body = {"n1": n1, "n2": n2}
if request.form.get('add'):
body['add'] = True
elif request.form.get('sub'):
body['sub'] = True
elif request.form.get('div'):
body['div'] = True
elif request.form.get('mul'):
body['mul'] = True
else:
return ERR_MISSING, 422
r = requests.post('http://calculator:5000/arithmetic', data=body)
return render_template('calculator.html', tab='arithmetic', result=r.text)
@app.route('/notes')
def notes_page():
html = """
<head>
<title>Notes</title>
<link rel="stylesheet" href="static/css/style.css"/>
<script src="static/js/app.js"></script>
</head>
<body>
<ul>
<li><a href="/calculator">Calculator</a></li>
<li><a href="/notes">Notes</a></li>
<li><a href="/manager">Manager</a></li>
</ul><hr><br>
<a href=/notes/register>Register</a>"""
return html
@app.route('/notes/register', methods=["GET", "POST"])
def register():
if request.method == "GET":
return render_template('register.html')
data = {"mode": "register", "username": request.form.get("username")}
requests.post("http://notes:5000/useraction", data=data)
session["notes-username"] = request.form.get("username")
return redirect("/notes/profile")
def render_bio(username, userdata):
data = {"username": username,
"mode": "bioget"}
r = requests.post("http://notes:5000/useraction", data=data)
try:
r = requests.post("http://notes:5000/render", json={"bio": r.text, "data": userdata})
return r.text
except:
return "Error in bio"
def userdata(username):
data = {"username": session.get("notes-username"),
"mode": "getdata"}
r = requests.post("http://notes:5000/useraction", data=data)
data = json.loads(r.text)
if len(data) > 0:
return json.loads(r.text)[0]
else:
return {}
@app.route('/notes/profile', methods=["POST", "GET"])
def profile():
username = session.get('notes-username')
if not username:
return redirect('/notes/register')
uid = requests.get(f"http://notes:5000/getid/{username}").text
if request.method == "GET":
return render_template("profile.html",
bio=render_bio(username, userdata(username)),
userid=uid
)
mode = request.form.get("mode")
if mode == "adddata":
data = {"key": request.form.get("key"), "value": request.form.get("value"),
"username": username,
"mode": "adddata"}
requests.post("http://notes:5000/useraction", data=data)
elif mode == "bioadd":
data = {"bio": request.form.get("bio"),
"username": username,
"mode": "bioadd"}
requests.post("http://notes:5000/useraction", data=data)
elif mode == "keytransfer":
data = {"username": username,
"host": request.form.get("host"),
"port": request.form.get("port"),
"key": request.form.get("key"),
"mode": "keytransfer"}
requests.post("http://notes:5000/useraction", data=data)
return render_template("profile.html",
bio=render_bio(username, userdata(username)),
userid=uid
)
@app.route("/manager/login", methods=["POST"])
def manager_login():
username = request.form.get("username")
password = request.form.get("password")
r = requests.post("http://manager:5000/login", json={
"username": username,
"password": password
})
response = r.json()
if response.get('error'):
return response['error'], 403
session['managerid'] = response['uid']
session['managername'] = response['name']
if response.get('flag'):
session['flag'] = response['flag']
return redirect("/manager")
@app.route("/manager/update", methods=["POST"])
def manager_update():
schema = {"type": "object",
"properties": {
"id": {
"type": "number",
"minimum": int(session['managerid'])
},
"password": {
"type": "string",
"minLength": 10
}
}}
try:
jsonschema.validate(request.json, schema)
except jsonschema.exceptions.ValidationError:
return jsonify({"error": f"Invalid data provided"})
return jsonify(requests.post("http://manager:5000/update",
data=request.get_data()).json())
@app.route("/manager")
def manager_index():
return render_template("manager.html",
username=session.get("managername"),
flag=session.get("flag")
)
if __name__ == '__main__':
app.config["SECRET_KEY"] = os.urandom(24)
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/MAAS/manager/app.py | ctfs/RaRCTF/2021/web/MAAS/manager/app.py | from flask import Flask, request, jsonify
import requests
import redis
import os
from binascii import hexlify
app = Flask(__name__)
@app.before_first_request
def setup():
red = redis.Redis(host="manager_users")
red.set("current", 0)
add_user("admin", hexlify(os.urandom(16)).decode())
def get_user(name=None, uid=None):
if name == "current":
return None
red = redis.Redis(host="manager_users")
if uid is not None:
user = red.get(str(uid))
if user is not None:
user, password = user.decode().split(",")
return uid, user, password
return None
elif name is not None:
for key in red.scan_iter("*"):
if key.decode() == "current":
continue
user = red.get(key)
if user is not None:
user, password = user.decode().split(",")
if user == name:
return int(key.decode()), user, password
else:
return None
def add_user(name, password):
if name == "current":
return None
red = redis.Redis(host="manager_users")
uid = str(red.get("current").decode())
red.incr("current", 1)
red.set(uid, f"{name},{password}")
return uid
@app.route("/login", methods=["POST"])
def login():
user = request.json['username']
password = request.json['password']
entry = get_user(name=user)
if entry:
if entry[2] == password:
data = {"uid": entry[0], "name": user}
if user == "admin" and entry[0] == 0:
data['flag'] = open("/flag.txt").read()
return jsonify(data)
else:
return jsonify({"error": "Incorrect password"})
else:
return jsonify({"uid": add_user(user, password), "name": user})
@app.route("/update", methods=["POST"])
def update():
return jsonify(requests.post("http://manager_updater:8080/",
data=request.get_data()).json())
app.run(host="0.0.0.0", port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/MAAS/calculator/app.py | ctfs/RaRCTF/2021/web/MAAS/calculator/app.py | from flask import Flask, request
import requests
app = Flask(__name__)
@app.route('/checkers', methods=["POST"])
def checkers():
if request.form.get('even'):
r = requests.get(f'http://checkers:3000/is_even?n={request.form.get("value")}')
elif request.form.get('odd'):
r = requests.get(f'http://checkers:3000/is_odd?n={request.form.get("value")}')
elif request.form.get('number'):
r = requests.get(f'http://checkers:3000/is_number?n={request.form.get("value")}')
result = r.json()
res = result.get('result')
if not res:
return str(result.get('error'))
return str(res)
@app.route('/arithmetic', methods=["POST"])
def arithmetic():
if request.form.get('add'):
r = requests.get(f'http://arithmetic:3000/add?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
elif request.form.get('sub'):
r = requests.get(f'http://arithmetic:3000/sub?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
elif request.form.get('div'):
r = requests.get(f'http://arithmetic:3000/div?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
elif request.form.get('mul'):
r = requests.get(f'http://arithmetic:3000/mul?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
result = r.json()
res = result.get('result')
if not res:
return str(result.get('error'))
try:
res_type = type(eval(res))
if res_type is int or res_type is float:
return str(res)
else:
return "Result is not a number"
except NameError:
return "Result is invalid"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/MAAS/notes/app.py | ctfs/RaRCTF/2021/web/MAAS/notes/app.py | from flask import Flask, request, jsonify, render_template_string
import redis
import requests
import re
import json
import sys
app = Flask(__name__)
@app.route('/getid/<username>')
def getid(username):
red = redis.Redis(host="redis_users")
return red.get(username).decode()
@app.route('/useraction', methods=["POST"])
def useraction():
mode = request.form.get("mode")
username = request.form.get("username")
if mode == "register":
r = requests.get('http://redis_userdata:5000/adduser')
port = int(r.text)
red = redis.Redis(host="redis_users")
red.set(username, port)
return ""
elif mode == "adddata":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
requests.post(f"http://redis_userdata:5000/putuser/{port}", json={
request.form.get("key"): request.form.get("value")
})
return ""
elif mode == "getdata":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
r = requests.get(f"http://redis_userdata:5000/getuser/{port}")
return jsonify(r.json())
elif mode == "bioadd":
bio = request.form.get("bio")
bio.replace(".", "").replace("_", "").\
replace("{", "").replace("}", "").\
replace("(", "").replace(")", "").\
replace("|", "")
bio = re.sub(r'\[\[([^\[\]]+)\]\]', r'{{data["\g<1>"]}}', bio)
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
requests.post(f"http://redis_userdata:5000/bio/{port}", json={
"bio": bio
})
return ""
elif mode == "bioget":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
r = requests.get(f"http://redis_userdata:5000/bio/{port}")
return r.text
elif mode == "keytransfer":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
red2 = redis.Redis(host="redis_userdata",
port=int(port))
red2.migrate(request.form.get("host"),
request.form.get("port"),
[request.form.get("key")],
0, 1000,
copy=True, replace=True)
return ""
@app.route("/render", methods=["POST"])
def render_bio():
data = request.json.get('data')
if data is None:
data = {}
return render_template_string(request.json.get('bio'), data=data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/MAAS/notes/redis_userdata/app.py | ctfs/RaRCTF/2021/web/MAAS/notes/redis_userdata/app.py | from flask import Flask, request, jsonify
import redis
import random
import os
import os
app = Flask(__name__)
@app.route('/adduser')
def adduser():
port = random.randint(50000, 60000)
if os.system(f"redis-server --port {port} --daemonize yes --protected-mode no") == 0:
return str(port), 200
else:
return "0", 500
@app.route('/getuser/<port>', methods=["GET"])
def getuser(port):
r = redis.Redis(port=port)
res = []
for key in r.scan_iter("*"):
res.append({key.decode(): r.get(key).decode()})
return jsonify(res)
@app.route('/putuser/<port>', methods=["POST"])
def putuser(port):
r = redis.Redis(port=port)
r.mset(request.json)
return "", 200
@app.route("/bio/<port>", methods=["POST", "GET"])
def bio(port):
if request.method == "GET":
if os.path.exists(f"/tmp/{port}.txt"):
with open(f"/tmp/{port}.txt") as f:
return f.read()
else:
return ""
elif request.method == "POST":
with open(f"/tmp/{port}.txt", 'w') as f:
f.write(request.json.get("bio"))
return ""
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/maas2/app/app.py | ctfs/RaRCTF/2021/web/maas2/app/app.py | from flask import Flask, render_template, request, session, redirect, jsonify
import requests
import jsonschema
import os
import json
import sys
app = Flask(__name__)
ERR_MISSING = "Missing required parameters"
@app.route('/')
def index():
html = """<html><head><title>MAAS</title></head>
<body><a href=/calculator>Calculator</a><br>
<a href=/notes>Notes</a><br>
<a href=/manager>Manager</a>"""
return html
@app.route('/calculator', methods=["POST", "GET"])
def calculator():
if request.method == "GET":
return render_template('calculator.html')
mode = request.form.get('mode')
if not mode:
return ERR_MISSING, 422
if mode == 'checkers':
value = request.form.get('value')
if not value:
return ERR_MISSING, 422
body = {"value": value}
if request.form.get('even'):
body['even'] = True
elif request.form.get('odd'):
body['odd'] = True
elif request.form.get('number'):
body['number'] = True
else:
return ERR_MISSING, 422
r = requests.post('http://calculator:5000/checkers', data=body)
return render_template('calculator.html', tab='checkers', result=r.text)
elif mode == 'arithmetic':
n1 = request.form.get('n1')
n2 = request.form.get('n2')
if not n1 or not n2:
return ERR_MISSING, 422
body = {"n1": n1, "n2": n2}
if request.form.get('add'):
body['add'] = True
elif request.form.get('sub'):
body['sub'] = True
elif request.form.get('div'):
body['div'] = True
elif request.form.get('mul'):
body['mul'] = True
else:
return ERR_MISSING, 422
r = requests.post('http://calculator:5000/arithmetic', data=body)
return render_template('calculator.html', tab='arithmetic', result=r.text)
@app.route('/notes')
def notes_page():
html = """
<head>
<title>Notes</title>
<link rel="stylesheet" href="static/css/style.css"/>
<script src="static/js/app.js"></script>
</head>
<body>
<ul>
<li><a href="/calculator">Calculator</a></li>
<li><a href="/notes">Notes</a></li>
<li><a href="/manager">Manager</a></li>
</ul><hr><br>
<a href=/notes/register>Register</a>"""
return html
@app.route('/notes/register', methods=["GET", "POST"])
def register():
if request.method == "GET":
return render_template('register.html')
data = {"mode": "register", "username": request.form.get("username")}
requests.post("http://notes:5000/useraction", data=data)
session["notes-username"] = request.form.get("username")
return redirect("/notes/profile")
def render_bio(username, userdata):
data = {"username": username,
"mode": "bioget"}
r = requests.post("http://notes:5000/useraction", data=data)
try:
r = requests.post("http://notes:5000/render", json={"bio": r.text, "data": userdata})
return r.text
except:
return "Error in bio"
def userdata(username):
data = {"username": session.get("notes-username"),
"mode": "getdata"}
r = requests.post("http://notes:5000/useraction", data=data)
data = json.loads(r.text)
if len(data) > 0:
return json.loads(r.text)[0]
else:
return {}
@app.route('/notes/profile', methods=["POST", "GET"])
def profile():
username = session.get('notes-username')
if not username:
return redirect('/notes/register')
uid = requests.get(f"http://notes:5000/getid/{username}").text
if request.method == "GET":
return render_template("profile.html",
bio=render_bio(username, userdata(username)),
userid=uid
)
mode = request.form.get("mode")
if mode == "adddata":
data = {"key": request.form.get("key"), "value": request.form.get("value"),
"username": username,
"mode": "adddata"}
requests.post("http://notes:5000/useraction", data=data)
elif mode == "bioadd":
data = {"bio": request.form.get("bio"),
"username": username,
"mode": "bioadd"}
requests.post("http://notes:5000/useraction", data=data)
elif mode == "keytransfer":
data = {"username": username,
"host": request.form.get("host"),
"port": request.form.get("port"),
"key": request.form.get("key"),
"mode": "keytransfer"}
requests.post("http://notes:5000/useraction", data=data)
return render_template("profile.html",
bio=render_bio(username, userdata(username)),
userid=uid
)
@app.route("/manager/login", methods=["POST"])
def manager_login():
username = request.form.get("username")
password = request.form.get("password")
r = requests.post("http://manager:5000/login", json={
"username": username,
"password": password
})
response = r.json()
if response.get('error'):
return response['error'], 403
session['managerid'] = response['uid']
session['managername'] = response['name']
if response.get('flag'):
session['flag'] = response['flag']
return redirect("/manager")
@app.route("/manager/update", methods=["POST"])
def manager_update():
uid = int(session['managerid'])
schema = {"type": "object",
"properties": {
"id": {
"type": "number",
"minimum": uid
},
"password": {
"type": "string",
"minLength": 10
}
}}
try:
jsonschema.validate(request.json, schema)
except jsonschema.exceptions.ValidationError:
return jsonify({"error": f"Invalid data provided"})
return jsonify(requests.post(f"http://manager:5000/update?id={uid}",
data=request.get_data()).json(),
headers={"Content-Type": "application/json"})
@app.route("/manager")
def manager_index():
return render_template("manager.html",
username=session.get("managername"),
flag=session.get("flag")
)
if __name__ == '__main__':
app.config["SECRET_KEY"] = os.urandom(24)
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/maas2/manager/app.py | ctfs/RaRCTF/2021/web/maas2/manager/app.py | from flask import Flask, request, jsonify
import requests
import redis
import jsonschema
import json
import os
from binascii import hexlify
app = Flask(__name__)
@app.before_first_request
def setup():
red = redis.Redis(host="manager_users")
red.set("current", 0)
add_user("admin", hexlify(os.urandom(16)).decode())
def get_user(name=None, uid=None):
if name == "current":
return None
red = redis.Redis(host="manager_users")
if uid is not None:
user = red.get(str(uid))
if user is not None:
user, password = user.decode().split(",")
return uid, user, password
return None
elif name is not None:
for key in red.scan_iter("*"):
if key.decode() == "current":
continue
user = red.get(key)
if user is not None:
user, password = user.decode().split(",")
if user == name:
return int(key.decode()), user, password
else:
return None
def add_user(name, password):
if name == "current":
return None
red = redis.Redis(host="manager_users")
uid = str(red.get("current").decode())
red.incr("current", 1)
red.set(uid, f"{name},{password}")
return uid
@app.route("/login", methods=["POST"])
def login():
user = request.json['username']
password = request.json['password']
entry = get_user(name=user)
if entry:
if entry[2] == password:
data = {"uid": entry[0], "name": user}
if user == "admin" and entry[0] == 0:
data['flag'] = open("/flag.txt").read()
return jsonify(data)
else:
return jsonify({"error": "Incorrect password"})
else:
return jsonify({"uid": add_user(user, password), "name": user})
@app.route("/update", methods=["POST"])
def update():
uid = int(request.args['id'])
schema = {"type": "object",
"properties": {
"id": {
"type": "number",
"minimum": uid
},
"password": {
"type": "string",
"minLength": 10
}
}}
payload = json.loads(request.get_data())
try:
jsonschema.validate(payload, schema)
except jsonschema.exceptions.ValidationError as e:
return jsonify({"error": f"Invalid data provided"})
return jsonify(requests.post("http://manager_updater:8080/",
data=request.get_data()).json())
app.run(host="0.0.0.0", port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/maas2/calculator/app.py | ctfs/RaRCTF/2021/web/maas2/calculator/app.py | from flask import Flask, request
import requests
app = Flask(__name__)
import builtins
@app.route('/checkers', methods=["POST"])
def checkers():
if request.form.get('even'):
r = requests.get(f'http://checkers:3000/is_even?n={request.form.get("value")}')
elif request.form.get('odd'):
r = requests.get(f'http://checkers:3000/is_odd?n={request.form.get("value")}')
elif request.form.get('number'):
r = requests.get(f'http://checkers:3000/is_number?n={request.form.get("value")}')
result = r.json()
res = result.get('result')
if not res:
return str(result.get('error'))
return str(res)
@app.route('/arithmetic', methods=["POST"])
def arithmetic():
if request.form.get('add'):
r = requests.get(f'http://arithmetic:3000/add?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
elif request.form.get('sub'):
r = requests.get(f'http://arithmetic:3000/sub?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
elif request.form.get('div'):
r = requests.get(f'http://arithmetic:3000/div?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
elif request.form.get('mul'):
r = requests.get(f'http://arithmetic:3000/mul?n1={request.form.get("n1")}&n2={request.form.get("n2")}')
result = r.json()
res = result.get('result')
if not res:
return str(result.get('error'))
try:
res_type = type(eval(res, builtins.__dict__, {})))
if res_type is int or res_type is float:
return str(res)
else:
return "Result is not a number"
except NameError:
return "Result is invalid"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/maas2/notes/app.py | ctfs/RaRCTF/2021/web/maas2/notes/app.py | from flask import Flask, request, jsonify, render_template_string
import redis
import requests
import re
import json
import sys
app = Flask(__name__)
@app.route('/getid/<username>')
def getid(username):
red = redis.Redis(host="redis_users")
return red.get(username).decode()
@app.route('/useraction', methods=["POST"])
def useraction():
mode = request.form.get("mode")
username = request.form.get("username")
if mode == "register":
r = requests.get('http://redis_userdata:5000/adduser')
port = int(r.text)
red = redis.Redis(host="redis_users")
red.set(username, port)
return ""
elif mode == "adddata":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
requests.post(f"http://redis_userdata:5000/putuser/{port}", json={
request.form.get("key"): request.form.get("value")
})
return ""
elif mode == "getdata":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
r = requests.get(f"http://redis_userdata:5000/getuser/{port}")
return jsonify(r.json())
elif mode == "bioadd":
bio = request.form.get("bio")
bio = bio.replace(".", "").replace("_", "").\
replace("{", "").replace("}", "").\
replace("(", "").replace(")", "").\
replace("|", "")
bio = re.sub(r'\[\[([^\[\]]+)\]\]', r'{{data["\g<1>"]}}', bio)
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
requests.post(f"http://redis_userdata:5000/bio/{port}", json={
"bio": bio
})
return ""
elif mode == "bioget":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
r = requests.get(f"http://redis_userdata:5000/bio/{port}")
return r.text
elif mode == "keytransfer":
red = redis.Redis(host="redis_users")
port = red.get(username).decode()
red2 = redis.Redis(host="redis_userdata",
port=int(port))
red2.migrate(request.form.get("host"),
request.form.get("port"),
[request.form.get("key")],
0, 1000,
copy=True, replace=True)
return ""
@app.route("/render", methods=["POST"])
def render_bio():
data = request.json.get('data')
if data is None:
data = {}
return render_template_string(request.json.get('bio'), data=data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/maas2/notes/redis_userdata/app.py | ctfs/RaRCTF/2021/web/maas2/notes/redis_userdata/app.py | from flask import Flask, request, jsonify
import redis
import random
import os
import os
app = Flask(__name__)
@app.route('/adduser')
def adduser():
port = random.randint(50000, 60000)
if os.system(f"redis-server --port {port} --daemonize yes --protected-mode no") == 0:
return str(port), 200
else:
return "0", 500
@app.route('/getuser/<port>', methods=["GET"])
def getuser(port):
r = redis.Redis(port=port)
res = []
for key in r.scan_iter("*"):
res.append({key.decode(): r.get(key).decode()})
return jsonify(res)
@app.route('/putuser/<port>', methods=["POST"])
def putuser(port):
r = redis.Redis(port=port)
r.mset(request.json)
return "", 200
@app.route("/bio/<port>", methods=["POST", "GET"])
def bio(port):
if request.method == "GET":
if os.path.exists(f"/tmp/{port}.txt"):
with open(f"/tmp/{port}.txt") as f:
return f.read()
else:
return ""
elif request.method == "POST":
with open(f"/tmp/{port}.txt", 'w') as f:
f.write(request.json.get("bio"))
return ""
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/lemonthinker/app/generate.py | ctfs/RaRCTF/2021/web/lemonthinker/app/generate.py | import os
from PIL import Image, ImageDraw, ImageFont
import sys
font = ImageFont.truetype('static/generator/comic-sans.ttf', size=48)
outfile = sys.argv[1]
text = sys.argv[2]
if len(text) > 1000: # Too much text :lemonthink:
text = "Too long!"
width, height = 512, 562
img = Image.new('RGB', (width, height), color=(255, 255, 255))
canvas = ImageDraw.Draw(img)
chunks = []
chunk = ""
for char in text:
chunk += char
text_width, text_height = canvas.textsize(chunk, font=font)
if text_width >= (width-20):
chunks.append(chunk[:-1])
chunk = char
if len(chunks) == 0:
chunks.append(chunk)
if chunks[-1] != chunk:
chunks.append(chunk)
for i,chunk in enumerate(chunks):
text_width, text_height = canvas.textsize(chunk, font=font)
x_pos = int((width - text_width) / 2) + 10
y_pos = 15 + i * 100
canvas.text((x_pos, y_pos), chunk, font=font, fill='#000000')
if "rarctf" in text: # Don't try and exfiltrate flags from here :lemonthink:
img = Image.open("static/generator/noleek.png")
img.save(f"static/images/{outfile}")
else:
img2 = Image.open('static/generator/lemonthink.png')
img.paste(img2, (0, 0), img2.convert('RGBA'))
if len(chunks) > 1:
img3 = Image.open("static/generator/move.png").convert('RGBA')
img3.paste(img, (170,42), img.convert('RGBA'))
img3.save(f"static/images/{outfile}")
else:
img.save(f"static/images/{outfile}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RaRCTF/2021/web/lemonthinker/app/app.py | ctfs/RaRCTF/2021/web/lemonthinker/app/app.py | from flask import Flask, request, redirect, url_for
import os
import random
import string
import time # lemonthink
clean = time.time()
app = Flask(__name__)
chars = list(string.ascii_letters + string.digits)
@app.route('/')
def main():
return open("index.html").read()
@app.route('/generate', methods=['POST'])
def upload():
global clean
if time.time() - clean > 60:
os.system("rm static/images/*")
clean = time.time()
text = request.form.getlist('text')[0]
text = text.replace("\"", "")
filename = "".join(random.choices(chars,k=8)) + ".png"
os.system(f"python3 generate.py {filename} \"{text}\"")
return redirect(url_for('static', filename='images/' + filename), code=301)
if __name__ == "__main__":
app.run("0.0.0.0",1002)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2018/Quals/SignatureServer/server.py | ctfs/CTFZone/2018/Quals/SignatureServer/server.py | #!/usr/bin/python
import sys
import hashlib
import logging
import SocketServer
import base64
from flag import secret
from checksum_gen import WinternizChecksum
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(ch)
HASH_LENGTH=32
CHECKSUM_LENGTH=4
MESSAGE_LENGTH=32
CHANGED_MESSAGE_LENGTH=MESSAGE_LENGTH+CHECKSUM_LENGTH
BITS_PER_BYTE=8
show_flag_command="show flag"+(MESSAGE_LENGTH-9)*"\xff"
admin_command="su admin"+(MESSAGE_LENGTH-8)*"\x00"
PORT = 1337
def extend_signature_key(initial_key):
full_sign_key=str(initial_key)
for i in range(0,255):
for j in range(0,CHANGED_MESSAGE_LENGTH):
full_sign_key+=hashlib.sha256(full_sign_key[j*HASH_LENGTH+i*CHANGED_MESSAGE_LENGTH*HASH_LENGTH:(j+1)*HASH_LENGTH+i*CHANGED_MESSAGE_LENGTH*HASH_LENGTH]).digest()
return full_sign_key
class Signer:
def __init__(self):
with open("/dev/urandom","rb") as f:
self.signkey=f.read(HASH_LENGTH*CHANGED_MESSAGE_LENGTH)
self.full_sign_key=extend_signature_key(self.signkey)
self.wc=WinternizChecksum()
self.user_is_admin=False
def sign_byte(self,a,ind):
assert(0<=a<=255)
signature=self.full_sign_key[(CHANGED_MESSAGE_LENGTH*a+ind)*HASH_LENGTH:(CHANGED_MESSAGE_LENGTH*a+ind+1)*HASH_LENGTH]
return signature
def sign(self,data):
decoded_data=base64.b64decode(data)
if len(decoded_data)>MESSAGE_LENGTH:
return "Error: message too large"
if decoded_data==show_flag_command or decoded_data==admin_command:
return "Error: nice try, punk"
decoded_data+=(MESSAGE_LENGTH-len(decoded_data))*"\xff"
decoded_data+=self.wc.generate(decoded_data)
signature=""
for i in range(0, CHANGED_MESSAGE_LENGTH):
signature+=self.sign_byte(ord(decoded_data[i]),i)
return base64.b64encode(decoded_data)+','+base64.b64encode(signature)
def execute_command(self,data_sig):
(data_with_checksum, signature)=map(base64.b64decode,data_sig.split(','))
data=data_with_checksum[:MESSAGE_LENGTH]
data_checksummed=data+self.wc.generate(data)
if data_checksummed!=data_with_checksum:
return "Error: wrong checksum!"
signature_for_comparison=""
for i in range(0, CHANGED_MESSAGE_LENGTH):
signature_for_comparison+=self.sign_byte(ord(data_with_checksum[i]),i)
if signature!=signature_for_comparison:
return "Error: wrong signature!"
if data==admin_command:
self.user_is_admin=True
return "Hello, admin"
if data==show_flag_command:
if self.user_is_admin:
return "The flag is %s"%secret
else:
return "Only admin can get the flag\n"
else:
return "Unknown command\n"
def process(data,signer):
[query,params]=data.split(':')
params=params.rstrip("\n")
if query=="hello":
return "Hi"
elif query=="sign":
return signer.sign(params)
elif query=="execute_command":
return signer.execute_command(params)
else:
return "bad query"
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
signer=Signer()
logger.info("%s client sconnected" % self.client_address[0])
self.request.sendall("Welcome to the Tiny Signature Server!\nYou can sign any messages except for controlled ones\n")
while True:
data = self.request.recv(2048)
try:
ret = process(data,signer)
except Exception:
ret = 'Error'
try:
self.request.sendall(ret + '\n')
except Exception:
break
def finish(self):
logger.info("%s client disconnected" % self.client_address[0])
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == '__main__':
server = ThreadedTCPServer(('0.0.0.0', PORT), ThreadedTCPRequestHandler)
server.allow_reuse_address = True
server.serve_forever()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2018/Quals/FederationWorkflowSystem/client.py | ctfs/CTFZone/2018/Quals/FederationWorkflowSystem/client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import socket
from time import sleep
from Crypto.Cipher import AES
from base64 import standard_b64decode
class SecureClient:
def __init__(self):
self.msg_end = '</msg>'
self.msg_wrong_pin = 'BAD_PIN'
self.aes_key = 'aes.key'
self.host = 'crypto-04.v7frkwrfyhsjtbpfcppnu.ctfz.one'
self.port = 7331
self.buff_size = 1024
try:
self.greeting()
except KeyboardInterrupt:
exit(0)
def greeting(self):
self.cls()
print('\n ==================================== !!! CONFIDENTIALITY NOTICE !!! ====================================')
print(' || You trying to access high confidential Federation workflow system. ||')
print(' || If you are not authorised to use this system leave it immediately. ||')
print(' || Otherwise incident will be reported and you will be eliminated as it considered by Federation Law. ||')
print(' ========================================================================================================\n')
user_choice = input(' Do you want to proceed? (yes/no) > ')
if user_choice.lower() == 'yes':
print(' Checking user...')
sleep(5)
print(' SUCCESS: ACCESS GRANTED')
print(' Last login time: {0}'.format(self.get_last_login()))
sleep(1)
self.cls()
print('\n Welcome, Head Consul.')
self.main_menu()
else:
print(' Checking user...')
sleep(5)
print(' ERROR: UNAUTHORISED USER')
sleep(1)
print('\n Reporting incident...')
sleep(5)
print(' SUCCESS: INCIDENT REPORTED')
sleep(1)
print('\n Please stay in place and wait for Federation Security Department extraction team.\n')
exit(0)
def main_menu(self):
while True:
print("\n You are authorised to:")
print(" list - view list of available files")
print(" file - request file from server")
print(" admin - use administrative functions")
print(" exit - exit workflow system")
user_choice = input('\n What do you want to do? (list/file/admin/exit) > ')
self.cls()
if user_choice.lower() == 'list':
self.list_files()
elif user_choice.lower() == 'file':
self.view_file()
elif user_choice.lower() == 'admin':
self.admin()
elif user_choice.lower() == 'exit':
exit(0)
else:
print('\n Unrecognized command, try again')
def list_files(self):
file_list = self.get_file_list()
print('\n You are authorised to view listed files:\n')
for file in file_list:
print(' - {0}'.format(file))
def view_file(self):
self.list_files()
filename = input('\n Which file you want to view? > ')
file_content = self.send('file {0}'.format(filename))
if len(file_content) > 0:
plain_content = self.decrypt(file_content)
if len(plain_content) > 0:
print('\n ========================================================================================================')
print(' Content of {0}'.format(plain_content))
print(' ========================================================================================================')
else:
print('\n Seems like you have no decryption key, so you can\'t see any files.')
else:
print('\n Error while requesting file')
def admin(self):
print('\n Access to administrative functions requires additional security check.')
pin = input(' Enter your administrative PIN > ')
response = self.send('admin {0}'.format(pin))
if response == self.msg_wrong_pin:
print('\n Wrong administrative PIN. Incident will be reported.')
else:
print('\n High confidential administrative data: {0}'.format(response))
def decrypt(self, data):
try:
key = open(self.aes_key).read()
cipher = AES.new(key, AES.MODE_ECB)
plain = cipher.decrypt(standard_b64decode(data)).decode('UTF-8')
plain = plain[:-ord(plain[-1])]
return plain
except Exception as ex:
return ''
def get_last_login(self):
return self.send('login')
def get_file_list(self):
files = self.send('list')
if len(files) > 0:
return files.split(',')
else:
return ['no files available']
def send(self, data):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.host, self.port))
sock.send('{0}{1}'.format(data, self.msg_end).encode('UTF-8'))
response = self.recv_until(sock, self.msg_end)
sock.close()
return response
except Exception as ex:
return ''
def recv_until(self, sock, end):
try:
recv = sock.recv(self.buff_size).decode('utf-8')
while recv.find(end) == -1:
recv += sock.recv(self.buff_size).decode('utf-8')
return recv[:recv.find(end)]
except Exception as ex:
return ''
def cls(self):
os.system('cls' if os.name == 'nt' else 'clear')
if __name__ == '__main__':
secure_client = SecureClient()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2018/Quals/FederationWorkflowSystem/server.py | ctfs/CTFZone/2018/Quals/FederationWorkflowSystem/server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import hmac
import socket
from hashlib import sha1
from Crypto.Cipher import AES
from struct import pack, unpack
from threading import Thread, Lock
from base64 import standard_b64encode
from time import time, sleep, strftime
class SecureServer:
def __init__(self):
self.msg_end = '</msg>'
self.msg_not_found = 'NOT_FOUND'
self.msg_wrong_pin = 'BAD_PIN'
self.lock = Lock()
self.log_path = '../top_secret/server.log'
self.real_flag = '../top_secret/real.flag'
self.aes_key = '../top_secret/aes.key'
self.totp_key = 'totp.secret'
self.files_available = [
'lorem.txt',
'flag.txt',
'admin.txt',
'password.txt'
]
self.host = '0.0.0.0'
self.port = 7331
self.buff_size = 1024
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.listen(50)
self.listener = Thread(target=self.listen)
self.listener.daemon = True
self.listener.start()
self.log('Server started')
def listen(self):
while True:
try:
client, address = self.sock.accept()
client.settimeout(30)
sock_thread = Thread(target=self.handle, args=(client, address))
sock_thread.daemon = True
sock_thread.start()
self.log('Client {0} connected'.format(address[0]))
except Exception as ex:
self.log(ex)
def handle(self, client, address):
data = self.recv_until(client, self.msg_end)
self.log('Got message from client {0}: {1}'.format(address[0], data))
args = data.split(' ', 1)
command = args[0].strip()
if command == 'list':
self.send_list_files(client, address)
elif command == 'login':
self.send_login_time(client, address)
elif command == 'file':
if len(args) != 2:
self.send(client, 'Bad request')
else:
self.send_file_data(args[1], client, address)
elif command == 'admin':
if len(args) != 2:
self.send(client, 'Bad request')
else:
self.send_admin_token(args[1], client, address)
else:
self.send(client, 'Bad request or timed out')
client.close()
def send_list_files(self, client, address):
self.send(client, ','.join(self.files_available))
self.log('Sending available files list to client {0}'.format(address[0]))
def send_login_time(self, client, address):
self.send(client, int(time()))
self.log('Client auth from {0}'.format(address[0]))
def send_file_data(self, file, client, address):
content = self.read_file(file)
response = '{0}: {1}'.format(file, content)
encrypted_response = self.encrypt(response)
self.send(client, encrypted_response)
self.log('Sending file "{0}" to client {1}'.format(file, address[0]))
def send_admin_token(self, client_pin, client, address):
try:
if self.check_totp(client_pin):
response = 'flag: {0}'.format(open(self.real_flag).read())
self.send(client, response)
self.log('Sending admin token to client {0}'.format(address[0]))
else:
self.send(client, self.msg_wrong_pin)
self.log('Wrong pin from client {0}'.format(address[0]))
except Exception as ex:
self.log(ex)
self.send(client, 'Bad request')
def check_totp(self, client_pin):
try:
secret = open(self.totp_key).read()
server_pin = self.totp(secret)
return client_pin == server_pin
except Exception as ex:
self.log(ex)
return False
def totp(self, secret):
counter = pack('>Q', int(time()) // 30)
totp_hmac = hmac.new(secret.encode('UTF-8'), counter, sha1).digest()
offset = totp_hmac[19] & 15
totp_pin = str((unpack('>I', totp_hmac[offset:offset + 4])[0] & 0x7fffffff) % 1000000)
return totp_pin.zfill(6)
def encrypt(self, data):
block_size = 16
data = data.encode('utf-8')
pad = block_size - len(data) % block_size
data = data + (pad * chr(pad)).encode('utf-8')
key = open(self.aes_key).read()
cipher = AES.new(key, AES.MODE_ECB)
return standard_b64encode(cipher.encrypt(data)).decode('utf-8')
def read_file(self, file):
try:
clean_path = self.sanitize(file)
if clean_path is not None:
return open(clean_path).read()
else:
return self.msg_not_found
except Exception as ex:
self.log(ex)
return self.msg_not_found
def sanitize(self, file):
try:
if file.find('\x00') == -1:
file_name = file
else:
file_name = file[:file.find('\x00')]
file_path = os.path.realpath('files/{0}'.format(file_name))
if file_path.startswith(os.getcwd()):
return file_path
else:
return None
except Exception as ex:
self.log(ex)
return None
def send(self, client, data):
client.send('{0}{1}'.format(data, self.msg_end).encode('UTF-8'))
def recv_until(self, client, end):
try:
recv = client.recv(self.buff_size).decode('utf-8')
while recv.find(end) == -1:
recv += client.recv(self.buff_size).decode('utf-8')
return recv[:recv.find(end)]
except Exception as ex:
self.log(ex)
return ''
def log(self, data):
self.lock.acquire()
print('[{0}] {1}'.format(strftime('%d.%m.%Y %H:%M:%S'), data))
sys.stdout.flush()
self.lock.release()
if __name__ == '__main__':
secure_server = SecureServer()
while True:
try:
sleep(1)
except KeyboardInterrupt:
secure_server.log('Server terminated')
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2018/Quals/BuggyPWN/buggy_pwn.py | ctfs/CTFZone/2018/Quals/BuggyPWN/buggy_pwn.py | #!/usr/bin/python
from ctypes import c_byte,c_ubyte,c_short,c_ushort,c_int,c_uint,c_long,c_ulong
from array import array
from time import sleep
from random import randrange
import SocketServer
from flag import secret
from curses.ascii import isprint
PORT = 1337
def delete_not_printable(s):
return ''.join([x if isprint(x) else "" for x in s])
class CARM:
"""
MemRange class representing one continious memory rectangle.
Directions of reading and writing bytes in MemRange are set by the user.
startx - the X coordinate of memory range starting address
starty - the Y coordinate of memory range starting address
lenx - the length of memory rectangle side parallel to the X axis
leny - the length of memory rectangle side parallel to the Y axis
contents - the actual array containing saved values
restricted - determines whether addressing within one range is restrictive (trying to access something outside with directional read or writes produces and exception) or not (all reads and writes are looped inside the memory range)
"""
class MemRange:
#Simple initialization
def __init__(self,startx,starty,lenx,leny,contents,restricted=True):
assert(len(contents)>=(lenx*leny*2))
contents=contents[:lenx*leny*2]
(self.startx,self.starty,self.lenx,self.leny)=(startx,starty,lenx,leny)
self.restricted=restricted
self.contents=array('B',contents)
#Change restriction on the go
def setRestriction(self,restricted):
self.restricted=restricted
#Check if a certain address is represented inside this memory range by X and Y coordinates
def containsAddr1(self,x,y):
if (self.startx<=x<(self.startx+self.lenx))and (self.starty<=y<(self.starty+self.leny)):
return True
return False
#Check if a register contains an address from this range
def containsAddr2(self,reg):
return self.containsAddr1(reg.real.value,reg.imaginary.value)
#Get relative offset inside the range (should be used privately)
def __getoffset(self,reg):
(sx,sy)=(reg.real.value-self.startx,reg.imaginary.value-self.starty)
return (sx,sy)
#Get single byte at relative offset (should be used privately)
def __getbytebyoffset(self,x,y):
return (self.contents[(x+self.lenx*y)*2],self.contents[(x+self.lenx*y)*2+1])
#Set single byte at relative offset (should be used privately)
def __setbytebyoffset(self,x,y,r,i):
(self.contents[(x+self.lenx*y)*2],self.contents[(x+self.lenx*y)*2+1])=(r,i)
#Convert directional sequence of bytes in the range into an integer for transfer
def getSequence(self,reg,direction,steps):
assert(direction!=CARM.REG(0,0))
(dirx,diry)=(direction.real.value,direction.imaginary.value)
if not self.containsAddr2(reg):
raise Exception("Memory access error\n")
(x1,y1)=self.__getoffset(reg)
(x_full,y_full)=(0,0)
for i in range(0,steps):
if self.restricted:
if x1>=self.lenx or y1>=self.leny or x1<0 or y1<0:
raise Exception("Memory access error\n")
else:
(x1,y1)=(x1%self.lenx,y1%self.lenx)
(x_cur,y_cur)=self.__getbytebyoffset(x1,y1)
(x_full,y_full)=(x_full|x_cur<<(8*i),y_full|y_cur<<(8*i))
(x1,y1)=(x1+dirx,y1+diry)
return (x_full,y_full)
def __setsequence(self,reg,direction,r,im,steps):
assert(direction!=CARM.REG(0,0))
(dirx,diry)=(direction.real.value,direction.imaginary.value)
if not self.containsAddr2(reg):
raise Exception("Memory access error\n")
(x1,y1)=self.__getoffset(reg)
for i in range(0,steps):
if self.restricted:
if x1>=self.lenx or y1>=self.leny or x1<0 or y1<0:
raise Exception("Memory access error\n")
else:
(x1,y1)=(x1%self.lenx,y1%self.lenx)
self.__setbytebyoffset(x1,y1,r&0xff,im&0xff)
(r,im)=(r>>8,im>>8)
(x1,y1)=(x1+dirx,y1+diry)
def writeMemory(self,reg,direction,data,steps):
assert(direction!=CARM.REG(0,0))
(dirx,diry)=(direction.real.value,direction.imaginary.value)
if not self.containsAddr2(reg):
raise Exception("Memory access error\n")
(x1,y1)=self.__getoffset(reg)
for i in range(0,steps):
if self.restricted:
if x1>=self.lenx or y1>=self.leny or x1<0 or y1<0:
raise Exception("Memory access error\n")
else:
(x1,y1)=(x1%self.lenx,y1%self.lenx)
self.__setbytebyoffset(x1,y1,ord(data[i*2]),ord(data[i*2+1]))
#(r,im)=(r>>8,im>>8)
(x1,y1)=(x1+dirx,y1+diry)
def readMemory(self,reg,direction,steps):
assert(direction!=CARM.REG(0,0))
s=''
(dirx,diry)=(direction.real.value,direction.imaginary.value)
if not self.containsAddr2(reg):
raise Exception("Memory access error\n")
(x1,y1)=self.__getoffset(reg)
for i in range(0,steps):
if self.restricted:
if x1>=self.lenx or y1>=self.leny or x1<0 or y1<0:
raise Exception("Memory access error\n")
else:
(x1,y1)=(x1%self.lenx,y1%self.lenx)
(a,b)=self.__getbytebyoffset(x1,y1)
s+=chr(a)+chr(b)
#(r,im)=(r>>8,im>>8)
(x1,y1)=(x1+dirx,y1+diry)
return s
#Load one BYTE with zero extension
def getZBYTE(self,reg,direction):
(x,y)=self.getSequence(reg,direction,1)
return CARM.REG(x,y)
#Load one BYTE with sign extension
def getSBYTE(self,reg,direction):
(x,y)=self.getSequence(reg,direction,1)
(x,y)=((1<<32-(x&1<<7))|x,(1<<32-(y&1<<7))|y)
return CARM.REG(x,y)
#Load one WORD with zero extension
def getZWORD(self,reg,direction):
(x,y)=self.getSequence(reg,direction,2)
return CARM.REG(x,y)
#Load one WORD with sign extension
def getSWORD(self,reg,direction):
(x,y)=self.getSequence(reg,direction,2)
(x,y)=((1<<32-(x&1<<15))|x,(1<<32-(y&1<<15))|y)
return CARM.REG(x,y)
#Load one DWORD
def getDWORD(self,reg,direction):
(x,y)=self.getSequence(reg,direction,4)
return CARM.REG(x,y)
def setBYTE(self,reg,direction,val_reg):
self.__setsequence(reg,direction,val_reg.real.value,val_reg.imaginary.value,1)
def setWORD(self,reg,direction,val_reg):
self.__setsequence(reg,direction,val_reg.real.value,val_reg.imaginary.value,2)
def setDWORD(self,reg,direction,val_reg):
self.__setsequence(reg,direction,val_reg.real.value,val_reg.imaginary.value,4)
def nextAddress(self,reg,direction):
assert(direction!=CARM.REG(0,0))
if self.restricted:
if self.containsAddr2(reg+direction):
return reg+direction
else:
raise Exception("Illegal address")
else:
return CARM.REG((reg.real.value-self.startx+direction.real.value)%self.lenx+self.startx,(reg.imaginary.value-self.starty+direction.imaginary.value)%self.leny+self.starty)
class REG:
def __init__(self,r=0,i=0):
self.real=c_uint(r)
self.imaginary=c_uint(i)
def __add__(self,other):
return CARM.REG(self.real.value+other.real.value,self.imaginary.value+other.imaginary.value)
def __radd__(self,other):
return self.__add__(other)
def __mul__(self,other):
return CARM.REG(self.real.value*other.real.value-self.imaginary.value*other.imaginary.value,self.real.value*other.imaginary.value+self.imaginary.value*other.real.value)
def __rmul__(self,other):
return self.__mul__(other)
def __xor__(self, other):
return CARM.REG(self.real.value^other.real.value,self.imaginary.value^other.imaginary.value)
def __sadd__(self,other):
(r1,i1,r2,i2)=(self.real.value,self.imaginary.value,other.real.value,other.imaginary.value)
(r1,i1,r2,i2)=(r1 if r1<(1<<31) else r1-(1<<32),i1 if i1<(1<<31) else i1-(1<<32),r2 if r2<(1<<31) else r2-(1<<32),i2 if i2<(1<<31) else i2-(1<<32))
return CARM.REG(r1+r2,i1+i2)
def __str__(self):
return '( '+hex(self.real.value)[:-1]+' + '+hex(self.imaginary.value)[:-1]+'i )'
def div_real(self,numb):
return CARM.REG(self.real.value/numb,self.imaginary.value/numb)
def __div__(self,other):
if other.real.value==0 and other.imaginary.value==0:
raise Exception("Can't divide by null")
(r1,i1,r2,i2)=(self.real.value,self.imaginary.value,other.real.value,other.imaginary.value)
(r1,i1,r2,i2)=(r1 if r1<(1<<31) else r1-(1<<32),i1 if i1<(1<<31) else i1-(1<<32),r2 if r2<(1<<31) else r2-(1<<32),i2 if i2<(1<<31) else i2-(1<<32))
(r_f,i_f)=(r1*r2+i1*i2,-r1*i2+i1*r2)
divis=(r2**2+i2**2)
return CARM.REG(r_f/divis,i_f/divis)
def __ovf__(self,other):
return CARM.REG(self.real.value%other.real.value,self.imaginary.value%other.imaginary.value)
def __neg__(self):
return CARM.REG(-self.real.value,-self.imaginary.value)
def __sub__(self,other):
return self.__add__(other.__neg__())
@staticmethod
def toSigned(num):
return num if num<(1<<31) else num-(1<<32)
def real_above(self,other):
return self.real.value>other.real.value
def real_below(self,other):
return self.real.value<other.real.value
def real_equal(self,other):
return self.real.value==other.real.value
def real_more(self,other):
return CARM.REG.toSigned(self.real.value)>CARM.REG.toSigned(other.real.value)
def real_less(self,other):
return CARM.REG.toSigned(self.real.value)<CARM.REG.toSigned(other.real.value)
def imaginary_above(self,other):
return self.imaginary.value>other.imaginary.value
def imaginary_below(self,other):
return self.imaginary.value<other.imaginary.value
def imaginary_equal(self,other):
return self.imaginary.value==other.imaginary.value
def imaginary_more(self,other):
return CARM.REG.toSigned(self.imaginary.value)>CARM.REG.toSigned(other.imaginary.value)
def imaginary_less(self,other):
return CARM.REG.toSigned(self.imaginary.value)<CARM.REG.toSigned(other.imaginary.value)
def __eq__(self,other):
return self.real.value==other.real.value and self.imaginary.value==other.imaginary.value
def __ne__(self,other):
return not self.__eq__(other)
def __mod__(self,other):
return self.__ovf__(other)
def __lt__(self,other):
return self.real.value<other.real.value and self.imaginary.value<other.imaginary.value
def __le__(self,other):
return self.real.value<=other.real.value and self.imaginary.value<=other.imaginary.value
def __gt__(self,other):
return self.real.value>other.real.value and self.imaginary.value>other.imaginary.value
def __ge__(self,other):
return self.real.value>=other.real.value and self.imaginary.value>=other.imaginary.value
#commands=[0x20,]
#hadlers=[self.nop]
def __initializeprogrammemory(self):
self.memory=[
#CARM.MemRange(0x40000,0x40000,30,10,"0\x10\x49\x01 \x01\x00"+" \x01"*600), #Executable code
CARM.MemRange(0x60000,0x60000,300,1,
"\x45\x00\x06\x00\x00\x00\x06\x06\x00\x00"+
"\x00\x00"+
"\x31\x05\x40\x40\x00\x00\x06\x06\x00\x00"+
"\x31\x03\x04\x00\x00\x00\x00\x00\x00\x00"+
"\x31\x06\x01\x00\x00\x00\x00\x00\x00\x00"+
"\x49\x03"+
"\x31\x05\x40\x41\x00\x00\x06\x06\x00\x00"+
"\x31\x03\x09\x00\x00\x00\x00\x00\x00\x00"+
"\x49\x03"+
"\x31\x04\x40\x45\x00\x00\x06\x06\x00\x00"+
"\x31\x01\x00\x01\x00\x00\x00\x00\x00\x00"+
"\x49\x05"+#68
"\x31\x05\x40\x42\x00\x00\x06\x06\x00\x00"+
"\x31\x03\x09\x00\x00\x00\x00\x00\x00\x00"+
"\x49\x03"+
"\x41\x45"+
"\x31\x03\x10\x00\x00\x00\x00\x00\x00\x00"+
"\x49\x02"+
"\x30\x14"
"\x47\x00\x2c\x00\x00\x00\x06\x06\x00\x00"+
"\x31\x05\x40\x43\x00\x00\x06\x06\x00\x00"+
"\x31\x03\x09\x00\x00\x00\x00\x00\x00\x00"+
"\x49\x03"+
"\x49\x05"+
"\x31\x05\x40\x44\x00\x00\x06\x06\x00\x00"+
"\x31\x03\x10\x00\x00\x00\x00\x00\x00\x00"+
"\x49\x03"+
"\x48\x07\x10\x00\x00\x00\x00\x00\x00\x00"+
"\x41\x75"+
"\x41\x23"
"\x49\x02"+
"\x49\x03"+
"\x48\x07\xf0\x00\xff\x00\xff\x00\xff\x00"+
"\x46\x00"+
"\x01"*600), #Executable code
CARM.MemRange(0x60000,0x60001,0x100,1,"\x00"*800), #Stack
CARM.MemRange(0x60040,0x60040,0x10,0x40,"EasyPwn"+"\x00"*0x19+ #16
"How many strings:" +"\x00"*0xf+ #14
"Input: "+"\x00"*0x19+#8
"How many letters:"+"\x00"*0xf+
"Your name please:"+"\x00"*0x0f+#8
"\x00"*0x1000) #data
]
def __initializeregisters(self):
self.eax=CARM.REG(0,0)
self.ebx=CARM.REG(0,0)
self.ecx=CARM.REG(0,0)
self.edx=CARM.REG(0,0)
self.esi=CARM.REG(0,0)
self.edi=CARM.REG(0,0)
self.edid=CARM.REG(0,0)
self.esd=CARM.REG(0,0)
self.edd=CARM.REG(0,0)
self.esp=CARM.REG(0x60100,0x60001)
self.espd=CARM.REG(1,0)
self.eip=CARM.REG(0x60000,0x60000)
self.eipd=CARM.REG(1,0)
self.dataregs=[self.eax,self.ebx,self.ecx,self.edx,self.esi,self.edi,self.edid,self.esp]
self.ZF=False;
self.CF=False;
self.SF=False;
self.OF=False;
self.NO=False;
def __update_states(self):
(self.eax,self.ebx,self.ecx,self.edx,self.esi,self.edi,self.edid,self.esp)=self.dataregs
def __update_states1(self):
self.dataregs=[self.eax,self.ebx,self.ecx,self.edx,self.esi,self.edi,self.edid,self.esp]
def __init__(self,socket):
self.socket=socket.request
self.__initializeregisters()
self.__initializeprogrammemory()
self.commands={
0x00: self.__command_powerdown,
0x20: self.__command_nop,
0x30: self.__command_add,
0x31: self.__command_mov_data,
0x32: self.__command_xor,
0x33: self.__command_rotip,
0x40: self.__command_test,
0x41: self.__command_mov_reg,
0x42: self.__command_mov_data_to_reg,
0x43: self.__command_mov_data_from_reg,
0x45: self.__command_call,
0x46: self.__command_ret,
0x47: self.__command_jmpne,
0x48: self.__command_sub,
0x49: self.__command_syscall,
0x50: self.__command_switch,}
"""
===================
=Commands' section=
===================
"""
#No Operation
def __command_nop(self,amplifier=0):
for mrange in self.memory:
if mrange.containsAddr2(self.eip):
self.eip=mrange.nextAddress(self.eip,self.eipd)
return
raise Exception("Eip not in identifiable memory range\n")
#Shut the emulator down
def __command_powerdown(self,amplifier=0):
return True
#Register addtition
def __command_add(self,amplifier):
inreg=amplifier&0xf
outreg=amplifier>>4
if inreg>len(self.dataregs) or outreg>len(self.dataregs):
raise Exception("Illegal command\n")
self.dataregs[inreg]=self.dataregs[inreg]+self.dataregs[outreg]
self.__update_states()
self.__command_nop()
def __command_xor(self,amplifier):
inreg=amplifier&0xf
outreg=amplifier>>4
if inreg>len(self.dataregs) or outreg>len(self.dataregs):
raise Exception("Illegal command\n")
self.dataregs[inreg]=self.dataregs[inreg].__xor__(self.dataregs[outreg])
self.__update_states()
self.__command_nop()
def __command_switch(self,amplifier):
inreg=amplifier&0xf
if inreg>len(self.dataregs):
raise Exception("Illegal command\n")
self.dataregs[inreg]=CARM.REG(self.dataregs[inreg].imaginary.value,self.dataregs[inreg].real.value)
self.__update_states()
self.__command_nop()
#Register addtition
def __command_mov_reg(self,amplifier):
inreg=amplifier&0xf
outreg=amplifier>>4
if inreg>len(self.dataregs) or outreg>len(self.dataregs):
raise Exception("Illegal command\n")
self.dataregs[inreg]=self.dataregs[outreg]
self.__update_states()
self.__command_nop()
#JUMP to Address
def __command_jump_basic(self,amplifier=0):
self.__command_nop()
for mrange in self.memory:
if mrange.containsAddr2(self.eip):
self.eip=mrange.getDWORD(self.eip,self.eipd)
return
raise Exception("Nowhere to jump")
#Register multiplication
def __comand_mul(self,amplifier):
inreg=amplifier&0xf
outreg=amplifier>>4
if inreg>len(self.dataregs) or outreg>len(self.dataregs):
raise Exception("Illegal command\n")
self.dataregs[inreg]=self.dataregs[inreg]*self.dataregs[outreg]
self.__update_states()
self.__command_nop()
"""
def movd(self,amplifier):
inreg=amplifier&0xf
outreg=amplifier>>4
if inreg>len(self.dataregs) or outreg>1:
raise Exception("Illegal command\n")
if outreg==1:
array[]
"""
def __getMrange(self,reg):
for i in range(0,len(self.memory)):
if self.memory[i].containsAddr2(reg):
return i
raise Exception("Register not in any memory range")
def __command_call(self,amplifier):
self.__command_nop()
reg=self.memory[self.__getMrange(self.eip)].getDWORD(self.eip,self.eipd)
self.esp=CARM.REG(self.esp.real.value-4,self.esp.imaginary.value)
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.memory[self.__getMrange(self.esp)].setDWORD(self.esp,self.espd,self.eip)
self.eip=reg
self.__update_states1()
def __command_sub(self,amplifier):
self.__command_nop()
inreg=amplifier&0xf
if inreg>len(self.dataregs):
raise Exception("Illegal command\n")
reg=self.memory[self.__getMrange(self.eip)].getDWORD(self.eip,self.eipd)
self.esp=self.esp-reg
#self.esp=CARM.REG(self.esp.real.value-4,self.esp.imaginary.value)
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.__update_states1()
def __command_jmpne(self,amplifier):
self.ecx=CARM.REG(self.ecx.real.value-1,self.ecx.imaginary.value)
self.__command_nop()
if self.ecx.real.value!=0:
reg=self.memory[self.__getMrange(self.eip)].getDWORD(self.eip,self.eipd)
self.eip=reg
else:
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.__update_states1()
def __command_ret(self,amplifier):
self.__command_nop()
self.eip=self.memory[self.__getMrange(self.esp)].getDWORD(self.esp,self.espd)
self.esp=CARM.REG(self.esp.real.value+4,self.esp.imaginary.value)
def __command_rotip(self,amplifier):
self.__command_nop()
if amplifier&1:
self.eipd=self.eipd*CARM.REG(0,1)
else:
self.eipd=self.eipd*CARM.REG(0,-1)
def __command_mov_data(self,amplifier):
inreg=amplifier&0xf
tp=amplifier>>4
if inreg>len(self.dataregs):
raise Exception("Illegal command\n")
self.__command_nop()
if (tp&1)==0:
self.dataregs[inreg]=self.memory[self.__getMrange(self.eip)].getDWORD(self.eip,self.eipd)
self.__update_states()
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.__command_nop()
else:
reg=self.memory[self.__getMrange(self.eip)].getDWORD(self.eip,self.eipd)
self.__command_nop()
self.__command_nop()
self.__command_nop()
self.__command_nop()
drctn=self.memory[self.__getMrange(self.eip)].getDWORD(self.eip,self.eipd)
self.dataregs[inreg]=self.memory[self.__getMrange(reg)].getDWORD(reg,drctn)
self.__update_states()
self.__command_nop()
def __command_mov_data_to_reg(self,amplifier):
inreg=amplifier&0xf
tp=amplifier>>4
if inreg>len(self.dataregs) or tp>len(self.dataregs):
raise Exception("Illegal command\n")
self.__command_nop()
regd=self.memory[self.__getMrange(self.eip)].getZBYTE(self.eip,self.eipd)
self.dataregs[inreg]=self.memory[self.__getMrange(self.dataregs[tp])].getDWORD(self.dataregs[tp],regd)
self.__update_states()
self.__command_nop()
def __command_mov_data_from_reg(self,amplifier):
inreg=amplifier&0xf
tp=amplifier>>4
if inreg>len(self.dataregs) or tp>len(self.dataregs):
raise Exception("Illegal command\n")
self.__command_nop()
regd=self.memory[self.__getMrange(self.eip)].getZBYTE(self.eip,self.eipd)
#self.dataregs[inreg]=self.memory[self.__getMrange(self.dataregs[tp])].getDWORD(self.dataregs[tp],regd)
self.memory[self.__getMrange(self.dataregs[inreg])].setDWORD(self.dataregs[inreg],regd,self.dataregs[tp])
self.__update_states()
self.__command_nop()
#Calling system functions
def __command_syscall(self,amplifier):
if amplifier==1:
self.socket.sendall(str(self.eax)+'\n')
elif amplifier==2:
s=delete_not_printable(self.socket.recv(64))
self.memory[self.__getMrange(self.edi)].writeMemory(self.edi,self.edid,s,self.edx.real.value)
elif amplifier==3:
s=self.memory[self.__getMrange(self.edi)].readMemory(self.edi,self.edid,self.edx.real.value)
self.socket.sendall(s+'\n')
elif amplifier==4:
data=""
for i in range(0,self.edx.real.value*2):
data+=chr(randrange(self.ecx.real.value,self.ecx.imaginary.value))
self.memory[2].writeMemory(self.edi,self.edid,data,self.edx.real.value)
elif amplifier==5:
data=int(self.socket.recv(64))
self.ecx=CARM.REG(data,0)
self.__update_states1()
elif amplifier==0x40:
if (self.eax==CARM.REG(ord("f"),ord("l"))) and (self.ebx==CARM.REG(ord("a"),ord("g"))):
self.socket.sendall(secret+'\n')
else:
raise Exception("Illegal command\n")
self.__command_nop()
def __command_test(self,amplifier):
inreg=amplifier&0xf
outreg=amplifier>>4
if inreg>len(self.dataregs) or outreg>len(self.dataregs):
raise Exception("Illegal command\n")
(first,second)=(self.dataregs[inreg],self.dataregs[outreg])
self.ZF=(first==second)
self.__update_states()
self.__command_nop()
def __getcommand(self):
for mrange in self.memory:
if mrange.containsAddr2(self.eip):
byte=mrange.getZBYTE(self.eip,self.eipd)
def processComand(self):
defaultMrange=None
for mrange in self.memory:
if mrange.containsAddr2(self.eip):
defaultMrange=mrange
break
if defaultMrange==None:
raise Exception("EIP not in identifiable range")
commandByte=defaultMrange.getZBYTE(self.eip,self.eipd)
(opcode,amplifier)=(commandByte.real.value,commandByte.imaginary.value)
if opcode in self.commands.keys():
return self.commands[opcode](amplifier)
else:
raise Exception("Illegal command\n")
def run(self):
pwd=None
while pwd!=True:
pwd=self.processComand()
command_prefixes=[]
handlers=[]
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
emulator=CARM(self)
emulator.run()
except Exception,e:
ret ='Error: ' +str(e)
self.request.sendall(ret+'\n')
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == '__main__':
server = ThreadedTCPServer(('0.0.0.0', PORT), ThreadedTCPRequestHandler)
server.allow_reuse_address = True
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2023/Quals/crypto/Wise_sage/server.py | ctfs/CTFZone/2023/Quals/crypto/Wise_sage/server.py | import random as rnd
import logging
import re
import socketserver
from hashlib import blake2b
from Crypto.Cipher import AES
from gmpy2 import isqrt
from py_ecc.fields import optimized_bn128_FQ
from py_ecc.optimized_bn128.optimized_curve import (
Optimized_Point3D,
normalize,
G1,
multiply,
curve_order,
add,
neg,
)
from flag import flag
hello_string = """Hello, adventurer! A wise sage told me that you can predict the future. Let's see if you can predict my private key. Shhhhhhhh! Send it securely
"""
help_string = """
Usage:
ecdh <(x,y)> - send the point to establish an ECDH tunnel
answer <hex> - send the answer to the question "What is my private key?" encrypted in hex from
help - this info
"""
prompt = ">"
def egcd_step(prev_row, current_row):
(s0, t0, r0) = prev_row
(s1, t1, r1) = current_row
q_i = r0 // r1
return (s0 - q_i * s1, t0 - q_i * t1, r0 - q_i * r1)
def find_decomposers(lmbda, modulus):
mod_root = isqrt(modulus)
egcd_trace = [(1, 0, modulus), (0, 1, lmbda)]
while egcd_trace[-2][2] >= mod_root:
egcd_trace.append(egcd_step(egcd_trace[-2], egcd_trace[-1]))
(_, t_l, r_l) = egcd_trace[-3]
(_, t_l_plus_1, r_l_plus_1) = egcd_trace[-2]
(_, t_l_plus_2, r_l_plus_2) = egcd_trace[-1]
(a_1, b_1) = (r_l_plus_1, -t_l_plus_1)
if (r_l**2 + t_l**2) <= (r_l_plus_2**2 + t_l_plus_2**2):
(a_2, b_2) = (r_l, -t_l)
else:
(a_2, b_2) = (r_l_plus_2, -t_l_plus_2)
return (a_1, b_1, a_2, b_2)
lmbda = 4407920970296243842393367215006156084916469457145843978461
beta = 2203960485148121921418603742825762020974279258880205651966
(a_1, b_1, a_2, b_2) = find_decomposers(lmbda, curve_order)
def compute_balanced_representation(scalar, modulus):
c_1 = (b_2 * scalar) // modulus
c_2 = (-b_1 * scalar) // modulus
k_1 = scalar - c_1 * a_1 - c_2 * a_2
k_2 = -c_1 * b_1 - c_2 * b_2
return (k_1, k_2)
def multiply_with_endomorphism(x: int, y: int, scalar: int):
assert scalar >= 0 and scalar < curve_order
point = (optimized_bn128_FQ(x), optimized_bn128_FQ(y), optimized_bn128_FQ.one())
endo_point = (
optimized_bn128_FQ(x) * optimized_bn128_FQ(beta),
optimized_bn128_FQ(y),
optimized_bn128_FQ.one(),
)
(k1, k2) = compute_balanced_representation(scalar, curve_order)
print("K decomposed:", k1, k2)
if k1 < 0:
point = neg(point)
k1 = -k1
if k2 < 0:
endo_point = neg(endo_point)
k2 = -k2
return normalize(add(multiply(point, k1), multiply(endo_point, k2)))
(HOST, PORT) = ("0.0.0.0", 1337)
class CheckHandler(socketserver.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# Generate the private key
private_key = rnd.randint(2, curve_order - 1)
print("Private key:", private_key)
public_key = multiply_with_endomorphism(G1[0].n, G1[1].n, private_key)
self.request.sendall((hello_string + help_string + prompt).encode())
session_key = normalize(G1)
while True:
# self.request is the TCP socket connected to the client
try:
data = self.request.recv(2048).strip().decode()
(command, arguments) = data.split(" ")
if command == "help":
self.request.sendall((help_string + prompt).encode())
elif command == "ecdh":
(p_x, p_y) = map(
int,
re.match(
r"\((\d+),(\d+)\)", "".join(arguments).replace(" ", "")
)
.group()[1:-1]
.split(","),
)
session_key = multiply_with_endomorphism(p_x, p_y, private_key)
print(session_key)
hash_check = blake2b((str(session_key) + "0").encode()).hexdigest()
self.request.sendall(
(
f"Public key: {str(public_key)}, session check: {hash_check}\n"
+ prompt
).encode()
)
elif command == "answer":
fct = bytes.fromhex("".join(arguments))
if len(fct) < 32:
self.request.sendall(("IV + CT too short" + prompt).encode())
continue
key = blake2b((str(session_key) + "1").encode()).digest()[
: AES.key_size[-1]
]
aes = AES.new(key, AES.MODE_CBC, fct[: AES.block_size])
pt = aes.decrypt(fct[AES.block_size :])
answer = int(pt.decode())
if answer == private_key:
self.request.sendall(f"Yay! Here is your flag: {flag}".encode())
return
else:
self.request.sendall("No, wrong answer".encode())
return
except ValueError:
logging.error("Conversion problem or bad data")
self.request.sendall(("Malformed data\n" + prompt).encode())
continue
except ConnectionResetError:
logging.error("Connection reset by client")
return
except UnicodeDecodeError:
logging.error("Client sent weird data")
return
except AttributeError:
logging.error("Malformed command")
self.request.sendall(("Malformed command\n" + prompt).encode())
continue
if __name__ == "__main__":
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(name)-12s %(levelname)-8s %(message)s",
datefmt="%m-%d %H:%M",
filename="server.log",
filemode="w",
)
server = socketserver.TCPServer((HOST, PORT), CheckHandler, bind_and_activate=False)
server.allow_reuse_address = True
server.server_bind()
server.server_activate()
logging.info(f"Started listenning on {HOST}:{PORT}")
server.serve_forever()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2023/Quals/crypto/Wise_sage/flag.py | ctfs/CTFZone/2023/Quals/crypto/Wise_sage/flag.py | flag = "ctfzone{XXXXXXXXXXXXXXXXXXXXX}"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2023/Quals/crypto/Right_Decision/src/main.py | ctfs/CTFZone/2023/Quals/crypto/Right_Decision/src/main.py | import random
import string
import Crypto.Util.number as number
import numpy as np
import json
import socketserver
import galois
from hashlib import md5
PORT = 31339
with open('params.txt') as f:
params = json.load(f)
p = params['galois_p']
k = params['k']
n = params['RSA_n']
gf = galois.GF(p,verify=False,primitive_element=2)
with open('votes.txt') as f:
votes = json.load(f)
with open('flag.txt') as f:
flag = f.read()
def check_secret(s):
#check if secret is real phi for public key n
return pow(2,s,n)==1
def parse_new_vote(data):
all_votes = votes.copy()
all_votes.append(json.loads(data))
#check if we have k true votes
true_votes = sum([v['vote'] for v in all_votes])
if true_votes<k:
return 'bad vote!'
#calculate Shamir's shared secret
matrix = [[ gf(vote['i'])**(k-j-1) for j in range(k)] for vote in all_votes]
values = [vote['value'] for vote in all_votes]
matrix = gf(matrix)
values = gf(values)
r = np.linalg.solve(matrix,values)
for_test = int(r[-1])
# ok, now check that secret is correct
if check_secret(for_test):
return flag
else:
return 'bad vote!'
class CheckHandler(socketserver.BaseRequestHandler):
def check_pow(self):
prefix = ''.join(random.choices(string.ascii_letters,k=10))
pow_size = 7 # 3.5 byte
hash_bytes = ''.join(random.choices('abcdef1234567890',k=pow_size))
self.request.sendall(("Welcome! Please provide proof of work. \nPrefix: "+prefix+"\nTarget hash starts with:"+hash_bytes+'\nEnter: ').encode('utf-8'))
response = self.request.recv(100).decode('utf-8').strip()
if md5((prefix+response).encode('utf-8')).hexdigest().startswith(hash_bytes):
self.request.sendall(b'Proof of work confirmed. Go on!\n\n')
return True
else:
self.request.sendall(b'Proof of work is bad. Bye!')
return False
def handle(self):
if not self.check_pow():
return
self.request.sendall(b'Present your vote: \n')
data = self.request.recv(10000).strip()
try:
resp = parse_new_vote(data)
except:
resp = 'bad vote!'
self.request.sendall(resp.encode('utf-8'))
if __name__ == '__main__':
server = socketserver.TCPServer(('0.0.0.0',PORT),CheckHandler)
server.serve_forever()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2023/Quals/crypto/Right_Decision/src/generate_secrets.py | ctfs/CTFZone/2023/Quals/crypto/Right_Decision/src/generate_secrets.py | import random
import Crypto.Util.number as number
import numpy as np
import json
import sys
import galois
p = number.getPrime(2050)
f = galois.GF(p,verify=False,primitive_element=2)
k=8
num = 12
secret = sys.argv[1]
a = [random.randint(0,f.order) for _ in range(k-1)]
a.append(secret)
a = f(a)
def poly(a,x):
return np.sum([ a[i]*(x**(len(a)-i-1)) for i in range(len(a))])
i_s = [random.randint(0,f.order) for i in range(1,num+1,1)]
shared_secrets = [(i,poly(a,f(i))) for i in i_s]
print ('\n'.join( [ '{"i":%d,"value":%d}' %(s[0],int(s[1])) for s in shared_secrets ]))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2023/Quals/crypto/Messenger_zone/server/handler.py | ctfs/CTFZone/2023/Quals/crypto/Messenger_zone/server/handler.py | import tornado
from models import RegistrationHandler, SendMessageHandler, GetMessageHandler, KeyExchangeHandler, GetPublicValuesHandler, GeKeysHandler
def make_app():
return tornado.web.Application([
(r"/register", RegistrationHandler),
(r"/send", SendMessageHandler),
(r"/get", GetMessageHandler),
(r"/keys", KeyExchangeHandler),
(r"/pubs", GetPublicValuesHandler),
(r"/initkeys", GeKeysHandler)
])
if __name__ == "__main__":
app = make_app()
port = 7777
app.listen(port)
print("Server running on http://localhost:{}".format(port))
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/CTFZone/2023/Quals/crypto/Messenger_zone/server/db.py | ctfs/CTFZone/2023/Quals/crypto/Messenger_zone/server/db.py | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database
import os
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
Base = declarative_base()
engine = create_engine("sqlite:///" + os.path.join(BASE_DIR, 'messages.db'))
if not database_exists(engine.url):
print("Database does not exist")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2023/Quals/crypto/Messenger_zone/server/models.py | ctfs/CTFZone/2023/Quals/crypto/Messenger_zone/server/models.py | import tornado.escape
import tornado.ioloop
import tornado.web
from sqlalchemy import Column, String, Integer
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database
from db import Base, session
def x_y_to_string(t):
return str(t[0]) + ';' + str(t[1])
def string_to_x_y(string):
data = string.split(';')
return (int(data[0]), int(data[1]))
Base = declarative_base()
engine = create_engine("sqlite:///./messages.db")
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
IK = Column(String)
PK = Column(String)
sig = Column(String)
OPK = Column(String)
def __init__(self, name, IK, PK, sig, OPK=None):
self.name = name
self.IK = IK
self.PK = PK
self.sig = sig
self.OPK = OPK
class Message(Base):
__tablename__ = 'messages'
id = Column(Integer, primary_key=True)
from_m = Column(String)
to_m = Column(String)
header = Column(String)
message = Column(String)
def __init__(self, from_m, to_m, header, message):
self.from_m = from_m
self.to_m = to_m
self.header = header
self.message = message
class Keys(Base):
__tablename__ = 'keys'
id = Column(Integer, primary_key=True)
name = Column(String)
IK = Column(String)
EK = Column(String)
TO = Column(String)
MSG = Column(String)
def __init__(self, name, IK, EK, TO, MSG):
self.name = name
self.IK = IK
self.EK = EK
self.TO = TO
self.MSG = MSG
class RegistrationHandler(tornado.web.RequestHandler):
def post(self):
data = tornado.escape.json_decode(self.request.body)
# delete old data
session.query(User).filter(User.name == data['name']).delete()
user = User(data['name'], data['IK'], data['PK'], data['sig'], data.get('OPK'))
session.add(user)
session.commit()
self.set_status(201)
self.write({'message':'User registration'})
class SendMessageHandler(tornado.web.RequestHandler):
def post(self):
data = tornado.escape.json_decode(self.request.body)
message = Message(data['from_m'], data['to_m'], data['header'], data['message'])
session.add(message)
session.commit()
self.set_status(201)
self.write({'message':'Save msg on server'})
class GetMessageHandler(tornado.web.RequestHandler):
def get(self):
to_m=self.get_argument("to_m", None, True)
msgs = session.query(Message).filter(Message.to_m == to_m).order_by(Message.id.asc()).all()
if msgs is None:
msgs = []
data = []
for msg in msgs:
data.append({
'id': msg.id,
'from_m': msg.from_m,
'to_m': msg.to_m,
'header': msg.header,
'message': msg.message
})
# delete recieved msgs
session.query(Message).filter(Message.to_m == to_m).delete()
session.commit()
self.set_status(200)
self.write({'messages': data})
class GetPublicValuesHandler(tornado.web.RequestHandler):
def get(self):
name = self.get_argument("name", None, True)
usr = session.query(User).filter(User.name == name).first()
if usr is None:
self.set_status(404)
self.write({'messages': 'No such user'})
else:
self.set_status(200)
self.write({'IK':usr.IK, 'PK': usr.PK, 'sig':usr.sig, 'OPK':usr.OPK})
class KeyExchangeHandler(tornado.web.RequestHandler):
def post(self):
data = tornado.escape.json_decode(self.request.body)
keys = session.query(Keys).filter(Keys.TO == data['to']).filter(Keys.name == data['name']).delete()
keys = Keys(data['name'], x_y_to_string(data['ik']), x_y_to_string(data['ek']), data['to'], data['msg'])
session.add(keys)
session.commit()
self.set_status(201)
self.write({'message':'Init chat'})
class GeKeysHandler(tornado.web.RequestHandler):
def get(self):
name = self.get_argument("name", None, True)
keys = session.query(Keys).filter(Keys.TO == name).all()
if keys is None:
keys = []
data = []
for key in keys:
data.append([key.name, string_to_x_y(key.IK), string_to_x_y(key.EK), key.TO, key.MSG])
self.set_status(200)
self.write({'keys':data})
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTFZone/2023/Quals/crypto/Messenger_zone/client/client.py | ctfs/CTFZone/2023/Quals/crypto/Messenger_zone/client/client.py | import hmac
from pygost import gost34112012512
from pygost.gost3410 import sign, verify
from pygost.gost34112012 import GOST34112012
from pygost.gost3412 import GOST3412Kuznechik
from pygost.mgm import MGM
from pygost.mgm import nonce_prepare
from pygost import gost3410
from pygost.gost3413 import unpad2, pad2
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from binascii import unhexlify
import time
import random
import requests
server_url = 'http://localhost:7777'
keys_api = '/keys'
get_api = '/get'
send_api = '/send'
register_api = '/register'
pubs_api = '/pubs'
getkeys_api = '/initkeys'
size = 64
block_size = 16
app_name = b'MessengerZone'
start_mes = b'MessengerZone_start'
MAX_SKIP = 10
nonce = nonce_prepare(b'\x00'*block_size)
start_time = int(time.time())
random.seed(start_time)
def long_to_bytes(val, endianness='big'):
width = val.bit_length()
width += 8 - ((width % 8) or 8)
fmt = '%%0%dx' % (width // 4)
s = unhexlify(fmt % val)
if endianness == 'little':
s = s[::-1]
return s
def point_to_bytes(point):
return long_to_bytes(point[0]) + long_to_bytes(point[0])
def generate_bytes(n=size):
return random.randbytes(n)
CURVE = gost3410.CURVES['id-tc26-gost-3410-2012-512-paramSetA']
def GENERATE_DH():
prv_key = gost3410.prv_unmarshal(generate_bytes(64))
pub_key = gost3410.public_key(CURVE, prv_key)
return (prv_key, pub_key)
def DH(dh_pair, dh_pub):
return CURVE.exp(dh_pair[0], *dh_pub)
def KDF_RK(rk, dh_out):
data = point_to_bytes(dh_out)
key = hmac.new(key=rk, msg=data, digestmod=GOST34112012).digest()
return (key, key)
def KDF_CK(ck):
key = hmac.new(key=ck, msg=b'\x00'*16, digestmod=GOST34112012).digest()
return (key, key)
def ENCRYPT(mk, plaintext, associated_data):
mgm = MGM(GOST3412Kuznechik(mk).encrypt, block_size)
return mgm.seal(nonce, plaintext, associated_data)
def DECRYPT(mk, ciphertext, associated_data):
mgm = MGM(GOST3412Kuznechik(mk).encrypt, block_size)
return mgm.seal(nonce, ciphertext, associated_data)
def HEADER(dh_pair, pn, n):
a = Header()
a.dh = dh_pair[1]
a.pn = pn
a.n = n
return a
def header_to_string(header):
print([header.dh, header.pn, header.n])
return ';'.join([str(header.dh[0]), str(header.dh[1]), str(header.pn), str(header.n)])
def string_to_header(string):
l = string.split(';')
dh_pub = (int(l[0]), int(l[1]))
dh = [0, dh_pub]
return HEADER(dh, int(l[2]), int(l[3]))
def CONCAT(ad, header):
return ad + header_to_string(header).encode('utf-8')
class Header(object):
pass
class Ratchet:
def __init__(self, DHs, DHr, RK, CKs):
self.DHs = DHs
self.DHr = DHr
self.RK = RK
self.CKs = CKs
self.CKr = None
self.Ns = 0
self.Nr = 0
self.PN = 0
self.MKSKIPPED = {}
def RatchetEncrypt(self, plaintext, AD):
self.CKs, mk = KDF_CK(self.CKs)
header = HEADER(self.DHs, self.PN, self.Ns)
self.Ns += 1
return header, ENCRYPT(mk, plaintext, CONCAT(AD, header))
def RatchetDecrypt(self, header, ciphertext, AD):
plaintext = self._TrySkippedMessageKeys(header, ciphertext, AD)
if plaintext != None:
return plaintext
if header.dh != self.DHr:
self._SkipMessageKeys(header.pn)
self._DHRatchet(header)
self._SkipMessageKeys(header.n)
self.CKr, mk = KDF_CK(self.CKr)
self.Nr += 1
return DECRYPT(mk, ciphertext, CONCAT(AD, header))
def _DHRatchet(self, header):
self.PN = self.Ns
self.Ns = 0
self.Nr = 0
self.DHr = header.dh
self.RK, self.CKr = KDF_RK(self.RK, DH(self.DHs, self.DHr))
self.DHs = GENERATE_DH()
self.RK, self.CKs = KDF_RK(self.RK, DH(self.DHs, self.DHr))
def _TrySkippedMessageKeys(self, header, ciphertext, AD):
if (header.dh, header.n) in self.MKSKIPPED:
mk = self.MKSKIPPED[header.dh, header.n]
del self.MKSKIPPED[header.dh, header.n]
return DECRYPT(mk, ciphertext, CONCAT(AD, header))
else:
return None
def _SkipMessageKeys(self, until):
if self.Nr + MAX_SKIP < until:
raise Exception()
if self.CKr != None:
while self.Nr < until:
self.CKr, mk = KDF_CK(self.CKr)
self.MKSKIPPED[self.DHr, self.Nr] = mk
self.Nr += 1
class Server:
def __init__(self):
self.open_vals = dict()
self.messages = dict()
self.first_messages = dict()
def register(self, name, IK, PK, sig, OPK=[]):
print('[*] User registration')
print('name:',name)
print('IK:',IK.hex())
print('PK:',PK.hex())
print('sig:',sig)
data = {'name':name, 'IK':IK.hex(), 'PK': PK.hex(), 'sig':sig, 'OPK':str(OPK)}
r = requests.post(server_url+register_api, json=data)
return r.json()['message'] == 'User registration'
def get_pubs(self, name):
r = requests.get(server_url + pubs_api, params={'name':name})
print(r.json())
return r.json()
def start_messages(self, m_from, IK_A, EK, m_to, mes):
print('[*] Init chat')
print('name:',m_from)
print('IK:',IK_A)
print('EK:',EK)
print('To:',m_to)
print('Msg:',mes)
data = {'name':m_from, 'ik':IK_A, 'ek': EK, 'to':m_to, 'msg':mes.hex()}
r = requests.post(server_url+keys_api, json=data)
return r.json()['message'] == 'Init chat'
def get_start_messages(self, m_to):
print('[*] Get init chat msgs', m_to)
r = requests.get(server_url + getkeys_api, params={'name':m_to})
print(r.json())
return r.json()['keys']
def store_message(self, from_m, to_m, header, message):
print('Save msg on server')
print('To:',to_m)
print('From:',from_m)
print('header:',header)
print('message:',message)
data = {'from_m':from_m, 'to_m':to_m, 'header': header_to_string(header), 'message':message.hex()}
print(data)
r = requests.post(server_url+send_api, json=data)
print(r.json())
return r.json()['message'] == 'Save msg on server'
def get_messages(self, to_m):
print('Recive msgs', to_m)
r = requests.get(server_url + get_api, params={'to_m':to_m})
return r.json()['messages']
class Client:
def __init__(self, name, server):
self.name = name
self.server = server
self.IK_prv = gost3410.prv_unmarshal(generate_bytes(64))
self.IK = gost3410.public_key(CURVE, self.IK_prv)
print(name, 'IK', self.IK)
self.PK_prv = gost3410.prv_unmarshal(generate_bytes(64))
self.PK = gost3410.public_key(CURVE, self.PK_prv)
print(name, 'PK', self.PK)
self.RATCHET_dict = dict()
dgst = gost34112012512.new(gost3410.pub_marshal(self.PK)).digest()[::-1]
sig_PK = sign(CURVE, self.IK_prv, dgst)
# register
res = server.register(self.name, gost3410.pub_marshal(self.IK), gost3410.pub_marshal(self.PK), sig_PK.hex())
print('Registered ',self.name,res)
def start_x3dh(self, m_to):
# x3dh as Alice
keys = self.server.get_pubs(m_to)
IK_B = gost3410.pub_unmarshal(bytes.fromhex(keys['IK']))
print(m_to, 'IK', IK_B)
PK_B = gost3410.pub_unmarshal(bytes.fromhex(keys['PK']))
print(m_to, 'PK', PK_B)
sig = bytes.fromhex(keys['sig'])
OPK_B = keys['OPK']
dgst = gost34112012512.new(gost3410.pub_marshal(PK_B)).digest()[::-1]
if not verify(CURVE, IK_B, dgst, sig):
print('Signature not valid')
return False
EK = gost3410.prv_unmarshal(generate_bytes(64))
self.EK = EK
EK_pub = gost3410.public_key(CURVE, EK)
self.EK_pub = EK_pub
DH1 = CURVE.exp(self.IK_prv, *PK_B)
DH2 = CURVE.exp(EK, *IK_B)
DH3 = CURVE.exp(EK, *PK_B)
data_bytes = b'\x00'*32 + point_to_bytes(DH1) + point_to_bytes(DH2) + point_to_bytes(DH3)
SK = HKDF(algorithm=hashes.SHA256(), length=size, salt=b'\x00'*size, info=app_name,).derive(data_bytes)
print(self.name,'generated SK =', SK.hex())
AD = gost3410.pub_marshal(self.IK) + gost3410.pub_marshal(IK_B)
DHs_A=GENERATE_DH()
RK_A, CKs_A = KDF_RK(SK, DH(DHs_A, PK_B))
self.RATCHET_dict[m_to] = Ratchet(DHs=DHs_A, DHr=PK_B, RK=RK_A, CKs=CKs_A)
mgm = MGM(GOST3412Kuznechik(SK).encrypt, block_size)
ciphertext = mgm.seal(nonce, start_mes, AD)
self.server.start_messages(self.name, self.IK, self.EK_pub, m_to, ciphertext)
return True
def receive_x3dh(self):
for data in self.server.get_start_messages(self.name):
# x3dh as bob
m_from = data[0]
IK_A = data[1]
EK = data[2]
m_to = data[3]
mes = bytes.fromhex(data[4])
if m_to != self.name:
print('Message not for me')
else:
DH1 = CURVE.exp(self.PK_prv, *IK_A)
DH2 = CURVE.exp(self.IK_prv, *EK)
DH3 = CURVE.exp(self.PK_prv, *EK)
data_bytes = b'\x00'*32 + point_to_bytes(DH1) + point_to_bytes(DH2) + point_to_bytes(DH3)
SK = HKDF(algorithm=hashes.SHA256(), length=size, salt=b'\x00'*size, info=app_name,).derive(data_bytes)
print(self.name,'generated SK =', SK.hex())
AD = gost3410.pub_marshal(IK_A) + gost3410.pub_marshal(self.IK)
mgm = MGM(GOST3412Kuznechik(SK).encrypt, block_size)
dec_mes = mgm.open(nonce, mes, AD)
if dec_mes != start_mes:
print('Start message invalid')
else:
self.RATCHET_dict[m_from] = Ratchet(DHs=(self.PK_prv, self.PK), DHr=None, RK=SK, CKs=None)
def send(self, m_to, msg, send=True):
if m_to not in self.RATCHET_dict.keys():
self.start_x3dh(m_to)
msg = pad2(msg, block_size)
AD = (self.name + m_to).encode('utf-8')
head, cipher = self.RATCHET_dict[m_to].RatchetEncrypt(msg, AD)
if send:
print('SEND', header_to_string(head).encode('utf-8'), cipher, AD)
self.server.store_message(self.name, m_to, head, cipher)
return True
def pull(self):
msg_l = list()
data_l = self.server.get_messages(self.name)
for data in data_l:
from_m = data['from_m']
head = string_to_header(data['header'])
cipher = bytes.fromhex(data['message'])
AD = (from_m + self.name).encode('utf-8')
print(from_m, data['header'], cipher, AD)
if from_m not in self.RATCHET_dict.keys():
self.receive_x3dh()
print('PULL', header_to_string(head).encode('utf-8'), cipher, AD)
msg = self.RATCHET_dict[from_m].RatchetDecrypt(head, cipher, AD)
msg = unpad2(msg[:-2*block_size], block_size)
msg_l.append((from_m, msg))
return msg_l
def start_main():
server = Server()
client_dict = dict()
current_client = 'A'
print('Created client', current_client)
client_dict[current_client] = Client(current_client, server)
current_client = 'B'
print('Created client', current_client)
client_dict[current_client] = Client(current_client, server)
while True:
print('Client:',current_client)
print('1 - Change client')
print('2 - Send msg')
print('3 - Pull msgs')
print('q - quit')
choose = input('> ')
if choose == '1':
if current_client == 'A':
current_client = 'B'
else:
current_client = 'A'
if current_client not in client_dict.keys():
client_dict[current_client] = Client(current_client, server)
print('Created client', current_client)
elif choose == '2':
if current_client == 'A':
to_m = 'B'
else:
to_m = 'A'
msg = input('Msg: ')
r = client_dict[current_client].send(to_m, msg.encode('utf-8'))
if r:
print('Sended')
else:
print('Error')
elif choose == '3':
msgs = client_dict[current_client].pull()
print('Msgs:')
for msg in msgs:
print(msg[0],':',msg[1].decode('utf-8'))
elif choose == 'q':
exit(0)
else:
print('Invalid choose')
start_main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/darkCON/2021/crypto/Rookie_Choice_4_you/chall.py | ctfs/darkCON/2021/crypto/Rookie_Choice_4_you/chall.py | #!/usr/bin/env python3
from Crypto.Cipher import ARC4 # pip3 install pycryptodome
import os
KEY = os.urandom(16)
FLAG = "******************* REDUCTED *******************"
menu = """
+--------- MENU ---------+
| |
| [1] Show FLAG |
| [2] Encrypt Something |
| [3] Exit |
| |
+------------------------+
"""
print(menu)
while 1:
choice = input("\n[?] Enter your choice: ")
if choice == '1':
cipher = ARC4.new(KEY)
enc = cipher.encrypt(FLAG.encode()).hex()
print(f"\n[+] Encrypted FLAG: {enc}")
elif choice == '2':
plaintext = input("\n[*] Enter Plaintext: ")
cipher = ARC4.new(KEY)
ciphertext = cipher.encrypt(plaintext.encode()).hex()
print(f"[+] Your Ciphertext: {ciphertext}")
else:
print("\n:( See ya later!")
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/darkCON/2021/crypto/TonyAndJames/src.py | ctfs/darkCON/2021/crypto/TonyAndJames/src.py | #!/usr/bin/env python3
import random
def get_seed(l):
seed = 0
rand = random.getrandbits(l)
raw = list()
while rand > 0:
rand = rand >> 1
seed += rand
raw.append(rand)
if len(raw) == l:
return raw, seed
else:
return get_seed(l)
def encrypt(m):
l = len(m)
raw, seed = get_seed(l)
random.seed(seed)
with open('encrypted.txt', 'w') as f:
for i in range(l):
r = random.randint(1, 2**512)
if i == 0:
print("r0 =",r)
encoded = hex(r ^ m[i] ^ raw[i])[2:]
f.write(f"F{i}: {encoded}\n")
def main():
m = open('flag.txt').read()
encrypt(m.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/darkCON/2021/crypto/DisguisedWordlets/func_.py | ctfs/darkCON/2021/crypto/DisguisedWordlets/func_.py | def encrypt(text, key):
return ''.join([ chr((( key[0]*(ord(t) - ord('A')) + key[1] ) % 26) + ord('A')) for t in text.upper().replace(' ', '') ])
def compress(uncompressed):
_size = 256
dictionary = dict((chr(i), chr(i)) for i in range(_size))
w = ""
result = []
for c in uncompressed:
wc = w + c
if wc in dictionary:
w = wc
else:
result.append(dictionary[w])
# Add wc to the dictionary.
dictionary[wc] = _size
_size += 1
w = c
if w:
result.append(dictionary[w])
return result
text = ''
key = [3, 19]
enc_text = encrypt(text, key)
compressed = compress(enc_text)
print(compressed) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DeadSec/2023/crypto/LCG/chall.py | ctfs/DeadSec/2023/crypto/LCG/chall.py | import random
from Crypto.Util.number import *
import gmpy2
class LCG:
def __init__(self, a, c, m, seed):
self.seed = seed
self.multiplier = a
self.increment = c
self.modulus = m
def next(self):
self.seed = (self.multiplier*self.seed + self.increment) % self.modulus
return self.seed
def __str__(self):
return ",".join(map(str, [self.seed, self.multiplier, self.increment, self.modulus]))
def gen_primes(PRIME_SIZE):
lcg = LCG(random.getrandbits(PRIME_SIZE//4), random.getrandbits(PRIME_SIZE//4), random.getrandbits(PRIME_SIZE//4), random.getrandbits(PRIME_SIZE//4))
r1 = random.getrandbits(PRIME_SIZE//4)
p = r1 << ((PRIME_SIZE*3)//4)
for _ in range(3):
p = p | (lcg.next() << (PRIME_SIZE*(2 - _))//4)
r2 = random.getrandbits(PRIME_SIZE//4)
q = r2 << ((PRIME_SIZE*3)//4)
for _ in range(3):
q = q | (lcg.next() << (PRIME_SIZE*(2 - _))//4)
return lcg, p, q
while True:
lcg, p, q = gen_primes(512)
if gmpy2.is_prime(p) and gmpy2.is_prime(q) and gmpy2.gcd(lcg.multiplier, lcg.modulus) == 1:
break
#print(lcg)
n = p * q
e = 65537
flag = b''
c = pow(bytes_to_long(flag), e, n)
print(f"n: {n}")
print(f"ct: {c}")
print("Hint:")
print([lcg.next() for _ in range(6)]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DeadSec/2025/crypto/imrul_kAES/server.py | ctfs/DeadSec/2025/crypto/imrul_kAES/server.py | #!/usr/local/bin/python
from Crypto.Util.number import bytes_to_long, long_to_bytes, getPrime
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
print('Yo welcome to my sign as a service...')
p, q = getPrime(512), getPrime(512)
e = 12389231641983877009741841713701317189420787527171545487350619433744301520682298136425919859970313849150196317044388637723151690904279767516595936892361663
n = p * q
d = pow(e, -1, (p - 1) * (q - 1))
k = get_random_bytes(16)
cipher = AES.new(k, AES.MODE_ECB)
flag = open('flag.txt', 'rb').read()
assert len(flag) <= 50
ct = pow(bytes_to_long(flag), e, n)
print(ct)
while 1:
try:
i = int(input("Enter message to sign: "))
assert(0 < i < n)
print(cipher.encrypt(pad(long_to_bytes(pow(i, d, n) & ((1<<512) - 1)), 16)).hex())
except:
print("bad input, exiting") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DeadSec/2025/crypto/infant_RSA/infant_rsa.py | ctfs/DeadSec/2025/crypto/infant_RSA/infant_rsa.py | #!/usr/bin/env python3
from Crypto.Util.number import getPrime, bytes_to_long
from secret import flag
p, q = getPrime(512), getPrime(512)
n = p * q
e = 65537
phi = (p-1) * (q-1)
hint = phi & ((1 << 500)-1)
m = bytes_to_long(flag)
c = pow(m, e, n)
print(f'{n=}')
print(f'{c=}')
print(f'{hint=}')
#n=144984891276196734965453594256209014778963203195049670355310962211566848427398797530783430323749867255090629853380209396636638745366963860490911853783867871911069083374020499249275237733775351499948258100804272648855792462742236340233585752087494417128391287812954224836118997290379527266500377253541233541409
#c=120266872496180344790010286239079096230140095285248849852750641721628852518691698502144313546787272303406150072162647947041382841125823152331376276591975923978272581846998438986804573581487790011219372437422499974314459242841101560412534631063203123729213333507900106440128936135803619578547409588712629485231
#hint=867001369103284883200353678854849752814597815663813166812753132472401652940053476516493313874282097709359168310718974981469532463276979975446490353988
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DeadSec/2025/crypto/bullmad/bullmad.py | ctfs/DeadSec/2025/crypto/bullmad/bullmad.py | import os, time, signal
from hashlib import sha256
from ecdsa import SigningKey, SECP256k1
from ecdsa.util import sigencode_string
from random import SystemRandom
G = SECP256k1.generator
n = SECP256k1.order
BITS = 64
def sign_with_nonce(sk, message, nonce):
e = int.from_bytes(sha256(message).digest(), 'big')
R = nonce * G
r = R.x() % n
if r == 0: raise ValueError("Invalid nonce: r == 0")
k_inv = pow(nonce, -1, n)
s = (k_inv * (e + r * sk)) % n
if s == 0: raise ValueError("Invalid signature: s == 0")
return (r, s, R.y() % 2)
def banner():
print("""
Welcome to BULLMAD -- The premium BPN solution!
Here you can redeem your 1, 3, 6 or 12 month codes and add time to your BPN account.
The codes are signatures, and look like these DEMO messages:
""".strip())
signal.alarm(60)
if __name__ == "__main__":
banner()
rnd = SystemRandom()
nonce = rnd.randint(1, n - 1)
demo_accounts = sorted((rnd.getrandbits(BITS), length) for length in [30, 180])
sk = int.from_bytes(os.urandom(32), "big")
pk = SigningKey.from_secret_exponent(sk, curve=SECP256k1, hashfunc=sha256).get_verifying_key()
print(f"My pubkey is {pk}")
for i,(account_id,length) in enumerate(demo_accounts):
message = f"DEMO Account expires at {time.time()+86400*length:.0f}"
r, s, v = sign_with_nonce(sk, message.encode(), (nonce + account_id)%(n - 1))
print(f"m{i+1} = '{message}'")
print(f"r{i+1} = {hex(r)}")
print(f"s{i+1} = {hex(s)}")
print(f"v{i+1} = {hex(v)}")
message = f"Account expires at {time.time()+86400*360:.0f}"
print(f"Now give me a signature for a 1 year non-demo account: '{message}'")
r = int(input("r = "))
s = int(input("s = "))
try:
if pk.verify(sigencode_string(r,s,n), message.encode(), hashfunc=sha256):
print(open("flag.txt").read())
except:
print("Bad signature, are you sure you entered it correctly?") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OverTheWireAdventBonanza/2021/crypto/Santas_Secrets/server.py | ctfs/OverTheWireAdventBonanza/2021/crypto/Santas_Secrets/server.py | #!/usr/bin/env python3
import asyncio
from Cryptodome.Cipher import AES # pip3 install pycryptodomex
import os
from REDACTED import FLAG
assert(type(FLAG) is str)
assert(len(FLAG) == 32)
HOST = "0.0.0.0"
PORT = 1209
NUM_SLOTS = 8
SLOT_SIZE = 16
MAX_CMDS = 1000
TIMEOUT = 60
HELPMSG = f"""
Welcome to Santa's Super-Secure Secret Storage Service
There are {NUM_SLOTS} write-only keyslots.
There are {NUM_SLOTS} read/write dataslots.
You can encrypt the data in a chosen dataslot,
with a key from a chosen keyslot.
Once a keyslot is written, it cannot be read back.
This allows the elves to securely process encrypted data,
without being able to access the keys.
For example, to encrypt the string "topsecretmessage"
with key deadbeefdeadbeefdeadbeefdeadbeef:
write_key 3 deadbeefdeadbeefdeadbeefdeadbeef hex
write_data 7 topsecretmessage ascii
encrypt 3 2 7
read_data 2
AVAILABLE COMMANDS:
"""
class SecurityEngine():
def __init__(self):
self.commands = {
"help": (self.cmd_help, []),
"encrypt": (self.cmd_encrypt, ["keyslot", "dest", "src"]),
"read_data": (self.cmd_read_data, ["dataslot"]),
"write_data": (self.cmd_write_data, ["dataslot", "data", "encoding"]),
"write_key": (self.cmd_write_key, ["keyslot", "data", "encoding"]),
"exit": (self.cmd_exit, [])
}
self.running = True
self.counter = 0
self.keyslots = bytearray(SLOT_SIZE * NUM_SLOTS)
self.dataslots = bytearray(SLOT_SIZE * NUM_SLOTS)
def _parse_slot_idx(self, i):
i = int(i)
if i < 0 or i >= NUM_SLOTS:
raise Exception("Slot index out of range")
return i
def _parse_data_string(self, data, encoding):
if encoding == "hex":
if len(data) != SLOT_SIZE * 2:
raise Exception("Invalid data length")
return bytes.fromhex(data)
elif encoding == "ascii":
if len(data) != SLOT_SIZE:
raise Exception("Invalid data length")
return data.encode()
raise Exception("Invalid encoding")
def run_cmd(self, cmd):
self.counter += 1
if self.counter > MAX_CMDS:
self.running = False
return "ERROR: MAX_CMDS exceeded"
cmd = cmd.strip()
if not cmd: return ""
op, *args = cmd.split()
if op not in self.commands:
return "ERROR: command not found"
cmdfn, cmdargs = self.commands[op]
if len(args) != len(cmdargs):
return "ERROR: wrong number of arguments"
return cmdfn(*args)
def cmd_help(self):
"""print this message"""
result = HELPMSG
for cmdname, (cmdfn, cmdargs) in self.commands.items():
result += f"{cmdname + ' ' + ' '.join(cmdargs): <34} {cmdfn.__doc__}\n"
return result
def cmd_encrypt(self, keyslot, dest, src):
"""encrypt src dataslot with chosen keyslot, write the result to dest dataslot"""
try: keyslot = self._parse_slot_idx(keyslot)
except: return "ERROR: Invalid keyslot index"
try: dest = self._parse_slot_idx(dest)
except: return "ERROR: Invalid dest index"
try: src = self._parse_slot_idx(src)
except: return "ERROR: Invalid src index"
plaintext = self.dataslots[SLOT_SIZE*src:SLOT_SIZE*(src+1)]
key = self.keyslots[SLOT_SIZE*keyslot:SLOT_SIZE*(keyslot+1)]
ciphertext = AES.new(key=key, mode=AES.MODE_ECB).encrypt(plaintext)
self.dataslots[SLOT_SIZE*dest:SLOT_SIZE*(dest+1)] = ciphertext
return f"dataslot[{dest}] <= AES(key=keyslot[{keyslot}], data=dataslot[{src}])"
def cmd_read_data(self, slot_idx):
"""read a chosen dataslot"""
try: slot_idx = self._parse_slot_idx(slot_idx)
except: return "ERROR: Invalid index"
return self.dataslots[SLOT_SIZE*slot_idx:SLOT_SIZE*(slot_idx+1)].hex()
def cmd_write_data(self, slot_idx, data, encoding):
"""write data to a chosen dataslot"""
try: slot_idx = self._parse_slot_idx(slot_idx)
except: return "ERROR: Invalid index"
try: data = self._parse_data_string(data, encoding)
except: return "ERROR: Invalid data length or encoding"
self.dataslots[SLOT_SIZE*slot_idx:SLOT_SIZE*slot_idx+len(data)] = data
return f"dataslot[{slot_idx}] <= {data.hex()}"
def cmd_write_key(self, slot_idx, data, encoding):
"""write data to a chosen keyslot"""
try: slot_idx = self._parse_slot_idx(slot_idx)
except: return "ERROR: Invalid index"
try: data = self._parse_data_string(data, encoding)
except: return "ERROR: Invalid data length or encoding"
self.keyslots[SLOT_SIZE*slot_idx:SLOT_SIZE*slot_idx+len(data)] = data
return f"keyslot[{slot_idx}] <= {data.hex()}"
def cmd_exit(self):
"""exit the session"""
self.running = False
return "bye"
async def handle_client(reader, writer):
se = SecurityEngine()
# provision keyslot 5 with a secure random key, and use it to encrypt the flag
# since keyslots are write-only, the flag cannot be recovered!
se.run_cmd(f"write_key 5 {os.urandom(SLOT_SIZE).hex()} hex")
se.run_cmd(f"write_data 0 {FLAG[:16]} ascii")
se.run_cmd(f"write_data 1 {FLAG[16:]} ascii")
se.run_cmd(f"encrypt 5 0 0")
se.run_cmd(f"encrypt 5 1 1")
while se.running:
command = await reader.readline()
try: command = command.decode()
except: continue
result = se.run_cmd(command)
writer.write(result.encode() + b"\n")
await writer.drain()
async def handle_client_safely(reader, writer):
peer = writer.get_extra_info("peername")
print("[+] New connection from", peer)
try:
await asyncio.wait_for(handle_client(reader, writer), TIMEOUT)
writer.close()
print("[+] Gracefully closed connection from", peer)
except ConnectionResetError:
print("[*] Connection reset by", peer)
except asyncio.exceptions.TimeoutError:
print("[*] Connection timed out", peer)
writer.close()
async def main():
server = await asyncio.start_server(handle_client_safely, HOST, PORT)
print("[+] Server started")
async with server:
await server.serve_forever()
asyncio.run(main())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2021/pwn/CBC-Jail/jail.py | ctfs/niteCTF/2021/pwn/CBC-Jail/jail.py | #!/usr/bin/python3 -u
import os, base64, sys
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
KEY=os.urandom(16)
IV=os.urandom(16)
def encrypt(msg):
msg = pad(msg,16)
cipher = AES.new(KEY,AES.MODE_CBC,IV)
encrypted = cipher.encrypt(msg)
encrypted = encrypted.hex()
msg = IV.hex() + encrypted
return msg
def decrypt(msg,iv):
if len(msg) > 16:
print("Message must be <= 16")
cipher = AES.new(KEY,AES.MODE_CBC,iv)
decrypted = unpad(cipher.decrypt(msg),16).decode()
return decrypted
def weirdify(inp):
iv = bytes.fromhex(inp[:32])
msg = bytes.fromhex(inp[32:])
command = decrypt(msg,iv)
return command
banned = ['_', 'import','.','flag']
def crack():
REDACTED
print('Welcome to Prison.')
print('A mad cryptographer thought it would be cool to mess your shell up.')
print('Lets see if you can "crack()" your way out of here')
print("As a gift we'll give you a sample encryption")
print(encrypt(b'trapped_forever'))
while True:
try:
inp = input(">>")
inp = weirdify(inp)
for w in banned:
if w in inp:
print("GOTTEM!!")
sys.exit(0)
exec(inp)
except KeyboardInterrupt:
print('\n')
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/niteCTF/2021/pwn/Auto-Pwn/auto-pwn.py | ctfs/niteCTF/2021/pwn/Auto-Pwn/auto-pwn.py | #!/usr/bin/python3 -u
import os
import sys
import subprocess
import uuid
import random
def main():
number = random.randint(10,100)
dir = '/tmp/' + str(uuid.uuid4())
os.mkdir(dir)
with open('./auto-pwn.c', 'r') as auto_pwn_tmpl_file:
auto_pwn_c_code = auto_pwn_tmpl_file.read()
auto_pwn_c_code = auto_pwn_c_code.replace('$1', str(number))
auto_pwn_tmpl_file.close()
os.chdir(dir)
with open('./auto-pwn.c', 'w') as auto_pwn_file:
auto_pwn_file.write(auto_pwn_c_code)
auto_pwn_file.close()
subprocess.run(['/usr/bin/gcc', '-O0', '-fno-stack-protector', '-no-pie', './auto-pwn.c', '-o', 'auto-pwn'], env={'PATH': '/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin'})
os.remove('./auto-pwn.c')
print('-' * 27 + ' START BINARY ' + '-' * 27 + '\n')
print(os.popen('cat ./auto-pwn | xxd').read())
print('-' * 28 + ' END BINARY ' + '-' * 28)
subprocess.run(['./auto-pwn'], stdin=sys.stdin, timeout=10)
os.remove('./auto-pwn')
if __name__ == '__main__':
print('We give you a few binary with a arbitrary offset. Your task is to use your automated\n pwning setup (that you obviously already have) to get the flag.')
print('Are you ready ? [y/n] ', end='')
choice = input()
if ( choice == 'y' or choice == 'Y' ):
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2021/crypto/NJWT/NJWT.py | ctfs/niteCTF/2021/crypto/NJWT/NJWT.py | import base64
from Crypto.Util.number import *
import sys
import random
import os
import sympy
class NJWT:
n = 1
e = 1
d = 1
def __init__(self):
self.genkey()
return
def genkey(self):
p = getStrongPrime(1024)
q = p
k = random.randint(0,100)
for _ in range(k):
q += random.randint(0,100)
q = sympy.nextprime(q)
self.n = p*q
self.e = 17
self.d = inverse(self.e,(p-1)*(q-1))
return
# Utility function to just add = to base32 to ensure right padding
def pad(self,data):
if len(data)%8 != 0:
data += b"=" * (8-len(data)%8)
return data
def sign(self,token):
sig = long_to_bytes(pow(bytes_to_long(token),self.d,self.n))
return sig
def generate_token(self,username):
if 'admin' in username:
print("Not authorized to generate token for this user")
return "not_auth"
header = b'{"alg": "notRS256", "typ": "notJWT"}'
payload = b'{user : "' + username.encode() + b'", admin : False}'
token = header + payload
sig = self.sign(token)
# Base-32 and underscores cuz its NOT JWT
token = base64.b32encode(header).decode().strip("=") + "_" + base64.b32encode(payload).decode().strip("=") + "_" + base64.b32encode(sig).decode().strip("=")
return token
def verify_token(self,token):
data = token.split("_")
header = base64.b32decode(self.pad(data[0].encode()))
if header != b'{"alg": "notRS256", "typ": "notJWT"}':
return "invalid_header"
payload = base64.b32decode(self.pad(data[1].encode()))
if not b'admin : True' in payload:
return "access_denied"
given_sig = bytes_to_long(base64.b32decode(self.pad(data[2].encode())))
msg = long_to_bytes(pow(given_sig,self.e,self.n))
if msg == header+payload:
return "Success"
else:
return "invalid_signature"
return
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2021/crypto/NJWT/app.py | ctfs/niteCTF/2021/crypto/NJWT/app.py | from flask import Flask, render_template, request, make_response
import NJWT
import os, base64
from dotenv import load_dotenv
app = Flask(__name__)
load_dotenv()
FLAG = os.environ.get('FLAG')
Obj = NJWT.NJWT()
@app.route('/')
def index():
cookie = "None"
resp = make_response(render_template("index.html", display=cookie))
try:
resp.set_cookie('NJWT', cookie)
except TypeError:
print("TypeError")
return resp
@app.route('/generateToken', methods=["GET", "POST"])
def generateToken():
if request.method == "GET":
return render_template("index.html", display="THAT IS NOT HOW YOU ARE SUPPOSED TO GENERATE TOKEN.")
else:
username = request.form['username']
cookie = Obj.generate_token(username)
resp = make_response(render_template("index.html", display=cookie))
if cookie == "not_auth":
return render_template("index.html", display='Username Admin is not allowed.')
try:
resp.set_cookie('NJWT', cookie)
except TypeError:
print("TypeError")
return resp
@app.route('/verify', methods=["POST", "GET"])
def verify():
if request.method == 'GET':
return render_template('response.html', msg="Error")
else:
token = request.cookies.to_dict()['NJWT']
flag = Obj.verify_token(token)
if flag == 'access_denied':
return render_template('response.html', msg="Access Denied")
elif flag == "invalid_signature":
return render_template('response.html', msg="Invalid Signature")
elif flag == "invalid_header":
return render_template('response.html', msg="Invalid Header")
elif flag == "Success":
return render_template('flag.html', msg=FLAG)
else:
return render_template('response.html', msg="Error")
if __name__ == '__main__':
app.run(debug=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2021/crypto/CPA/enc.py | ctfs/niteCTF/2021/crypto/CPA/enc.py | from sage.all import *
from Crypto.Util.number import bytes_to_long
from FLAG import flag
f = flag
def make_matrix(n):
zn = IntegerModRing(n)
mat_list = [randint(0, n-1) for i in range(4)]
mat = [[mat_list[0], mat_list[1]], [mat_list[2], mat_list[3]]]
mat = Matrix(zn, mat)
return mat
def enc(pt,n):
alpha = make_matrix(n)
X = make_matrix(n)
while X*alpha.inverse() == alpha*X or alpha.is_invertible == False or X.is_invertible == False :
alpha = make_matrix(n)
X = make_matrix(n)
beta =X.inverse()*alpha.inverse()*X
r = randint(1, 2**512)
gamma = X**r
s = randint(1, 2**512)
delta = gamma**s
epsilon = delta.inverse()*alpha*delta
k = delta.inverse()*beta*delta
ct = k*pt*k
return (alpha,beta,gamma,ct,epsilon)
p = random_prime(2**256)
q = random_prime(2**256)
n = p*q
long_flag = bytes_to_long(f)
l = len(str(long_flag))
q = l//4
pt = []
for i in range(4):
pt.append((str(long_flag)[i*q:(i+1)*q]))
if pt[i].startswith('0'):
pt[i-1] += '0'
p = [int(i) for i in pt]
pt = [[p[0],p[1]],[p[2],p[3]]]
pt = Matrix(pt)
pub = enc(pt,n)
#CREATING MATRIX LINEAR EQUATIONS
#A*X + B*Y = C
#D*X + E*Y = F
A = make_matrix(n)
B = make_matrix(n)
D = make_matrix(n)
E = make_matrix(n)
C = A*X + B*Y
F = D*X + E*Y
while A.is_invertible()==False or B.is_invertible()==False or C.is_invertible()==False or D.is_invertible()==False or E.is_invertible()==False or F.is_invertible()==False:
A = make_matrix(n)
B = make_matrix(n)
D = make_matrix(n)
E = make_matrix(n)
C = A*X + B*Y
F = D*X + E*Y
print('n:', n)
print('alpha: ', pub[0])
print('beta:', pub[1])
print('gamma:', pub[2])
print('cipher text:', pub[3])
print('-'*440)
print('A:',A)
print('B:',B)
print('C:',C)
print('D:',D)
print('E:',E)
print('F:',F) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2021/crypto/Variablezz/enc.py | ctfs/niteCTF/2021/crypto/Variablezz/enc.py | import random
flag = 'nite{XXXXXXXXXXXXXXXXXXXXXXXX}'
a = random.randint(1,9999999999)
b = random.randint(1,9999999999)
c = random.randint(1,9999999999)
d = random.randint(1,9999999999)
enc = []
for x in flag:
res = (a*pow(ord(x),3)+b*pow(ord(x),2)+c*ord(x)+d)
enc.append(res)
print(enc) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2021/crypto/Rabin_To_The_Rescue/rabin_to_the_rescue.py | ctfs/niteCTF/2021/crypto/Rabin_To_The_Rescue/rabin_to_the_rescue.py | from Crypto.Util.number import *
from sympy import *
import random
def mixer(num):
while(num>1):
if(int(num) & 1):
num=3*num+1
else:
num=num/2
return num
def gen_sexy_primes():
p=getPrime(256)
q=p+6
while((p%4!=3)or(q%4!=3)):
p=getPrime(256)
q=nextprime(p+1)
return p, q
p, q=gen_sexy_primes()
n=p*q
def encrypt(m, e, n):
return pow(m, e, n)
e=int(mixer(q-p))*2
print("________________________________________________________________________________________________")
print("\n\n")
print("-----------------------------------")
print("-----------------------------------")
print("-----------------------------------")
print(" /\\")
print(" __/__\\__")
print(" \\/ \\/")
print(" /\\____/\\")
print(" ``\\ /`` ")
print(" \\/")
print("-----------------------------------")
print("-----------------------------------")
print("-----------------------------------")
print("\n\n")
print("Welcome to the Encryption challenge!!!!")
print("\n")
print("Menu:")
print("=> [E]ncrypt your message")
print("=> [G]et Flag")
print("=> E[x]it")
print("________________________________________________________________________________________________")
while(true):
choice=input(">>")
if choice.upper()=='E':
print("Enter message in hex:")
try:
m=bytes_to_long(bytes.fromhex(input()))
except:
print("Wrong format")
exit(0)
ciphertext=encrypt(m,e,n)
print("Your Ciphertext is: ")
print(hex(ciphertext)[2:])
elif choice.upper()=='G':
print("Your encrypted flag is:")
with open('flag.txt','rb') as f:
flag=bytes_to_long(f.read())
t=random.randint(2, 2*5)
for i in range(t):
ciphertext=encrypt(flag,e,n)
print(hex(ciphertext)[2:])
elif choice.upper()=='X':
print("Exiting...")
break
else:
print("Please enter 'E','G' or 'X'")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2021/crypto/Flip_Me_Over/flipmeover.py | ctfs/niteCTF/2021/crypto/Flip_Me_Over/flipmeover.py | from Crypto.Cipher import AES
from Crypto.Util.number import *
import os
from Crypto.Util.Padding import pad,unpad
from Crypto.Util.strxor import strxor
import random
import hashlib
from secrets import FLAG
KEY = os.urandom(16)
entropy = hashlib.md5(os.urandom(128)).digest()
def generate_token(username):
iv = os.urandom(16)
try:
pt = bytes.fromhex(username)
except:
print("Invalid input.")
exit(0)
if b'gimmeflag' in pt:
print("Nah not allowed.")
exit(0)
cipher = AES.new(KEY,AES.MODE_CBC,iv)
ct = cipher.encrypt(pad(pt,16))
tag = b'\x00'*16
for i in range(0,len(ct),16):
tag = strxor(tag,ct[i:i+16])
tag = strxor(tag,iv)
tag = strxor(tag,entropy)
return tag.hex()+ct.hex()
def verify(tag,token):
try:
tag = bytes.fromhex(tag)
ct = bytes.fromhex(token)
except:
print("Invalid input")
exit(0)
for i in range(0,len(ct),16):
tag = strxor(tag,ct[i:i+16])
tag = strxor(tag,entropy)
iv = tag
cipher = AES.new(KEY,AES.MODE_CBC,iv)
username = cipher.decrypt(ct)
return username.hex()
print("Hello new user")
print("We shall allow you to generate one token:")
print("Enter username in hex():")
username = input()
token = generate_token(username)
print(token)
while True:
print("Validate yourself :)")
print("Enter token in hex():")
token = input()
print("Enter tag in hex():")
tag = input()
if b'gimmeflag'.hex() in verify(tag,token):
print("Oh no u flipped me...")
print("I am now officially flipped...")
print("Here's ur reward...")
print(FLAG)
break
else:
print("Something went wrong...")
print(f"Is your username {verify(tag,token)}")
print("Smthin looks fishy")
print("Pls try again :(")
print()
entropy = hashlib.md5(entropy).digest() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2024/ai/Mumbo_Dumbo/pow.py | ctfs/niteCTF/2024/ai/Mumbo_Dumbo/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/niteCTF/2024/crypto/R_Stands_Alone/chal.py | ctfs/niteCTF/2024/crypto/R_Stands_Alone/chal.py | from Crypto.Util.number import *
def gen_keys():
while True:
a = getPrime(128)
b = getPrime(128)
A = a+b
B = a-b
p = ((17*A*A*A) - (15*B*B*B) - (45*A*A*B) + (51*A*B*B)) // 8
if isPrime(p) :
return a, b, p
p, q, r = gen_keys()
e = 65537
n = p*q*r
flag = b"nite{REDACTED}"
ct = pow(bytes_to_long(flag), e, n)
print(f"{r =}")
print(f"{ct =}")
"""OUTPUT :
r =17089720847522532186100904495372954796086523439343401190123572243129905753474678094845069878902485935983903151003792259885100719816542256646921114782358850654669422154056281086124314106159053995410679203972646861293990837092569959353563829625357193304859110289832087486433404114502776367901058316568043039359702726129176232071380909102959487599545443427656477659826199871583221432635475944633756787715120625352578949312795012083097635951710463898749012187679742033
ct =583923134770560329725969597854974954817875793223201855918544947864454662723867635785399659016709076642873878052382188776671557362982072671970362761186980877612369359390225243415378728776179883524295537607691571827283702387054497203051018081864728864347679606523298343320899830775463739426749812898275755128789910670953110189932506526059469355433776101712047677552367319451519452937737920833262802366767252338882535122186363375773646527797807010023406069837153015954208184298026280412545487298238972141277859462877659870292921806358086551087265080944696281740241711972141761164084554737925380675988550525333416462830465453346649622004827486255797343201397171878952840759670675361040051881542149839523371605515944524102331865520667005772313885253113470374005334182380501000
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2023/misc/least_ELOistic_fish/main.py | ctfs/niteCTF/2023/misc/least_ELOistic_fish/main.py | from stockfish import Stockfish
stockfish = Stockfish(path='/usr/bin/stockfish/stockfish-ubuntu-x86-64-avx2')
{
"Debug Log File": "",
"Contempt": 0,
"Min Split Depth": 0,
"Threads": 4,
"Ponder": "false",
"Hash": 2048,
"MultiPV": 1,
"Skill Level": 69,
"Move Overhead": 10,
"Minimum Thinking Time": 60,
"Slow Mover": 100,
"UCI_Chess960": "false",
"UCI_LimitStrength": "false",
"UCI_Elo": 3600
}
blacklist = [ "import", "open", "module", "write", "load", "read", "flag", "eval", "exec", "system", "os", "_", "#", "'", "\"" ]
print("_______________________________________")
print("| |")
print("| WELCOME TO UNFAIR CHESS! |")
print("| |")
print("| You know the rules and so do I! |")
print("|_____________________________________|")
print()
stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
print(stockfish.get_board_visual())
count = 0
all_moves = list()
try:
while count<150:
user_move = ""
while user_move == "":
user_move = input("Your move: ").strip()
if user_move:
all_moves.append(user_move)
stockfish.make_moves_from_current_position([user_move])
print(stockfish.get_board_visual())
else:
print("Error: Empty input. Please enter a valid move.")
stockfish.make_moves_from_current_position([stockfish.get_best_move()])
print(stockfish.get_board_visual())
count += 1
change = stockfish.get_fen_position().split()
change[1] = 'b'
changed = ' '.join(change)
stockfish.set_fen_position(changed)
stockfish.make_moves_from_current_position([stockfish.get_best_move()])
print(stockfish.get_board_visual())
count += 1
print(count)
except:
if(count>50):
print("Wow, you are incredible! Now, lets check your execution in this game.")
result = "".join(all_moves)
if not any(any(word in result for word in blacklist_word.split()) for blacklist_word in blacklist):
exec(result)
else:
print("Invalid characters.")
else:
print("GAME OVER!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2023/crypto/cha_cha_cha/server.py | ctfs/niteCTF/2023/crypto/cha_cha_cha/server.py | #!/usr/bin/python3 -u
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from secret import FLAG
TOKEN = ''.join(['{:02x}'.format(byte) for byte in os.urandom(9)])
def get_tokens():
tokens = [str(TOKEN[i:i+3]) for i in range(0, len(TOKEN), 3)]
return tokens
def derive_key(token, iterations=100000, key_length=32):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
salt=b'CryPT0N1t3',
length=key_length,
iterations=iterations,
backend=default_backend()
)
key = kdf.derive(token.encode())
return key
def decrypt(ciphertext, token_index):
nonce = ciphertext[:12]
ciphertext = ciphertext[12:]
key = derive_key(tokens[token_index])
cipher = ChaCha20Poly1305(key)
plaintext = cipher.decrypt(nonce, ciphertext, None)
return plaintext
def main():
global tokens
global token_index
global queries
tokens = get_tokens()
token_index = 0
queries = 0
while queries <= 800:
print ("\nchoose an option:\n")
print("1. select token")
print("2. decrypt")
print("3. get flag")
print("4. exit")
option = input(">>: ")
if option == "1":
sel = int(input("\nselect a token (1-6)\n>>: "))
if 1 <= sel <= 6:
token_index = sel - 1
else:
print("invalid token index")
elif option == "2":
ciphertext = bytes.fromhex(input("ciphertext (hex): "))
try:
pt = decrypt(ciphertext, token_index)
print (f"decrypted (hex): {pt.hex()}")
except:
print ("error decrypting")
elif option == "3":
entered_token = input("enter token: ")
if entered_token == TOKEN:
print(f"{FLAG}")
break
else:
print("wrong token")
break
elif option == "4":
break
queries += 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/niteCTF/2023/crypto/double_whammy/server.py | ctfs/niteCTF/2023/crypto/double_whammy/server.py | #!/usr/bin/python3 -u
import json
import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from ecdsa import VerifyingKey
from ecdsa.util import sigdecode_der
from random import getrandbits
from secret import FLAG
with open("public.pem") as f:
public_key = VerifyingKey.from_pem(f.read())
with open("users.json", 'r') as f:
users = json.load(f)
def verify(name, userid, sig):
msg = f'{name} | {userid}'.encode()
try:
return public_key.verify(sig, msg, hashlib.sha256, sigdecode=sigdecode_der)
except:
print(f"signature verification failed")
return False
def iv_gen():
iv = b''.join(getrandbits(24).to_bytes(3, byteorder='big') for i in range(4))
return iv + b'nite'
def encrypt(key, pt):
iv = iv_gen()
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(pt, AES.block_size))
return iv + ct
def decrypt(key, ct):
iv = ct[:16]
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct[16:]), AES.block_size)
return pt.decode()
def get_flag():
key = getrandbits(128).to_bytes(16, byteorder='big')
return encrypt(key, FLAG)
def login():
print("\nenter credentials:")
name = input("name: ")
userid = input("userid: ")
sig = input("signature: ")
if verify(name, userid, bytes.fromhex(sig)):
if (name == "FUTURE ADMIN" and userid == "SONY953"):
admin()
else:
try:
assert users[userid]['sign'] == sig
except:
print("invalid credentials")
user()
else:
print("invalid credentials")
def user():
while True:
print("\nchoose an option:")
print("1. encrypt\n2. decrypt\n3. back to login\n4. exit")
option = input(">> ")
if option == "1":
key_hex = input("key (hex): ")
pt = input("plaintext: ")
try:
key = bytes.fromhex(key_hex)
assert len(key) == 16
ct = encrypt(key, pt.encode())
print(f"encrypted: {ct.hex()}")
except Exception as e:
print(f"error encrypting: {e}")
elif option == "2":
key_hex = input("key (hex): ")
ct = input("ciphertext (hex): ")
try:
key = bytes.fromhex(key_hex)
assert len(key) == 16
pt = decrypt(key, bytes.fromhex(ct))
print(f"decrypted: {pt}")
except Exception as e:
print(f"error decrypting: {e}")
elif option == "3":
break
elif option == "4":
exit()
def admin():
while True:
print("\nchoose an option:")
print("1. get flag\n2. back to login\n3. exit")
option = input(">> ")
if option == "1":
flag = get_flag()
print(f"\nencrypted: {flag.hex()}")
elif option == "2":
break
elif option == "3":
exit()
def main():
while True:
login()
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/niteCTF/2023/crypto/babyRSA/encrypt.py | ctfs/niteCTF/2023/crypto/babyRSA/encrypt.py | from Crypto.Util.number import getPrime, bytes_to_long
from secret import FLAG
m = bytes_to_long(FLAG)
f = open ('output.txt', 'w')
e = 37
n = [getPrime(1024)*getPrime(1024) for i in range(e)]
c = [pow(m, e, n[i]) for i in range(e)]
with open ('output.py', 'w'):
f.write(f"e = {e}\n")
f.write(f"c = {c}\n")
f.write(f"n = {n}\n")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2023/crypto/Unraveling_the_Patterns/challenge.py | ctfs/niteCTF/2023/crypto/Unraveling_the_Patterns/challenge.py | import os
import random
from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long
def get_seed(size):
return int(os.urandom(size).hex(), 16)
input_data = None
output_data = ""
seed = get_seed(4)
random.seed(seed)
old = "0123456789abcdef"
new = list(old)
random.shuffle(new)
new = ''.join(new)
with open("input.txt", "r") as in_file:
input_data = in_file.read()
for alpha in input_data:
encoded = (bytes(alpha.encode()).hex())
output_data += new[old.index(encoded[0])]
output_data += new[old.index(encoded[1])]
with open("output1.txt", "w") as f:
print("{}".format(output_data), file=f)
key = RSA.generate(4096, e=3)
msg = "" #from output1.txt
ind = 280
flag = "nite{do_not_worry_this_is_a_fake_flag!!}"
msg = msg[:ind] + flag + msg[ind:]
m = bytes_to_long(msg.encode())
c = pow(m, key.e, key.n)
with open("output2.txt", "w") as f:
print("n = {}".format(key.n), file=f)
print("e = {}".format(key.e), file=f)
print("c = {}".format(c), file=f) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2023/crypto/Quantum_Quandary/LWE.py | ctfs/niteCTF/2023/crypto/Quantum_Quandary/LWE.py | from secret_value import message
import numpy as np
import json
from pathlib import Path
flag = "nite{xxxxxxxxxxxxxx}"
l = len(message)
def message_to_vector(message):
vector = [ord(char) for char in message]
return vector
m = message_to_vector(message)
def randomized_matrix(lower_bound, upper_bound, row, column):
rando = np.random.uniform(lower_bound, upper_bound, size=(row, column))
return rando
def randomised_matrix(lower_bound, upper_bound, row, column):
rando = np.random.randint(lower_bound, upper_bound, size=(row, column))
return rando
A = randomized_matrix(20, 50, l, l)
s = randomized_matrix(20, 50, l, l)
e = randomised_matrix(-2, 2, l, 1)
t = np.dot(A, s) + e
from numpy import ndarray
def create_cipher(key1, key2, message):
e1 = randomised_matrix(-2, 2, l, 1)
e2 = randomised_matrix(-2, 2, l, 1)
e3 = randomised_matrix(-2, 2, l, 1)
u = np.dot(key2, e1) + message
v = np.dot(key1, e1)
return u, v
u, v = create_cipher(A, t, m)
print(f"u = {ndarray.tolist(u)}")
print(f"v = {ndarray.tolist(v)}")
def dump_values(s, A, t):
if isinstance(s, np.ndarray):
dump = {'secret_key': s.tolist(), 'A': A.tolist(), 't': t.tolist()}
else:
dump = {'secret_key': s}
home_directory = Path.home()
if home_directory:
dump_folder = home_directory / 'dump'
if not dump_folder.is_dir():
try:
dump_folder.mkdir(parents=True, exist_ok=True)
except Exception as e:
print(f"Error creating dump folder: {e}")
return
dump_file = dump_folder / 'dump_values.json'
try:
with open(dump_file, 'w') as file:
json.dump(dump, file, indent=2)
except Exception as e:
print(f"Error dumping values to file: {e}")
else:
pass
dump_values(s, A, t) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2023/web/Image_Gallery/main.py | ctfs/niteCTF/2023/web/Image_Gallery/main.py | from flask import Flask, render_template, request, redirect, url_for, session
import sqlite3
import uuid
app = Flask(__name__)
app.secret_key = str(uuid.uuid4())
@app.route("/login", methods=["POST", "GET"])
def login():
if "logged_in" in session and session["logged_in"]:
session.pop("logged_in", None)
return redirect(url_for("login"))
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
loweruser = username.lower()
lowerpass = password.lower()
invalid_entries = invalid_entries = [
"=",
"<",
">",
"+",
"//",
"|",
";",
" ",
" ",
"'1",
" 1",
" true",
"'true",
" or",
"'or",
"/or",
" and",
"'and",
"/and",
"'like",
" like",
"/like",
"'where",
" where",
"/where",
"%00",
"null",
"admin'",
]
matching_value = next(
(
value
for value in invalid_entries
if value in loweruser or value in lowerpass
),
None,
)
if matching_value:
error = (
f"Invalid entry in username and/or password fields. Please try again."
)
return render_template("login.html", error=error)
conn = sqlite3.connect("chal.db")
cursor = conn.cursor()
query = f"SELECT secret FROM login_details WHERE username = '{username}' AND password = '{password}';"
result = cursor.execute(query)
user = result.fetchone()
conn.close()
if user:
session["logged_in"] = True
session["username"] = username
session["secret"] = user[0]
return redirect(url_for("profile"))
else:
error = "Invalid login credentials. Please try again."
return render_template("login.html", error=error)
return render_template("login.html")
@app.route("/")
def index():
if "logged_in" in session and session["logged_in"]:
session.pop("logged_in", None)
return redirect(url_for("index"))
return render_template("landing.html")
@app.route("/profile")
def profile():
if "logged_in" in session and session["logged_in"]:
username = session["username"]
secret = session.get("secret")
key = "0"
if "secret" not in str(secret):
key = "1"
return render_template(
"profile.html", username=username, secret=secret, key=key
)
else:
error = "You are not logged in. Please log in first."
return render_template("login.html", error=error)
@app.route("/logout")
def logout():
session.pop("logged_in", None)
return render_template("login.html")
@app.after_request
def add_cache_control(response):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "-1"
return response
if __name__ == "__main__":
app.run(host="0.0.0.0", port=1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2025/crypto/smol_fan/server.py | ctfs/niteCTF/2025/crypto/smol_fan/server.py | from hashlib import sha256
from ecdsa import VerifyingKey, SECP256k1
from gmpy2 import is_prime
import os
import sympy
import secrets
FLAG_MESSAGE = b"gimme_flag"
FLAG = os.getenv("flag","nite{fake_flag}")
curve = SECP256k1
G = curve.generator
n = curve.order
d = secrets.randbelow(n)
Q = d * G
vk = VerifyingKey.from_public_point(Q, curve=SECP256k1)
def ecdsa_sign(message: bytes):
while True:
z = int.from_bytes(sha256(message).digest(),"big") % n
k = secrets.randbelow(2**200 - 1) + 1
R = k * G
r = R.x() % n
if r == 0 or is_prime(r) == 0:
continue
k_inv = pow(k,-1,n)
s = (k_inv * (z + r*d)) % n
if s == 0 or is_prime(s) == 0:
continue
m = r*s
a = pow(10 + r,11,m)
b = pow(s**2 + 10,r,m)
return m,a,b
def ecdsa_verify(message: bytes, r: int, s: int) -> bool:
if not (1 <= r < n and 1 <= s < n):
return False
z = int.from_bytes(sha256(message).digest(),"big") % n
w = pow(s,-1,n)
u1 = (z * w) % n
u2 = (r * w) % n
X = u1 * G + u2 * Q
x = X.x() % n
return x == r
def get_pubkey():
print("Public key (uncompressed):")
print(f"Qx = {Q.x()}")
print(f"Qy = {Q.y()}\n")
def cmd_sign():
m_hex = input("Enter message as hex: ").strip()
try:
msg = bytes.fromhex(m_hex)
except ValueError:
print("Invalid hex.\n")
return
if msg == FLAG_MESSAGE:
print("THATS NOT ALLOWED.\n")
return
m,a,b = ecdsa_sign(msg)
print(f"m = {m}")
print(f"a = {a}\n")
print(f"b = {b}\n")
def claim():
print("Submit a signature for the flag.")
try:
r_str = input("Enter r: ").strip()
s_str = input("Enter s: ").strip()
r = int(r_str)
s = int(s_str)
except ValueError:
print("Invalid integers.\n")
return
if ecdsa_verify(FLAG_MESSAGE, r, s):
print(FLAG)
else:
print("Invalid signature.\n")
def main():
print("Menu:")
print(" 1) Get public key")
print(" 2) Sign a message")
print(" 3) Submit claim for the flag")
print(" 4) Quit")
while True:
choice = input("> ").strip()
if choice == "1":
get_pubkey()
elif choice == "2":
cmd_sign()
elif choice == "3":
claim()
elif choice == "4":
print("Bye!")
break
else:
print("Invalid choice.\n")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2022/crypto/Shoo-in/primes.py | ctfs/niteCTF/2022/crypto/Shoo-in/primes.py | 8342828072912665446640812496657974616895237729734331520447110635700611195720588924201965069564261323380181467910921708206195375403970552688043142521352679
11261182920255484587328622670740312344434746846806430954734873940195850016351945896817555661909277786253900984842735860881865717569965731032925702398871639
13188204471216646422412789202744330082643556859213246177046255769408687760764407710911775119836087336476942099671540300222638500542149976941263838656459379
13123689485447687052486653550683059154124720659336653302333479596387363217707254591423240797085645700225539521724429974011780150852270894038325888327597357
9151867259817796223137657365063120830046248147403894701093515398686188731095244059034436528341949618062849182749487665414119058072393876067793302819222729
10949390751054461805057349957742733025796585599489526910545693673671649894519218001066967917135896562950461093021320305277479934483167124145740297584284493
12196336181525360252460649520518205294965557736971181292311980841368926015529847186368081445345708102550227723624207488185247401857271884112063404895809073
10407316586139777257153426778677936705731182641649805023808539858247436923513961229314810183565743454794356901135908751651236557144911365680805710503650861
8139762250215544514407052197189414899004288944043577122796315397132907787706458346834391114214544270136790291853245698278844582411144774479801743990138801
12515962753423000710849589250386155062250925851952207148581467927370842325239499601343542272430246754124975845476426969761416500529854524719346975552258223
10370700732300879743185860809462166755033294717722998070326858237399077357782499945435418248486460728754242567394968853190347555352541061218190628620702961
11603327698876289336306499241053363805761575801799437570389251759055503141149309404570461738746083282593095336840704287256260558894605360321600882049818629
8917529746647563697407710069310546107679339825462569684254656668130418228743094445290054986817136944369412688060240870012026656498908282472024977370808793
7207339468841752789557111561834964418051786797455016722775880959184763344090771446731273040955500306201131558296287163016928914617596059743072719228699129
9957618971422368775504732184372037010551805915655798609063021082090479730998177731983487101418463118543059683417669582012189942310810727808531078299432121
10606400927191921442859379182930982823024573271986943581512077482989012208027930933284882881303133169081824922566494245214128594896388391866837041552081933
13059409412107550869379874965778658854366685707957305683445122416071172136952247826937811853810389083153744361858952994043557278622242605037179484950159527
10775383200255132545732987665553060629593102556252340222322556268251811445548994258452362804531112136783470255723327385455748842772876858783014821778392007
8188732601307823536638632697512763679699388231729693043897722584385187501359193339686197683126241904494654584041930260081806756149600290811823218863555401
12014637359370919237515460272381853441944713385158425940054937792394056235387536399936490871228514331804128904069498134229403982613288311493791137836563853
11680482964941481016220761645635156028236133730689561626917658310753504239531853099164506114409019356398601306651629155182127980557621203255894462706955489
9796274307293044540584569727271524011062613568988960678654402684000657069307994744362179024598649496489875494877403525442279624046719901742693487536116193
7134555881075729124860520725368249625300397446232754592160556382495830552267587399878821553449285199695708743680481193076415708084180931169891957178659311
7699881086723402500244830200100419314101287480327335409062711639759961721539623851654064230228767521353177606977325822516692029495897204726840405656329629
10881160158921085142184580954998653422458518269660610216971757281952371862537582915355443061872227774151698793033595370717616014661904338469539085361133857
10593516581992446988495866142429303748423655867243973877767106527956796434933413716769501284117226635526811128669298649750287197349487273025611791899747123
12167713317978576007577162865426392256726453258821691515058696359294600508691604383501606162256281107414079053816220998539121909539542022395319618043996773
10610408130448005712286966653303184824746317869400710840476497467252994544056939111194391377474693500635307257152801371297216162483396971231548700089546447
8320912373485873045056020011443175494885657688598365874661213786668076346768051254910279155987716587660146608871533283944823957645779539196444493781839859
7762113474084689119308735084738760984022404523399124912692931159999441261118230806508906238521923970417210364020917189082144898690917131705830929102546373
8823205401686126221069508538960285071066021666158047912983104355852279886738640292030077985972232831105517273880167267771713901840621486417850366448113227
11193719902409697897152616365354275469865411627496069265882681024347310936367214160409557507764985435524952190365982094834667910706894907424815656978235009
8806843851956151815404765839643181355406419059348975384122519325325155245784907666302462470626114841618549929257646683422717508664094977816405551226596641
6921216510254206979339638944528093234057206613614547344055690062539747179262458822109607776380751160437881332788382723673170286802192109720973832699468819
8731883112457880005945572343420643346425511140884052095422785920272323837806792092147537203675666909831334470625370643395453760915765956813484722410436043
8535212311838276265970523029511000987688991221851900607884162901680948618126723448736956608878367082057162115570523973634580345703701762792559430624895911
9433480188422364683334789872473026949499415101541715821644565185950367905048465363935196424189828034793141287796283180898262999252086695488409413798302121
12699051393137243958729839854264711339620543693831195126351140737360133822781738797829730563675456429563272174988521574901373395084003681838805976893524277
9040183656160175245706741649459462120136600536653411174049111082502711364200601728433541336179862174247901215296466390299984100475035001289817609278458347
10761035296418583464088146477187240780120436983348519929653016545034276054226328099397558143037385046294202875012126413235039883119793349584050312760810813
11084536122813715927410051257817590896970562361811652731907519111743509886000443634629301965808931651188998735979652006281012423974337408085727916211410131
6712917156266970090487828651230931667424858508861690125371148816456966010005568930177505216389348869226898079777818884466197861764209503873982759779495133
12973221200518243209427427909969238585640409431420714261399138024479342589916554162397892965551791266039293099460449097836564623912326525761811139956446811
7497177824926250947687175549959644057195245994363181119385548634588157034089687245059196115242731093409476933206094955340740427226216200174765106673766879
6786976215146284340422519160226685795906756061349956977950258803128788167998446703445173564535641479012112302741406476886585500488047047300313328828754463
8814448618547485088410707788503662160771606281964801790269116000620089489853947228264175637209438237732220803038416508279577776853983569451530898803700771
9704346781277509819214828307357674189645485249514613973138428001520512945686665964470732274278891614695242503956575251651045556550062742680179213637129827
10371067888900195747780307517419660377490343998891077765115747577950683471799621910106030211868247912267469393186626159852554550218478806684167973317914123
6959306449684473090739653859920515214056809708049124457988079596780168462654790383893811893107306917576460044410759764538775331046574485356624376606535383
10667273074300205486364885598392141923984617157223606576742102510328225540481701790369209928236465042169317370416280501388424503674768799770323694848961329
10116689842536698157049779407270946613890222839747233396718348252458922055049850643062252624511479779960418374405275773520847955858541529028272677318053879
8054698143329230412629898873652392162586869916573537533831928783032134420685028762998114627509665426619991667713699118168787070530911220909595527569764483
13393990304300265551219708150545602407790676630005878650141342115248378120370367966936042518963732799133382399398158101139432437995654297784982269202352777
10000179356858460732756695412564174120058279831008583518368035834686980291991346933710163212842636191738686580673403095705732468753955752850999250643445079
8913429827389283329826609022663161801505210331533941105457490127671982623050159933041157978357164005993343494683993852048551473380981206212977334820124449
12687388366745029048007533777503821827210913477928455269765200197269285240801509945580442226990759599907103133180662905060829008245451207490903074902134327
10589295345784943970624427448245666939094570732860579305470488994222847630330901369895128440484989935333657778843860270782519769558806258697717239398416909
8529542597167782290523617913633709866715281926326214807161447657080788852309157501453143614025294053889749390617730356901832669266992429313262933989748087
12575913737149589403863501864263439591390913868622729336082651241604328635376081168899075224936956772579039829392336657867351720099213107285011043161422423
9587350632641889977837936580353411231018771744356236697712144117334475715721377384828689804594358639011309389532982260263571659148273232251459235418995023
12552565233122451506876365151995874439036548923255956810204291089720035943278178829214480477105115343683216766567804487756186101820844136977761495730138867
7050736440320351510631120420184252505247708722391794452546898589662729570174086890814410722099133533049946569384944123823627072674790887601965295190228849
12137254602672983142341336998967625372636718889187118267472247650844208021969140388510916156768058649855882418922786995354451074029178471943335404968571651
11908523692974470808089100408699326579693108482176995354408890873258020331660674414359887820145182685087622411280464588827198464052262080378908058222263513
10801267281612277307937764614809725425418804368820685895925255391260498532207167504023675540536918916848847999370401696829030612846137449408298008880456621
11634583419942322156661646124793952924571088292560741440677819572192831795195673528404507067163974965494292939430032539093805583788418603100554972449599421
11444103620604737687728278681298613119032508402427239438396977911303931318029563205767999720790134200496144654610684418366547833677602981604598530901610181
9475461543820399247351715568803021211699958136533380220455618477832934269170800420864986956655333804379843289592081978570632955727907458220209141525541567
7325426739264398223099326017193760788941068068668213382190416279139120317533395517330968610066854184244879356391349284844076167427985922729224376347652911
12732820300740908307009528307779752247870773810692798802526523082988967813348105240259472647550940846815332494659328749332425455294730844976827700819657287
13256637201015490564125654364638730406942628803170636357903689836831508654469099915786438072040364815725950775785090081163077112869675510279853585169520161
11977679254507953524805511340437729597952669795990298667717951335644049438928793733628264732309942816677255092829357336793819217013096838853389132458087629
9845084852566353072656542068679794576590630311727953520175557951392143763800398977570696705338050167249556345180483269551243398239298058598965360970666349
12074066788071680596381458512526236698882382143614937802051796132850607769027779493063860358701174939804354596396549101541392967358692861632030365755776611
11907632545958944561112748541040869379830799027169613333177426316505131071925525902037620749191209879789406522595002413631785766139893862750027974520863993
10717057860425222294312276970947482748847225977918552163849687789857458473790436165847089356087640364883306869455833096455414678901412516071992078832128991
12309250343861133939927882941639794444756899557025538710789239362166935263069243571787924887406546124639577260182191949453050789786013453572257983054890661
10814392762204831111594043760288898482789296499897854563447889272009349351743389135308869519280861030562709148056045281497553579254085069775146849751306997
11457335732239093557930400107191163336554964686204946845880510810232120689597815253395348370835283039110048803802319043675343716778751713360482160901281091
12999986332352213237253491494166285559285285546064864003643280544244737659151883806344530802949448779168976427379950608457935684897473550123737295678380589
7555548915695304310456673358352697335688189687286847456976263307897771891636972119401876189807453903880079953391995288728531844652985693985640785414386619
8299935726707548880269882063524577196325102386307590425884153739425922511720233562030555622402657539630256836829907960181020834112898248980230839401358671
13298536496820253240861305001927887968175596288298898191704319156501773139874562881313556952994919112541431591202476554269246048921157715489618236192688201
12282722610232898608854246107320488791097879035208205958849648601926195636499402286782986793266541654941198729137402575623532795642707779709513176943385071
11181224523563089614246803637095989048164338172649593985285800312460153589389426113583797334156684906543692731365594118286785450450893344407127337361633887
8807337640665618553161303391533942018806281036951221154032809931677693530078878672191264569587680384006627605519176477496430701491154116167695858643515573
13275820125477200828041757881152761156674682833598232205362832859285533302774584887758030254035207277164335453397184981731030089712515911944565083285844509
8206432223157304231238797187012843361987831209427445773453810861756153834192404767581283380804028625746355849438536188907582981365344059338828943348040129
12269600769362188795863509019537514210096428353484691271806241729557037417568222639618128976494146522962756009960168901381980898448341936521018773398462741
10230119916698716882582028438516367932712136264242803433154377489064375249352819997662028013420556609584408375730711403578050811371943920057802165005945577
8126881303759166287850519541966782009979584400719022314841881820822830829964047595515677810485794200498515872581911953614415226879971716518427380727172557
7716555054686355722017583355520324747067248046887137229885541136252967737095189775481105029059947393370440867426968830192954762986722799543532993458785569
8848748343313198059432063589777700795429577946667002495698952786186962030908501678342979822953351701441996321615226113743396412135480463843668457201129993
10196411169822072060190053928747155049244184879671701700390333523832912809238580048622115335100621032340450761076222264977164794255108501165104125218393933
8687024227896207250924871541849685516488471368989204041849923193269600121778250025873081949951405245257234747368553801311534450131536779226082690281915891
8965010124730408281366368585196833338268623988300824560950813905316107316785214497248119076025677324854734215757738404941400382132737056337559013117624849
13102501329810858854878264906528558923215487105230196152358833380749791047328308905013356187258033421850377166611531950677268904422512725154986088338753489
8327467318637681915909290639121065152593475732682967002399272362337917917348950615342280419894387498089190735843593143421084220179557449896685429789243121
9687121944319844080147437560855582444189069682890866872336014108556725566946171121621063224304098263442647187440840055876213323820884558271513863720678381
10362321922786623342848396290414143418076722646179442025436748974886098945966761428568176179887117559087258934580647813853301915625436233306194754870174969
9993444665831971076328996465269328138074268831329894059737595043198945534949956193164383500350140533359716254914954104254723433939988788807410908650638251
8411691214001830283142230468478632918067257584871214323078231354253333928592124662061662669007139450533944072555180315374426230190613088447968826748563731
10067419845918247626449590257653780074363827549740910543406204677183923654420261157765600175618916910499340332026682337901099566652305734839311355147605437
6916418336224784579428281422275988771055633013708943333937489066706409910146912418020516931305083507902942723867084354125860026907981548684523128346082749
11636861737042331245689517849475643909872262922553095722095392030581321656907875658402884900667404923102806268963906164664633248690943029226287912377320193
11050238458945816229441301801978404083346880837867586032584923690585303442904005415774910710811979156605022781815083211560756898545561499384440711823546303
12445109301676807013816134869833974930023223499654546811935180169566377666558079503508552676690928431439900024986950298729804974012151912243267859324407067
9498222908569853658415425623436923638846843704511914748717233701192057532722737855726462240535305606009910924442258881400926709888157670817769056558267287
8390272773327352073564392187834741139626128988692009555365968554751398569345802300657670997121283904869075271548396173592286944384629344915962366830842553
11911717707916914585965411108114535162896564875540364084542925166306436929429219608493696254926223148483997442060453314669855867921864372149706749936208787
11924293750344869537890102748199588355008523013233601709059926531256095108822265501244624163101522023139289318403272229959513216380279769946716106809470097
11357880575568333506309985621206313448155109875155941048063601183495909283266859845425750438884076618565120516659030692382876353806754067987683045346064017
7496365261914502536941966902298939668880533237746243781170668675708124795077064931975960069219370093536298054444486398791244695206298902444838925048697353
10153400522709812079718609699720038740008734904731704218249605400837625344950845934466285857943243639412830079337987348395990156438850361887891288918616609
7878400152556504591581021742004613005070202447875468829904803868455642479733120423422581020466179056229390720488158352601854029280208873017736422509128087
9895539022883658544916333250157393300132728641418034194839487921540980501332319816835480285835645150149141375631758565522928964272495521033209944714482201
10320226494717310208731238727667335854655348313999715915142572987792034093045805104802468897845474098002717126849421288952003070703528458559177816215249471
7935472658445919448045670560614089794599977436985620589307866498409321276880269257725407257892787836165231356480087996268506541709183835775554302617301111
10164017132448624242660313322699461754970324681412205319557607084572273317737497539134947783178607394359962598898021204816071497720847840495387707554067227
11842053313213829732971695391898284354783050257636228738151452726105273854515147036107826116966036036857738381564439117387921417209600621574805842925474113
10663529190190788783841878886643225401656001973452776060714870387385023908188898105235207069913570369333603126980214660697603095013492913041223540727717061
7582969556949774578648544389207614897832895319927970637248310431119648540872066673273638401035849672126034753547302550948321549570949905528694649561978051
12329840899705844638273641366188843771311026619295472916495289598669161676832523030841726746230564552275525439684684595079362106902157252448001338534469531
9501038121620180357314658282382976090340929832466021237760661349904202432896706821720124300383338698782760730679922141323537040962856781584759827705928303
12970224676204269355910152623836191823501453875543778481300202360325856499167146921021097755832665332244357844901377233353502827212781702883137422420277751
13046800814814297911843234401436416332651274393762841537399717143172949926366944287907467353327357798803573831446574865754789734998973436590545803434059309
13040441715826358470699063886184997846506279497632440787740191231416201547340651824454484625859495375133460285226155745123343289655089703049139302449074429
11367462096061591088378410289988345266125954433005735208062301425568889102080168249728163712098802332917784511286460267576141407905221907910425580130678687
6927552267437161085270666732674883910505541278609741871970185489324873428092943852559157439977292143435367566317636268433108130685669529484376345775754971
7962368614194610231303212491338961520982540104965658144662906141213200114196497025212939009731926133017416847080789566265888456464942964263949149286163521
8497911575957087374024263875665459482546973402036638929196331325816847172087591776484239665576198068775034635342356525349792478910145100237032919335855719
8134824510989464898558538446724834929676946922054367658059574256218440324242106961595166509528971138290465390743660658679065591617588298289085266528226509
12447519932645615603764133645392654555980154224427360836189172564203112455044179742181693483497511851187894884494701167792746497912884580569162284275108649
8322700732301132617185468746609828496718099582366758771562002837084995234386133261660830513071091267824710999328426350425174322910940921615262977312338779
7716436207803450266119028751156731761249440901307002274458968477934481296275866904725570045030456596035509885790350563675721572416543350375258170847121947
10278101158502953847896307911399011400379287319586886616133818857877269129262374455418136867225328192093383305183946958576183184809838904055216967978299733
11474679843913779804692121489367376656972606700843665794169837458977075215543119499387969684181700365736047817691961311668339426143432778432202534708331893
13194440057531751240044229193408168574650063887761035062842304250125518452229097205359529449551659977425794730490287650788377554428289258988787087032490941
8092491489317722489758897421404136883523206171721014378223106904311413595810679243832587738730302090559934043779091373715137673875385559812011158041801343
12772098229929223697371493534903699460808601671475217747961024292887845498874552345314830973045825682759832409568645625124498080953595077710887491499287561
11371802334100916419408212382071711543556427159130283035817745423234778835027452216684208486939885536750821960961745186388723785186889533109245456439243041
8138147952400589328974568852561602379481025584008892998893225061316696907474103280754664924473915699126392522474216683652237678164718503095848124300502751
9372419624264674071673441940416136960572860460310735544626591202283606872876952907109386148492766026052742802261182275712456255644118305473737649675241601
7006201802345390565752005299232365228753853398272596109972611248786606634045931978275303968996777291925269089409634094039173069097207481489300192898532461
11511961243960987916077411968203198260321194518692504638396124649471479301430264623054080747371154878384304848049714915549992589303342831512879908173616567
6911341822469521291028576397740456866866187399658008012093621679523192805426381117640513405707819662391552390043835196954683965568226475884963947868050893
9237913421949051779661017638555490093426110885444864553850244303278596466835234393600776968081844899411848546474228424840989508114477466284130163063896383
11605549665935250558759424223335961488893054766012547624293941702176821545244354040554994432135404979935677425862120923800136773108318314965318396183030591
9711981778293281008739070167094615958341250963983950666900010608185081960223442032471184451762222741854868406085777727858955558965763502921029470577870533
8293434343236732082091003905029567351157617964103598636073211373836496751248719082953753549400767051583901499392554044570029014584806955721079651024706371
10841935280752310527725283756565599139009093276643016464461016142234768568024029512442963026363793434816647084933365315117499382656754455071589892030181733
10972831712534518230469862885837663625015792416519129278837450366560065556474382962342070469546223163830231438523224978158506262280276964118289351354811319
13036965431163296854491098631031102377078467957300299575800912308158442320305600769764875163904210612424149831589929277580506382690264051992802632931398979
8165915262352507051574654466665925042419670742418732940833498187914436408226636753209346808054666574815425155859344202156147998459042593003708133550046783
11078458175471542852042704925202272386521629100363192266072907116116668274513049897944239630505746747570621269949647059586580057053544190253419264415925219
12338645360953689193072607361938471896927672020618119145068829921159699061165109532349260076601006113205086456408278908216612438968396831653780249685304983
12089623051580274350195356573291624296898968901967762968638637838628036869721989177295168163644635013423737391297834504277861999444186538604234250842496121
7230368401493361987185278750430940211580387465499257361055902895030916111148498747692082396878163291608371322585176054908177441492102920602157918054426771
11821062683947846079312811237911408023240194597567569927275790384499089475792192614612025098860371324416009113294492033141057225518942192336793363304915047
11622637090069638697620051999253052805204611719900854892570296463866454614276302609760658706913773491204460202165852308938629740154793403596585567709979199
12271371876187150762879062005985600677435851256459266673922528418949618563456975399908471288697007908587803270976471365898957391432387260828508089420204379
12479554306031788211088842171321165352180168287763857869716211529352357206228904245396692096947063626363257594967667425068962652589087783970564363256188571
9060748510266834735791953153254161522227971201714679206268210089134085909224699464957971932431339734827723764174560200202130890813602833707287546489727143
13000413790670052919240058731830216538511903184129205762484543415938589587428447820413219129634090468297705511632063416017396412857995052960543718104621403
12264395043944969963791613205012545679890689834018187248404457370551454956415657570265513630835299365498137488795995169358094851380321662324702674183011221
11492296395389004722811787358591112478544931522546363328025822242757061978475838732262598389294243208603185605392326965120581545769887419385810420454520921
6730875503723047113557005816676062502545781806150498473275594016998807325543456645586403288564437231317071685920905875520815883577963258084849772713556541
8858765911310133894817685485728252195505256454112330657758496343273778416854531617754820676772547359144273298345894861009206000397840061526320317027809537
11303757776216459869615547614456696404677745836936921786682679894143734146956512766656834153305641538838179668312184415930964804830196825782562365027527819
9645923392122074469513831201703450197303559151904387343898675868822600318227975793911779490589944685558914217389651087628065302835282588010686759176948447
6742798214388112232470343213766688056059795882171926155870560249067508759954297312401155371795207138429831216839975531465163894483807690136324673089963929
10596877922316695694409073093267193873859111390645889109242737570118655532178610674862056170541291282101067408431618566571927229138051338368567433522245407
8998473500950198090521516761645019831097924952860124008545637656806985084405381261044228749981983299352666885566836355200012950666429387599230348201354157
9444432079115278121119982105462005268420739493097595965851540473913107267159266752810298287114838700094397288031166761815996092026437549242299363324025181
10852674662564105714329614434864398662255447061227554130575410451963522357184057064631848556671098541198186795254411031719703775516677809422311928670909463
11549066521270319064542180227266043814487997852907304481395136262754794707969427915693259259181798252733601795880066705105497166423096419342507809878292859
9782079252098008002705473211945893220107825685168507077288011388229933484454414513955818708743601389247981670732885116315844009613118563890975749323271509
12600390845279151140419730935013553337640899425151374197284613591534179299868159486308687974958895031389493340860818551893131469284605340781105273564533193
10795668893360584984005328843208792301440308869569670327662007070101492029804841909677000424655427021050750203346580176673787409113239456859043185230311771
7424844088769881904946675138821883803691306482783435629861981247919891501008432209601571930967896717000208047404844157111697538831394782048850895209676441
9567889969140990153111041735553196499354637405935420495356034670796003521316530597282657390095946864528646841642029184799482156925366078100497143897321933
12475670854464610513408311113788811137936798640460517254654400047083018292118505138449679306187435692350712908595881585933326398403850803976426445329625267
6893760583690469510658843199382344210820960193045562569834491211667462083863527826238208898016546616998265527429196378495524792597864225021963528312406801
11521654164468614438626624545370284123636176364804192538064706693652929299668253881515627183979860860751095607335569667199782321634713034665058154664347081
7579422629936925242872669360526265853314205172546449812803377589775847075298833471076450277299070821254018330109402660577051089034052113517042752575911361
10924757262306942725209975488362309300178874109495115497907934569836250672993814727128289812932203732020981576385808717562957056131941474157148264148319621
7261679367369634345716408743778550839145178377314805258270070218165861232648419916190228146684720544975668006736473191932433509794570953182441731469072131
8587447458252384261231014102913740339127257490190460039712644422512440077570300132463972772736798975422681013195826570010778698114179195694718211960358857
8124957472189926840439938883819001474526533186781639565473538734685193924648770780296143703174443982516285618778484139257201749652808148884766173356901161
7597261932225725535293176576238986883831883790779264946787115448946457522834636728303304013192110473253863822779916303833383995011620900876131212857503749
6814926683121835835680921933702514772745918218136737470631765537925665955943787632633761125582618107158394864260209862482330706878762815702654292902122367
12063711716101954527271495240111694384000997737324196920238311067958943293175096045620048032111259174492707338916836083194785142647060630184976198501504669
13098190580108144466871394057515971908375085208949501500804859830106971503676362313244959689493975367614510950887288879049289841625929888404024272952319293
9227985887433132721838662504358923979086045707089230469980805079825595481581635687741151545527024521739984712290771557971982192782171318826417095799055327
7583180296730325141563431318207402525348198910691543720379371154323259816351023765302564878565485056650186328059719292747808125058321340763500688009076719
10099784040546404647039504714475977018846236048012257762753494302880293071650152955429321351259363637876377785642130016768824587329590425148800332888860831
11674378042023021888956598118801657383702278396767330712537963115910561582927154358897846621202009260388132772831232028186124410764854354090880152752907861
9895849256167082219159489175714767223096557510130414626339881706836022730254378004966210786520625812174315572590619360927776640221693714672875956249894829
11310620291335013563182015820711536673442252267448246301161380030934012024939640014115483187153700913588270868550290764002612586855385539538405435650111877
11921077894874007769775186334266416538841744771105153769354498004281963823009746748966581041070955571034674977362655018342488079678555251613490488438325727
11388287183727969281417640117593580959600358193844960144489812652750896012523631930643778313542572422899375930454765295556897769082223443170115106213580319
7535519278719166968816359521006917589225092353587113666377601574655918821605512249359293342640534048061847432323773524405479278421876560930565066531843213
12175378980555940928458317933314121984421408716122068434065329474057807715648501091889088379502823110529153797781839175610416394566627241680366979727406473
9653966526164035306799150133627646042381944588246622275570722680175652899945520527153270650894943741535114329291873735263938477275599484872101283054512703
12120069341537952672890779035099139293131588078951465211189980010250112466264492207544892395219386981635716630151386811622719742578065542019886283772048411
11544932774744980847506070582270547280636986655775413008570062359137664877150853634854366034580300686043620683642468276604633589346616247532323275637289077
13146415374223882177733205137151282034410177086476448353540991019899325918489671515046601317646054844548156534021059138452879469141859939636095240824494179
12671814484221017946600349160954125928989977564888540951039407152098159786800166299051980771679984649580342998921636903097338570486632245185765242352098543
7797643798659242570687804415945798037334805113354550430894847038841627744728552634581477447698312795075652575327580859994139342436076050744623032656199473
12592539336025018516488315326281281283026268658962900880847576999966591321301215902836618756614781679712106714057926290530302746880870771727422622306215533
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2022/crypto/Shoo-in/chal.py | ctfs/niteCTF/2022/crypto/Shoo-in/chal.py | import gmpy2
import secrets as s
from flag import flag
fn = open(r"firstnames.py", 'r')
ln = open(r"lastnames.py", 'r')
fp = open (r"primes.py", 'r')
fn_content = fn.readlines()
ln_content = ln.readlines()
prime_arr = fp.readlines()
class RNG:
def __init__ (self, seed, a, b, p):
self.seed = seed
self.a = a
self.b = b
self.p = p
def gen(self):
out = self.seed
while True:
out = (self.a * out + self.b) % self.p
self.a += 1
self.b += 1
self.p += 1
yield out
def getPrime ():
prime = int(prime_arr[next(gen)].strip())
return prime
def generate_keys():
p = getPrime()
q = getPrime()
n = p*q
g = n+1
l = (p-1)*(q-1)
mu = gmpy2.invert(((p-1)*(q-1)), n)
return (n, g, l, mu)
def pallier_encrypt(key, msg, rand):
n_sqr = key[0]**2
return (pow(key[1], msg, n_sqr)*pow(rand, key[0], n_sqr) ) % n_sqr
N=(min(len(fn_content), len(ln_content)))
seed, a, b = s.randbelow(N), s.randbelow(N), s.randbelow(N)
lcg = RNG(seed, a, b, N)
gen=lcg.gen()
for i in range (0, 10):
if i==0:
name1 = fn_content[a].strip()+" "+ln_content[b].strip()
else:
name1 = fn_content[next(gen)].strip()+" "+ln_content[next(gen)].strip()
name2 = fn_content[next(gen)].strip()+" "+ln_content[next(gen)].strip()
print (f"{name1} vs {name2}")
winner=next(gen)%2
inp = int(input ("Choose the winner: 1 or 2\n"))
if (winner!=inp%2):
print ("Sorry, you lost :(")
break
else:
if (i<9):
print ("That's correct, here is the next round\n")
else:
print ("Congratulations! you made it")
print ("Can you decode this secret message?")
key=generate_keys()
print(pallier_encrypt(key, int.from_bytes(flag, "big"), next(gen)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2022/crypto/Shoo-in/firstnames.py | ctfs/niteCTF/2022/crypto/Shoo-in/firstnames.py | Tyrone
Zain
Gerald
Seamus
Matteo
Erick
Devin
Lucian
Vincent
Nikhil
Damion
Beckham
Emmanuel
Jesse
Bryant
Remington
Lorenzo
Benjamin
Gary
Elisha
Tomas
Rayan
Felipe
Marcos
Cesar
Xzavier
Darryl
Gianni
Jonas
Adan
Teagan
Owen
Jose
Ean
Kael
Ramon
Landon
Jaydin
Andres
Dustin
Brayden
Carlo
Tripp
Nathaniel
Jeremiah
Brett
Kyle
Preston
Marley
George
Leonardo
Efrain
Rogelio
Jamarion
Avery
Leo
Yair
Morgan
Marcus
Carter
Bentley
Dorian
Uriah
Case
Emilio
Blake
Cole
Kylan
Issac
Adrien
Maximus
Triston
Damien
Koen
Ayden
Weston
Skylar
Jairo
Tommy
Cornelius
Colby
Juan
Walker
Hezekiah
Bryce
Cedric
Jakobe
Xander
Terrance
Brendan
Pierce
Cyrus
Jensen
Levi
Kenny
Silas
Ian
Adonis
Jonathon
Antonio
Damian
Alan
Trevon
Davis
Calvin
Abdullah
Rodolfo
Skyler
Henry
Leonard
Mohamed
Cristofer
Rolando
Conor
Gael
Khalil
Carsen
Trent
Ben
Miles
Cael
Robert
Deegan
Zachary
Armando
Roberto
Savion
Soren
Mitchell
Jerry
Jadon
Andy
Ulises
Messiah
Landen
Marlon
Fabian
Lamar
Arturo
Trevor
Tyrese
Aedan
Luis
Erik
Alfonso
Seth
Mario
Ashton
Reece
Gerardo
Kaden
Cade
Sean
Ruben
Kingston
Jessie
Houston
Jovani
Romeo
Cameron
Darrell
Jermaine
David
Michael
Jason
Kian
Camryn
Cody
Hudson
Franklin
Alexis
Spencer
Victor
Rashad
Makhi
Keaton
Thomas
Brycen
Alex
Judah
Stanley
Jace
Sam
Keenan
Samuel
Kane
Noe
Amir
Eden
John
Ethan
Roland
Javion
Luka
Ernest
Dylan
Emiliano
Jeremy
Ty
Maximo
Reagan
Elliott
King
Aidyn
Kadyn
Talan
Branden
Broderick
Cory
Dario
Lance
Ismael
Kieran
Eddie
Zayne
Kolby
Declan
Edwin
Tucker
Landyn
Kenneth
Giovanni
Lee
Lawrence
Aarav
Jesus
Salvatore
Aryan
Camron
Todd
Lukas
Valentin
Darius
Lucas
Beau
Jameson
Santos
Shamar
Kendrick
Aidan
Kaleb
Simon
Adam
Johnathan
Tyree
Simeon
Chase
Ignacio
Solomon
Saul
Rhett
Davian
Logan
Moshe
Keyon
London
Giancarlo
Aaden
Grayson
Wayne
Rylee
Royce
Roy
Gaige
Kade
Drew
Aden
Eugene
Nigel
Tobias
Finley
Harry
Deandre
Jagger
Tony
Demetrius
Slade
Ricky
Mohammad
Guillermo
Gilbert
Mark
Ayaan
Tate
Kasen
Nikolas
Patrick
Derick
Donte
Rodrigo
Caiden
Deshawn
Reuben
Andrew
Deon
Jayvon
Ernesto
Clark
Ralph
Brenden
Ronan
Layne
Reid
Hunter
Abraham
Omari
Sebastian
Rishi
Octavio
Franco
Hassan
Elvis
Jaylon
Jonathan
Russell
Jon
Jordyn
Samson
Max
Braden
James
Adolfo
Alec
Adrian
Jeffery
Conner
Orlando
Antoine
Myles
Dominick
Bennett
Marcelo
Jaden
Jerome
Jayvion
Bobby
Dereon
Nathanial
Demarion
Adriel
Walter
Raul
Nicolas
Jaydan
Eduardo
Jorden
Dashawn
Javon
Ishaan
Ari
Amari
Randy
Pablo
Nico
Casey
Clayton
Jamie
Sammy
Alvin
Kamari
Brock
Justus
Isaiah
Jovany
Hector
Isiah
Corey
Maximillian
Ibrahim
Josh
Zachariah
Prince
Jaron
Chandler
Nelson
Maurice
Cale
Jaylen
Nathanael
Edward
Gideon
Lyric
Chad
Arnav
Ezra
Martin
Dexter
Kole
Alexzander
Junior
Kendall
Darion
Abdiel
Bailey
River
Nash
Christopher
Everett
Isaias
Clinton
Jean
Marshall
Jayce
Reed
Brodie
Bronson
Marquis
Ronin
Shane
Kaiden
Trevin
Mathew
Ramiro
Hamza
Ryan
Brenton
Dane
Shawn
Kelvin
Joshua
Allen
Brandon
Tristan
Kaeden
Pranav
Sergio
Colt
Jonah
Rocco
Collin
Terry
Van
Rohan
Jaiden
Baron
Marc
Jerimiah
Konnor
Kameron
Moses
Luciano
Pierre
Marco
Chace
Lewis
Emanuel
Trace
Aditya
Drake
Quentin
Jaquan
Jovanny
Quinten
Kolten
Jacob
Nickolas
Braylon
Evan
Santino
Clarence
Vance
Talon
Tristian
Brent
Dwayne
Darwin
Leonel
Matthias
Ellis
Gordon
Dale
Quincy
Brennen
Frederick
Cristian
Matias
Alden
Oswaldo
Joaquin
Bryson
Gaven
Brice
Jake
Philip
Paul
Oliver
German
Hugo
Cortez
Cruz
Nathen
Terrence
Warren
Cannon
Kyan
Peyton
Braylen
Caden
Abram
Antwan
Alonso
Raiden
Yadiel
Jaxson
Carlos
Damarion
Francisco
Ronald
Anderson
Cooper
Stephen
Denzel
Fisher
Mike
Dominic
Donovan
Salvador
Howard
Cash
Jorge
Trey
Arjun
Kamren
Draven
Karson
Reynaldo
Gustavo
Malakai
Nikolai
Craig
Braeden
Brennan
Asher
Diego
Clay
Jared
Frank
Deangelo
Kamron
Wyatt
Wesley
Camren
Muhammad
Abel
Dominik
Julian
Rex
Izayah
Caleb
Raphael
Steven
Albert
Malachi
Joe
Davion
Devan
Ronnie
Roman
Davon
Alberto
Keon
Ace
Emmett
Porter
Kody
Gage
Keegan
Cordell
Cassius
Rhys
Fletcher
Zion
Boston
Jacoby
Sterling
Alejandro
Layton
Chaz
Zaiden
Vaughn
Tristin
Wade
Richard
Joseph
Brayan
Dayton
Braedon
Nehemiah
Cullen
Ezequiel
Noah
Aydan
Zachery
Rory
Devyn
Brendon
Kamden
Alonzo
Nolan
Urijah
Harrison
Misael
Santiago
Jaime
Timothy
Izaiah
Zechariah
Haiden
Ali
Jett
Rigoberto
Javier
Xavier
Nasir
Douglas
Geovanni
Kasey
Wilson
Isai
Giovani
Nicholas
Konner
Yosef
Alexander
Manuel
Malik
Yandel
Cayden
Samir
Ryder
Phillip
Jeramiah
Korbin
Dominique
Enrique
Asa
Paxton
Maximilian
Braiden
Duncan
Austin
Jadyn
Larry
Bo
Devon
Axel
Ahmad
Marquise
Oscar
Jamar
Colin
Armani
Isaac
Frankie
Turner
Jay
Emery
Yael
Alvaro
Kristian
Krish
Charlie
Brady
Alijah
Keagan
Gabriel
Willie
Melvin
Julius
Jabari
Tyler
Garrett
Ryland
Sullivan
Grant
Darren
Jaydon
Keith
Kenyon
Heath
Jayden
Makai
Elliot
Lincoln
Zane
Deacon
Derrick
Pedro
Riley
Rene
Dakota
Orion
Malaki
Emerson
Griffin
Kai
Yahir
Miguel
Zackary
Eric
Johnny
Maxwell
Jaidyn
Shaun
Corbin
Deven
Cristopher
Mauricio
Connor
Joel
Jude
Mohammed
Dawson
Jadiel
Francis
Ethen
Glenn
Donavan
Justice
Odin
Aldo
Karter
Kason
Hugh
Marcel
Ariel
Winston
Ray
Dax
Esteban
Jase
Aaron
Branson
Roger
Grady
Jack
Aydin
Landin
Killian
Tanner
Andre
Carson
Ivan
Valentino
Travis
Davin
Rylan
Humberto
Augustus
Mateo
Alfredo
Cohen
Felix
Waylon
Jaylan
Brogan
Dennis
Freddy
Ahmed
Justin
Camden
Kelton
Sheldon
Moises
Marvin
Kevin
Randall
Madden
Jamison
Yurem
Roderick
Luke
Harold
Chris
Sage
Jackson
Christian
Colten
Liam
Raymond
Toby
Darnell
Peter
Blaze
Charles
Aron
Mason
Maxim
Josiah
Joey
Jaxon
Jalen
Gunnar
Thaddeus
Bridger
Memphis
Marques
Anthony
Leland
Quinn
Desmond
Chance
Milton
Braxton
Harper
Nick
Osvaldo
Easton
Callum
Blaine
Ezekiel
Daniel
Fernando
Immanuel
Cason
Jamarcus
Carmelo
Agustin
Bernard
Markus
Jeffrey
Donald
Jordan
Gregory
Jamal
Jayson
Rodney
Jakob
Dillon
Julio
Nathan
Zander
Niko
Quintin
Maddox
Will
Zavier
Aiden
Edgar
Rowan
Coby
Theodore
Keshawn
Israel
Taylor
Kash
Zack
Maverick
Leon
Rafael
Zackery
Brody
Enzo
Tyshawn
Barrett
Neil
Graham
Omar
Julien
Kale
Tyrell
Amare
Jordon
Sincere
Greyson
Damari
Kymani
Jasper
Colton
Brian
August
Allan
Kristopher
Luca
Kyler
Trenton
Jamir
Reese
Harley
Sonny
Quinton
Sawyer
Kyson
Kareem
Sidney
Jovan
Lawson
Zaid
Jair
Ricardo
Ryker
Beckett
Leroy
Louis
Ross
Bradley
Dean
Andreas
Tyson
Jimmy
Byron
Reginald
Bruno
Hayden
Trystan
Coleman
Darien
Irvin
Bruce
Josue
Jefferson
Bradyn
Vicente
Zaire
Gavyn
Johan
Kobe
Giovanny
Terrell
Danny
Jaylin
Demarcus
Dallas
Lane
Troy
Lennon
Dante
Lamont
Eliezer
Steve
Damon
Kayden
Leonidas
Anton
Jovanni
Reilly
Darian
Rudy
Mathias
Dillan
Angel
Jaeden
Alessandro
Phoenix
Braydon
Noel
Kadin
Holden
Payton
William
Elijah
Micheal
Carl
Malcolm
Rey
Semaj
Atticus
Angelo
Antony
Gauge
Leandro
Finnegan
Alfred
Elian
Kellen
Titus
Eli
Jarrett
Milo
Brooks
Mekhi
Billy
Yusuf
Chaim
Bryan
Elias
Micah
Arthur
Finn
Jasiah
Jan
Johnathon
Gunner
Derek
Conrad
Jax
Addison
Scott
Tristen
Gilberto
Gavin
Dangelo
Parker
Jamari
Dalton
Kolton
Matthew
Zayden
Uriel
Curtis
Helen
Paris
Jaylene
Jenny
Elle
Kenna
Elyse
Tiara
Yaretzi
Amy
Felicity
Danielle
Izabelle
Jaida
Valentina
Kenzie
Nayeli
Nina
Janae
Deborah
Hallie
Tamia
Nylah
Tessa
Tess
Katelyn
Amari
Hayley
Penelope
Daisy
Lilian
Brenna
Mattie
Irene
Kinsley
Aylin
Braelyn
Fatima
Karlee
Salma
Rebekah
Belen
Julianna
Lillianna
Aileen
Yoselin
Skye
Marilyn
Caitlyn
Edith
Abbie
Kaylah
Sadie
Elaina
Jolie
Tiana
Emerson
Mckenzie
London
Nora
Baylee
Amelie
Keyla
Kate
Gabriella
Madalynn
Londyn
Arianna
Anna
Shyanne
Briana
Shaylee
Yasmine
Ariel
Cadence
Kiara
Mila
Raquel
Miley
Melany
Serena
Maliyah
Angel
Julissa
Cynthia
Ruby
Deanna
Meadow
Alayna
Monica
Shea
Maia
Paloma
Valery
Jaylyn
Krystal
Jaylynn
Shelby
Shania
Margaret
Journey
Briley
Brielle
Leanna
Shiloh
Giselle
Daniella
Mckenna
Ayana
Melody
Jamie
Daniela
Ally
Rowan
Alisha
Sasha
Khloe
Akira
Gina
Riya
Jazmin
Mariam
Alexa
Alexis
Lydia
Jaycee
Adalynn
Justine
Alice
Anaya
Kailyn
Elaine
Charity
Carly
Anastasia
Kaitlin
Cecelia
Giovanna
Tatum
Kayla
Julianne
Kendra
Mckayla
Jimena
Alaina
Melina
Nia
Jaylen
Lizeth
Vanessa
Alexandria
Reyna
Laci
Sierra
Annie
Sienna
Cristina
Faith
Adrienne
Megan
Abagail
Elena
Maren
Ella
Shyann
Kaydence
Nevaeh
Audrina
Ainsley
Georgia
Kaiya
Kristen
Skylar
Carolina
Noelle
Ruth
Reese
Luna
Jaelynn
Ashanti
Eleanor
Cloe
Elisa
Miya
Jacey
Kimberly
Gisselle
Beatrice
Hanna
Allison
Janessa
Keely
Maleah
Makayla
Annabel
Yasmin
Kaia
Karli
Josephine
Ayanna
Kristin
Emery
Violet
Jadyn
Savanna
Avery
Jacqueline
Abigail
Tatiana
Corinne
Ada
Harmony
Kaylyn
Gianna
Bailey
Aurora
Kailee
Marisol
Amina
Payton
Haylie
Mina
Kali
Kaliyah
Heaven
Diana
Macey
Jaden
Stephany
Yareli
Celeste
Isabella
Yaritza
Lauren
Camille
Michelle
Hannah
Kylie
Brynn
Ellie
Yamilet
Rachael
Esther
Campbell
Sherlyn
Kenley
Raelynn
Lorelei
Damaris
Lena
Kendal
Kyla
Carissa
Fernanda
Joanna
Anika
Neveah
Laylah
Micaela
Rihanna
Cindy
Taniya
Mackenzie
Victoria
Krista
Sylvia
Lily
Paulina
Elianna
Aimee
Jakayla
Leah
Bella
Lara
Diamond
Isabela
Natalie
Viviana
Yazmin
Mariah
Kiana
Laila
Imani
Lilly
Jordin
Desirae
Fiona
Meredith
Kathleen
Claudia
Caroline
Jaylah
Andrea
Selina
Bethany
April
Kathryn
Gia
Maddison
Xiomara
Brooklynn
Lexie
Gretchen
Raina
Jazlyn
Amelia
Haylee
Emily
Emmy
Sidney
Anabelle
Nyla
Lyric
Alannah
Shyla
Dakota
Madisyn
Mikaela
Kristina
Regina
Rylie
Mariela
Maya
Mylie
Essence
Angeline
Saige
Caylee
Jordan
Sage
Dalia
Giada
Finley
Amira
Joslyn
Skyler
Annika
Shayna
Sonia
Katelynn
Alison
Skyla
Ashleigh
Destiny
Aryanna
Marina
Mia
Tamara
Makena
Kelly
Samantha
Natalya
Athena
Michaela
Mylee
Allie
Monserrat
Maribel
Alia
Lexi
Cassandra
Esmeralda
Katrina
Emilia
Aliya
Janet
Kaley
Kaitlynn
Amaris
Isis
Karissa
Kaya
Jazlene
Dominique
Kamora
Jaliyah
Karly
Mary
Logan
Deja
Selah
Crystal
Kyra
Leticia
Kayley
Madilyn
Chanel
Selena
Janelle
Aryana
Alexia
Amiah
Angela
Meghan
Christine
Liana
Yuliana
Bridget
Arely
Madison
Harper
Evelyn
Sophie
Lucille
Nadia
Ivy
Myla
Lia
Anabella
Catalina
Shaniya
Kasey
Destinee
Danika
Abbey
Amiya
Kirsten
Alisson
Raven
Giana
Taliyah
Cherish
Jacquelyn
Kelsie
Ariella
Mercedes
Dayami
Jaslyn
Sarahi
Evangeline
Litzy
Nathalia
Kaelyn
Marely
Rhianna
Lailah
Alivia
Aaliyah
Marlee
Christina
Mayra
Magdalena
Clara
Rayna
Miranda
Mireya
Isla
Piper
Paisley
Audrey
Amaya
Alissa
Ava
Maggie
Haley
Elise
Kendall
Savanah
Ciara
Taryn
Lindsey
Martha
Nola
Tianna
Anya
Caitlin
Livia
Alejandra
Natalee
Halle
Patience
Zoe
Carlie
Iyana
Camila
Mara
Ashtyn
Princess
Brooke
Scarlett
Alina
Natasha
Karma
Paige
Dana
Marin
Kaylen
Marissa
Kamryn
Desiree
Valeria
Dixie
Aliza
Josie
Addyson
Layla
Charlize
Lea
Abril
Kassandra
Ayla
Amya
Frances
Zoie
Nathaly
Brylee
Marie
Zariah
Juliet
Elsie
Madilynn
Milagros
Zion
Alyssa
Autumn
Sabrina
Alyson
Lucy
Jaylin
Cassidy
Myah
Cara
Jennifer
Joyce
Nathalie
Camilla
Wendy
Mariana
Denise
Kinley
Karla
Libby
Francesca
Gillian
Helena
Lilah
Dulce
Mckinley
Gabriela
Lindsay
Janiyah
Anne
Kaila
Angelina
Adalyn
Linda
Stacy
Allyson
Kira
Azul
Tiffany
Anabel
Miriam
Taniyah
Courtney
Kyleigh
Stella
Cecilia
Shirley
Aubree
Emma
Kathy
Angie
Madyson
Carla
Carmen
Marlene
Aniya
Barbara
Hailey
Dahlia
Jaqueline
Reina
Susan
Noemi
Hadley
Savannah
Sanaa
Patricia
Lacey
Delilah
Ashlynn
Kallie
Aleah
Leslie
Talia
Bryanna
Karlie
Lesly
Amara
Charlotte
Jada
Leila
Veronica
Elliana
Saniyah
Yadira
Jordyn
Callie
Gabrielle
Marianna
Melissa
Erika
Aniyah
Emilee
Sophia
Eileen
Sandra
Arielle
Abigayle
Precious
Eliana
Jane
Grace
Stephanie
Ann
Emelia
Monique
Madelynn
Rylee
Rayne
Gracie
Lauryn
Kaylynn
Jewel
Carolyn
Chana
Brisa
Dania
Arabella
Carley
Morgan
Sydney
Amiyah
Lisa
Serenity
Holly
Sara
Aspen
Belinda
Kaylee
Abby
Simone
Jamya
Adeline
Cali
Melanie
Cristal
Luz
Lila
Alisa
Kiera
Dayana
Jayden
Norah
Carlee
Alana
Kaleigh
Tabitha
Amani
Teagan
Annabella
Kailey
Charlie
Ariana
Cierra
Jocelyn
Olivia
Saniya
Scarlet
Paola
Anahi
Miah
Mya
Bailee
Jazmine
Lina
Camryn
Leilani
Phoenix
Araceli
Zaria
Janiah
Denisse
Elizabeth
Itzel
Aubrie
Isabelle
Matilda
Joselyn
Jenna
Renee
Thalia
Erica
Rachel
Brenda
Jaidyn
Charlee
Kaylin
Kassidy
Amanda
Karsyn
Aubrey
Roselyn
Casey
Macie
Hillary
Samara
Kianna
Lillian
Marlie
Riley
Ashlyn
Nataly
Makenna
Alena
Ryan
Chaya
Tanya
Abbigail
Adriana
Kayden
Priscilla
Azaria
Ximena
Teresa
Alexus
Kelsey
Ansley
Addisyn
Adelaide
Ali
Tania
Presley
June
Amber
Lizbeth
Kiersten
Peyton
Breanna
Areli
Janiya
Alani
Hayden
Ryleigh
Angelica
Mikayla
Giuliana
Makaila
Guadalupe
Kennedy
Gloria
Molly
Mariyah
Jamiya
Tori
Eliza
Iliana
Carina
Larissa
Zara
Maria
Lillie
Cassie
Lucia
Ana
Asia
Jade
Rose
Cameron
Olive
Aria
Justice
Rosemary
Danica
Adyson
Kamila
Mollie
Gemma
Lyla
Heidi
Parker
Emilie
Zaniyah
Lola
Mira
Katherine
Elsa
Eden
America
Willow
Rubi
Valerie
Cailyn
Lilia
Juliette
Jaiden
Julie
Iris
Cheyanne
Trinity
Daphne
Genesis
Katie
Addison
Vivian
Leia
Liberty
Shannon
Jasmin
Nicole
Armani
Hailee
Kara
Joy
Ashley
Emmalee
Sharon
Malia
Britney
Claire
Maryjane
Eve
Ashly
Eva
Diya
Nyasia
Brianna
Alma
Kimora
Kiley
Delaney
Sarah
Yesenia
Reagan
Rebecca
Whitney
Allisson
Liliana
Ellen
Madalyn
Lorelai
Jocelynn
Perla
Annalise
Celia
Taylor
Mallory
Genevieve
Tia
Judith
Lorena
Adelyn
Aliyah
Frida
Madeleine
Evelin
Evie
Alicia
Aiyana
Sofia
Dayanara
Kayleigh
Tara
Aleena
Alessandra
Maritza
Brynlee
Karen
Jessie
Kierra
Summer
Kaylie
Zoey
Haven
Ryann
Siena
Nancy
India
Phoebe
Mareli
Kylee
Erin
Cheyenne
Chelsea
Raegan
Keira
Virginia
Carleigh
Jaslene
Averie
Jazlynn
Kaitlyn
Harley
Kamari
Naima
Clare
Angelique
Jessica
Ireland
Macy
Emely
Jaylee
Chloe
Hazel
Gracelyn
Jazmyn
Jillian
Annabelle
Quinn
Aliana
Ingrid
Izabella
Esperanza
Catherine
Lilyana
Heidy
Gwendolyn
Naomi
Elisabeth
Jaelyn
Lilliana
Sarai
Johanna
Ashlee
Shayla
Kennedi
Pamela
Theresa
Laura
Jasmine
Maci
Aracely
Madeline
Lilianna
Aisha
Kadence
Greta
Clarissa
Marley
Jayda
Lana
Isabell
Karley
Hadassah
Laurel
Leyla
Madelyn
Hailie
Adison
Karina
Paityn
Marisa
Isabel
Averi
Destiney
Maeve
Miracle
Sanai
Rory
Alexandra
Alondra
Estrella
Julia
Micah
Alyvia
Alanna
Jayla
Makenzie
Sydnee
Adrianna
Lainey
Regan
Brooklyn
Cora
Moriah
Bianca
Avah
Haleigh
Jayleen
Heather
Amirah
Danna
Bria
Luciana
Laney
Sariah
Juliana
Payten
Hope
Rosa
Paula
Donna
Natalia
Dylan
Brittany
Sloane
Hana
Chasity
Kenya | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2022/crypto/Shoo-in/lastnames.py | ctfs/niteCTF/2022/crypto/Shoo-in/lastnames.py | Foley
Simmons
Frazier
Beard
Guerrero
Mooney
Hoover
Rojas
Ritter
Stevens
Mercado
Mccall
Austin
Raymond
Wyatt
Wilcox
Barr
Wood
Buckley
Santiago
Greer
Fleming
Richardson
Craig
Kaufman
Cherry
Solomon
Hampton
Cobb
Blair
Campbell
Hebert
Hanson
Wolf
Mckenzie
Frank
Leach
Schmidt
Madden
Robles
Valentine
Keith
Costa
Bryan
Morgan
Robertson
Newton
Hartman
Bernard
Kent
Hawkins
Ibarra
Reid
Gill
Ray
Allison
Macias
Giles
Mills
Dickson
Moses
Horton
Salinas
Pena
Flowers
Myers
Shah
Spence
Haley
Berg
Mclean
Potts
Hull
Carlson
Levy
Bush
Pineda
Tran
Gregory
Villarreal
Vaughan
Fowler
Douglas
Bonilla
Durham
Dominguez
Holmes
Cisneros
Walker
Cunningham
Clark
Blackburn
Melton
Schroeder
Rios
Peck
Watts
Guzman
Sellers
Hunter
Bradley
Riley
Morris
Garza
Boyle
Campos
Bennett
Wilson
Beck
Meza
Buchanan
Braun
Osborn
Heath
Hardin
Rosario
Decker
Garrison
Ferrell
Hester
Medina
Farmer
Carney
Hammond
Hess
Walsh
Suarez
Howard
Camacho
Hines
Ware
Sparks
Williamson
Lamb
Schaefer
Schneider
Wagner
Norris
Ballard
Roman
Villanueva
Owen
Pace
Rush
Farley
Horne
Landry
Cruz
Sheppard
Mason
Mcpherson
Lynn
Combs
Butler
Pennington
Harper
Kidd
Sandoval
Fritz
Rangel
Conley
Hinton
Bowen
Porter
Caldwell
Trujillo
Joyce
Nelson
Hurst
Hopkins
Lucas
Odom
English
Knight
Garrett
Hickman
Galloway
Willis
Roberts
Mitchell
Donovan
Gardner
Weaver
Baldwin
Blake
Aguirre
Sims
Wilkins
Sharp
Wells
Olsen
Ford
Abbott
Carr
White
Mejia
Nunez
Hansen
Booker
Hernandez
Murray
Paul
Kirk
Callahan
Clarke
Parrish
Mccormick
Savage
Marquez
Soto
Marks
Ryan
Haney
Manning
Anthony
Larson
Cowan
Adams
Schultz
Santos
Mcguire
Arias
Curtis
Ward
Nixon
Sweeney
Fox
Cline
Dennis
Rodgers
Norton
Galvan
Walter
Gillespie
Jacobs
Everett
Reynolds
Obrien
Blevins
Roach
Pearson
Dyer
Williams
Morton
Glenn
Warner
Cummings
Rubio
Goodwin
Bailey
Warren
Rocha
Gilmore
Flynn
Yu
Burgess
Chase
Jefferson
Jarvis
Wall
Reeves
Hubbard
Singleton
Whitaker
Rivera
Henson
Herman
Arroyo
Steele
Mcgrath
Harding
Marshall
Chung
Pitts
York
Carter
Brandt
Livingston
Simon
Zamora
Dorsey
Mahoney
Contreras
Johnston
Richmond
Hahn
Huerta
Travis
Winters
Barrera
Mcneil
Lynch
Bryant
Mcintosh
Carson
Duran
Villa
Ortiz
Schwartz
Frye
Black
Cochran
Stevenson
Bradshaw
Walters
Matthews
Harrington
Hutchinson
Morrison
Dougherty
Mayo
Fuentes
Ball
Miller
Stephenson
Taylor
Fernandez
Bolton
Harmon
Atkinson
King
Moore
David
Jenkins
Cabrera
Thornton
Patton
Stein
Weber
Boyer
Yates
Estes
Preston
Hughes
Mckay
Parks
Mccoy
Phelps
Oneill
Torres
Ayers
Green
Perry
Mcconnell
Benitez
Moody
Russo
Ferguson
Bell
Kirby
Dunn
Clay
Griffin
Lam
Mullen
Arnold
Hanna
Wheeler
Nash
Stokes
Stanton
Collins
Strong
Barnes
Lawrence
Carey
Robbins
Ingram
Boone
Koch
Santana
Kane
Young
Wise
Vazquez
Woodward
Larsen
Brock
Ellison
Buck
Burke
Mckee
Murphy
Webster
Glass
Sullivan
Stafford
Cooke
Mccarthy
Burch
Huber
Navarro
Mullins
Velasquez
Duarte
Cross
Washington
Estrada
Bradford
Davies
Hogan
Dudley
Oneal
Zhang
Parker
Aguilar
Olson
Chapman
Duncan
Ortega
Fry
Harvey
Sawyer
Spears
Vargas
Fletcher
Barton
Norman
Vaughn
Ellis
Benjamin
Berry
Gray
Moyer
Melendez
Beltran
Hoffman
Reilly
Stanley
Mathews
Orozco
Yoder
Chan
Conner
Lowe
Wilkinson
Small
Tucker
Bean
Lindsey
Graves
Silva
Banks
Little
Diaz
Keller
Serrano
Castaneda
Hensley
Irwin
Harrison
Dawson
James
Dickerson
Leblanc
Velazquez
Tapia
Padilla
Palmer
Singh
Zuniga
Morales
Riggs
Peters
Gordon
Cantrell
Deleon
Brady
Grimes
Fisher
Mercer
Patterson
Alvarez
Barnett
Terrell
Hayes
Potter
Sampson
Duke
Mueller
Eaton
Reyes
Kemp
Rose
Shepherd
Montes
Mays
Wright
Pratt
Gomez
Reed
Duffy
Solis
Choi
Vasquez
Rivers
Baird
Gross
Snyder
Smith
Holt
Rowland
Strickland
Werner
Stone
Randolph
Haynes
Elliott
Daugherty
Avila
Compton
Ho
Cameron
Wong
Gallagher
Collier
Hatfield
Huynh
Cook
Macdonald
Crosby
Park
Hendrix
Tanner
Haas
Roth
Harrell
Ashley
Romero
Francis
Ramirez
Shields
Blanchard
Bates
Wallace
Randall
Anderson
Nichols
Gutierrez
Jones
Osborne
Good
Juarez
Nguyen
Lara
Humphrey
Maxwell
Bauer
Bentley
Townsend
Holland
Rice
Ochoa
Hamilton
Waller
Lutz
Mcdonald
Kline
Dean
Day
Kerr
Holder
Skinner
Mcclain
Chavez
Ross
Pollard
Mcmahon
Cervantes
Perez
Murillo
Wiggins
Shelton
Faulkner
Alvarado
Watkins
Ayala
Stuart
Castro
Lee
Joseph
Barajas
Owens
Petersen
Bullock
Khan
Sanford
Arellano
Cordova
Bray
Powell
Whitney
Nicholson
Richards
Clayton
Shannon
Finley
Atkins
Whitehead
Freeman
Dillon
Garcia
Velez
Vincent
Dixon
Baxter
Gallegos
Summers
Jacobson
Reese
Mora
Riddle
Hooper
Berger
Shea
Graham
Tyler
Chambers
Sanders
Krueger
Montoya
Church
Martinez
Roy
Sherman
Chandler
Phillips
Guerra
Mendez
Davis
Jimenez
Kaiser
George
Kelly
Byrd
Cannon
Hale
Kelley
Stewart
Martin
Barber
Wang
Waters
Gay
Hodges
Bridges
Foster
Wolfe
Rowe
Price
Downs
Moran
Bird
Charles
Huffman
Patel
Gibbs
Barron
Miles
Webb
Branch
Herring
Shaw
Hardy
Brown
Henry
Baker
Spencer
Mcfarland
Walton
Gonzalez
Davidson
Michael
Franklin
Mckinney
Figueroa
Gaines
Salas
Shepard
Cain
Saunders
Nolan
Hendricks
Avery
Mendoza
Ramos
Rhodes
Schmitt
Chang
Hobbs
Gilbert
Maddox
Erickson
Acosta
Archer
Brewer
Vance
Lozano
Pittman
Ali
Zavala
Oconnor
Bright
Acevedo
Cole
Mcbride
Mack
Patrick
Grant
Pacheco
Delacruz
Yang
Alexander
Shaffer
Kennedy
House
Colon
Chen
Miranda
Flores
Neal
Logan
Cardenas
Howell
Esparza
Fitzpatrick
Kim
Prince
Chaney
Mosley
Jennings
Andrade
Jensen
Vang
Lawson
Todd
Hodge
Long
Blankenship
Hill
Rogers
Doyle
Hicks
Gates
Casey
Crawford
Donaldson
Trevino
Wilkerson
Parsons
Mata
Zimmerman
Roberson
Moss
Bautista
Adkins
Blackwell
Floyd
Perkins
Calderon
Monroe
Swanson
Best
Escobar
Carroll
Huff
Cox
Hall
Evans
Rosales
Franco
Sanchez
Ponce
Goodman
Brooks
Mathis
Lang
Woods
Orr
Morse
Higgins
Davila
Andersen
Morrow
Valenzuela
Glover
Sutton
Curry
Simpson
Petty
Thomas
Maldonado
Greene
Leon
Novak
Fischer
Newman
Daniels
Moon
Dalton
Stark
Rasmussen
Calhoun
Turner
Oconnell
French
Lester
Ruiz
Carpenter
Coffey
Meyer
Hurley
Hood
Farrell
Frey
Levine
Mayer
Cohen
Welch
Castillo
Peterson
Mcdowell
Hudson
Underwood
Lopez
Bowman
Robinson
Barrett
Garner
Browning
Kramer
Terry
Lloyd
Christensen
Fuller
Montgomery
Knox
Gentry
Johns
Mccarty
Maynard
Henderson
Gonzales
Molina
Luna
Mccann
Krause
Love
Mcgee
Booth
Lambert
Wiley
Barry
Klein
Massey
Bowers
Rodriguez
Stout
Allen
Poole
Golden
Benson
Munoz
Friedman
Proctor
Hunt
Brennan
Case
Houston
Fields
Snow
Short
Huang
Ewing
Gibson
Conway
Hancock
Howe
Li
Marsh
Johnson
Mcdaniel
Bass
Cortez
Drake
Watson
Walls
Mclaughlin
Holloway
Liu
Burton
Thompson
Rivas
Weeks
Cooley
Mann
Conrad
Jackson
Lowery
Holden
Bishop
Carrillo
Griffith
West
Rollins
Mcmillan
Gould
Dunlap
Salazar
Pruitt
Burns
Bender
Stephens
Fitzgerald
Espinoza
Le
Pugh
Valencia
Pierce
Hays
Powers
Page
Malone
Richard
Lin
Villegas
Forbes
Herrera
Gamble
Wade
Horn
Hart
Woodard
Lyons
Sexton
Odonnell
Tate
Mccullough
Russell
Knapp
Wu
Boyd
Lucero
Barker
Weiss
Jordan
Middleton
Rich
Pope
Dodson
May
Andrews
Valdez
Armstrong
Mcknight
Edwards
Scott
Coleman
Meyers
Nielsen
Delgado
Mcclure
Mcintyre
Sloan
Cuevas
Bond
Meadows
Crane
Noble
Cantu
Leonard
Briggs
Lane
Quinn
Benton
Burnett
Sosa
Vega
Bartlett
Oliver
Davenport
Pham
Frost
Copeland
Bruce
Daniel
Payne
Hayden
Key
Becker
Harris
Cooper
Clements
Ramsey
Merritt
Lewis
Beasley
Moreno
Christian
Frederick
Anise
Juan
Susannah
Claudia
Julina
Dex
Robin
Conrad
Hyrum
Trey
Emerson
Vincent
Jeremy
Silvia
Merle
Bree
Jax
Coralie
Rayleen
Kae
Elodie
Michael
Troy
Verena
Irene
Neil
Anneliese
Clelia
Kathryn
Drew
Arden
Ricardo
Sullivan
Preston
Ray
Charles
Arthur
Brooke
Louis
Justin
Hollyn
Jordon
Finn
Lawrence
Evony
Madeleine
Jacklyn
Ashten
Lydon
Payten
Jae
Gillian
Oren
Garrison
Julian
Edward
Lane
Jolee
Zoe
Aaron
Raven
Aryn
Caleb
Tyson
Olive
Matteo
Apollo
Oscar
Joanna
Carmden
Noah
Will
Korin
Raine
Brock
Brandt
Robert
Shane
Brendon
Bailey
Georgina
Doran
Carelyn
Ryder
Abe
Lee
Amelia
Jasper
Haiden
Leo
Love
Elias
Erin
Joan
Justice
Murphy
Zion
Dawn
Drake
Dante
Krystan
Selene
Rory
Naomi
Noel
Juliet
Gavin
Natalie
Harrison
Anthony
Zachary
Ellory
Reese
Wade
Lane
Julian
Kaitlin
Everett
Vanessa
Carlen
Marguerite
Evelyn
Madisen
Monteen
June
Annabel
Brighton
Vivian
Lynn
Janetta
Timothy
Rylie
Cash
Blair
Emeline
Viola
Blake
Dustin
Fawn
Henry
Rebecca
Francis
Glenn
Lashon
Zane
Paul
Claude
Kalan
Eli
Beck
Blanche
Denise
Matilda
Cameron
Seth
Isaiah
Javan
Luke
Ellice
Taylore
Miranda
Harriet
Daniel
Quintin
Carleen
Kingston
Myron
Nicolas
Bianca
Annora
Caylen
Ellison
Rhett
Grey
Blake
Devon
Gwendolen
Ann
Miriam
Blaise
George
Aiden
Tobias
Josiah
William
Joseph
Dean
Berlynn
Marcella
Coy
Fern
Linnea
Gregory
Judd
Kai
Syllable
Felix
Hugh
Blayne
Kent
Tanner
Elijah
Dezi
Isaac
Warren
Eloise
Randall
Thomas
Adelaide
Sherleen
Damien
Rose
Xavier
Candice
Nevin
Adele
Dominick
Karilyn
Abigail
Sharon
Brett
Ace
Tristan
Alice
Lillian
Cody
Dash
Riley
Abraham
Taye
Imogen
Oliver
Kate
Allison
Reagan
Cerise
Amity
Denver
Mirabel
Jackson
Suzan
Jude
Varian
Jane
Debree
Sutton
Benjamin
Marcellus
David
Leonie
Trevor
Reeve
Coreen
Sheridan
Jaidyn
James
Tavian
Elein
Grant
Ocean
Naveen
Jack
Gabriel
Nadeen
Breean
Sophia
Louisa
Levi
Bailee
Vernon
Mae
Coralie
Malachi
Ellen
Orlando
Lee
Avery
Byron
Lilibeth
Porter
Damon
Sean
Caprice
Kylie
Caren
Rosalind
Clark
Bram
Chase
Heath
Lucinda
Clementine
Aryn
Jared
Rene
Sue
Hope
Bernice
Meaghan
Fernando | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2022/crypto/Basically_I_locked_up/new_encryption.py | ctfs/niteCTF/2022/crypto/Basically_I_locked_up/new_encryption.py |
def new_encryption(file_name, password):
with open(file_name, "rb") as f:
plaintext = f.read()
assert(len(password) == 8)
assert(b"HiDeteXT" in plaintext)
add_spice = lambda b: 0xff & ((b << 1) | (b >> 7))
ciphertext = bytearray(add_spice(c) ^ ord(password[i % len(password)]) for i, c in enumerate(plaintext))
with open(file_name + "_encrypted", "wb") as f:
f.write(ciphertext)
def new_decryption(file_name, password):
with open(file_name + "_encrypted", "rb") as f:
ciphertext = f.read()
remove_spice = lambda b: 0xff & ((b >> 1) | (b << 7))
plaintext = bytearray(remove_spice(c ^ ord(password[i % len(password)])) for i, c in enumerate(ciphertext))
with open(file_name + "_decrypted", "wb") as f:
f.write(plaintext)
password = REDACTED
new_encryption("Important", password)
new_decryption("Important", password)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/niteCTF/2022/crypto/curvAES/Encryption.py | ctfs/niteCTF/2022/crypto/curvAES/Encryption.py | from tinyec import registry
from Crypto.Cipher import AES
import hashlib, secrets, binascii
curve = registry.get_curve('0x630x750x720x760x650x200x690x730x200x620x720x610x690x6e0x700x6f0x6f0x6c0x500x320x350x360x720x31')
def To256bit(point):
algo = hashlib.sha256(int.to_bytes(point.x,32,'big'))
algo.update(int.to_bytes(point.y,32,'big'))
return algo.digest()
def encrypt_1(msg,secretKey):
Cipher1 = AES.new(secretKey,AES.MODE_GCM)
ciphertext,auth = Cipher1.encrypt_and_digest(msg)
print(ciphertext , Cipher1.nonce , auth)
return (ciphertext,Cipher1.nonce,auth)
def encrypt_2(msg,pubKey):
ctPK = secrets.randbelow(curve.field.n)
sharedKey = ctPK * pubKey
secretKey = To256bit(sharedKey)
ciphertext, nonce, auth = encrypt_1(msg, secretKey)
ctPubK = ctPK * curve.g
return (ciphertext, nonce, auth, PubKey)
privKey = 'Figure that out on your own :('
pubKey = privKey * curve.g
Encoded_message = encrypt_2(msg, pubKey)
encoded_message_details = {
'ciphertext': binascii.hexlify(),
'nonce': binascii.hexlify(),
'auth': binascii.hexlify(),
'PubKey': hex(??.x) + hex(??.y%2)[?:]
} | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TheOdyssey/2023/crypto/Anarkhia/enc.py | ctfs/TheOdyssey/2023/crypto/Anarkhia/enc.py | #!/usr/bin/python3
import random
from secret import flag
random.seed(''.join([str(random.randint(0x0, 0x9)) for i in range(random.randint(3, 6))]));theKey = [random.randint(0, 255) for i in range(len(flag))];theEnc = "".join([hex(((random.choice(theKey)) ^ ord(flag[i]))<<1) for i in range(len(flag))]);open('out.txt', 'w').write(theEnc) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TheOdyssey/2023/crypto/Astynomoi/chall.py | ctfs/TheOdyssey/2023/crypto/Astynomoi/chall.py | #!/usr/bin/env python3
from Crypto.Cipher import ARC4
import os
import gzip
import hashlib
SECRET = b"flag{REDACTED}"
assert len(SECRET) == 64
def compress(m):
return gzip.compress(m)
def package(plaintext):
KEY = os.urandom(32)
plaintext = bytes.fromhex(plaintext)
cipher = ARC4.new(KEY)
enc = cipher.encrypt(compress(plaintext + SECRET))
return enc.hex()
def banner():
print('==============================================')
print('You are connected to : Astynomoi Report Center')
print('==============================================')
def main():
banner()
while True:
try:
print('How can I help you with?')
print('1. Make report')
print('2. Verify report')
print('3. Exit')
u = input('>> ')
print('')
if u == "1":
print('Please type your report (in hex):')
m = input(">> ")
print(f"Here's your report: {package(m)}")
elif u == "2":
print("Please verify your signature before sending it.")
print("Signature:", hashlib.sha256(SECRET).hexdigest())
elif u == "3":
print('See ya!')
break
print('')
except:
print('Error! Exiting...')
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/TheOdyssey/2023/crypto/Thermopolium/chall.py | ctfs/TheOdyssey/2023/crypto/Thermopolium/chall.py | from random import getrandbits as grb
from Crypto.Util.number import getPrime as gp, isPrime as ip
FLAG = b"flag{REDACTED}"
class flavor:
def __init__(self, state, mod):
self.state = state
self.mod = mod
self.mult = grb(32)
self.inc = grb(32)
def gen(self):
self.state = ((self.state * self.mult + self.inc) % self.mod)
return self.state
def condiment(x):
while not ip(x):
x+=1
return x
def cook(m, x):
n = gp(64)
res = ""
for i in m:
res += hex(pow(i, 4, n) ^ x.gen())[2:] + "xx"
return res
def main():
print('====================================')
print('You are connected to : Αρχαία Γεύση ')
print(' Please make yourself at home ')
print('====================================')
while True:
try:
print('Food of the day:')
print('1. Cook flagga')
print('2. Cook your own menu')
print('3. Exit')
u = input('>> ')
print('')
if u == "1":#I wonder what will happen if i just use these values instead
ingredients = flavor(condiment(grb(64)), condiment(grb(64)))
print(f"Here's your food: {cook(FLAG, ingredients)}")
elif u == "2":
ingredients = flavor(gp(64), gp(64))
print('Menu:')
m = input(">> ").encode()
print(f"Here's your food: {cook(m, ingredients)}")
elif u == "3":
print('See ya!')
break
print('')
except:
print('Error! Exiting...')
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/SanDiego/2024/rev/Emojis/emoji.py | ctfs/SanDiego/2024/rev/Emojis/emoji.py | def main():
print("what do you think the key is?")
encrypted = '🙚🙒🙌🙭😌🙧🙬🙻🙠🙓😣🙯🙖🙺🙠🙖😡🙃🙭🙿🙩🙟😯🙮🙬🙸🙻🙦😨🙩🙽🙉🙻🙑😯🙥🙻🙳🙐🙓😿🙯🙽🙉🙣🙐😡🙹🙖🙤🙪🙞😿🙰🙨🙤🙐🙕😯🙨🙽🙳🙽🙊😷'
key = input()
plaintext = ''.join([chr(ord(c) ^ ord(key[i % len(key)])) for i, c in enumerate(encrypted)])
print("your decrypted text:", plaintext)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2024/crypto/Raccoon_Run/server.py | ctfs/SanDiego/2024/crypto/Raccoon_Run/server.py | import json
from time import time
import tornado
import tornado.websocket
import tornado.ioloop
import random
import asyncio
import os
from datetime import timedelta
import tornado.web
import tornado.gen
PORT = 8000
NUM_RACCOONS = 8
FINISH_LINE = 1000
TARGET_BET = 1000
STEP_TIME = 0.25 # in seconds
BETTING_TIME = 15 # in seconds
FLAG = os.environ["GZCTF_FLAG"]
active_betters = {}
connections = {}
connection_count = 0
game = None
class RaccoonRun:
def __init__(self):
self.raccoons = [0] * 8
self.finishers = []
self.can_bet = True
self.bet_end = 0
def step(self):
self.can_bet = False
random_int = random.getrandbits(32)
for i in range(NUM_RACCOONS):
self.raccoons[i] += (random_int >> (i * 4)) % 16
for (i, x) in enumerate(self.raccoons):
if x >= FINISH_LINE and i not in self.finishers:
self.finishers.append(i)
return (self.raccoons, self.finishers)
def game_over(self):
return len(self.finishers) >= NUM_RACCOONS
class Gambler:
def __init__(self, account=10):
self.account = account
self.guess = None
self.bet_amount = 0
def bet(self, guess, bet_amount):
if self.validate_bet(guess, bet_amount):
self.guess = guess
self.bet_amount = bet_amount
return True
else:
return False
def validate_bet(self, guess, bet_amount):
if (type(guess) is not list):
return False
if not all(type(x) is int for x in guess):
return False
if len(guess) != NUM_RACCOONS:
return False
if (type(bet_amount) is not int):
return False
if (bet_amount < 0 or bet_amount > self.account):
return False
return True
# updates amount of money in account after game is over and bet comes through
# and then return an boolean indicating whether you won/lost
def check_bet(self, game_instance):
if game_instance.finishers == self.guess:
self.account += self.bet_amount
return True
else:
self.account -= self.bet_amount
return False
def reset_bet(self):
self.guess = None
self.bet_amount = 0
def get_race_information(id):
return json.dumps({"type": "race_information", "can_bet": "true" if game.can_bet else "false", "raccoons": game.raccoons, "finishers": game.finishers, "account": active_betters[id].account})
class RRWebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
global game
global active_betters
global connections
global connection_count
self.better_id = connection_count
active_betters[self.better_id] = Gambler()
connections[self.better_id] = self
connection_count += 1
self.write_message(get_race_information(self.better_id))
if game.can_bet:
self.write_message(json.dumps({"type":"betting-starts","until":game.bet_end}))
def on_message(self, message):
try:
data = json.loads(message)
if "type" not in data:
self.write_message(json.dumps({"type": "response", "value": "invalid WebSockets message"}))
elif (data["type"] == "bet"):
if (game.can_bet):
if active_betters[self.better_id].bet(data["order"], data["amount"]):
self.write_message(json.dumps({"type": "response", "value": "bet successfully placed!"}))
else:
self.write_message(json.dumps({"type": "response", "value": "bet is invalid, failed to be placed"}))
else:
self.write_message(json.dumps({"type": "response", "value": "bet cannot be placed after the race starts, failed to be placed"}))
elif (data["type"] == "buy_flag"):
if (active_betters[self.better_id].account > TARGET_BET):
self.write_message(json.dumps({"type": "flag", "value": FLAG}))
elif (data["type"] == "state"):
self.write_message(json.dumps({"type": "response", "value": "bet" if game.can_bet else "race"}))
elif (data["type"] == "account"):
self.write_message(json.dumps({"type": "response", "value": active_betters[self.better_id].account}))
else:
self.write_message(json.dumps({"type": "response", "value": "invalid WebSockets message"}))
except json.JSONDecodeError:
self.write_message(json.dumps({"type": "response", "value": "invalid WebSockets message"}))
def on_close(self):
del active_betters[self.better_id]
del connections[self.better_id]
def game_loop():
global game
print("Raccoons", game.raccoons)
print("Finishers", game.finishers)
for (id, connection) in connections.items():
connection.write_message(get_race_information(id))
game.step()
if game.game_over():
print("Raccoons", game.raccoons)
print("Finishers", game.finishers)
for (id, connection) in connections.items():
connection.write_message(get_race_information(id))
connection.write_message(json.dumps({"type":"result", "value": game.finishers}))
for (id, x) in active_betters.items():
if x.guess != None:
win = x.check_bet(game)
connections[id].write_message(json.dumps({"type": "bet_status", "value": f"you {'won' if win else 'lost'} the bet, your account now has ${x.account}"}))
x.reset_bet()
else:
connections[id].write_message(json.dumps({"type": "bet_status", "value": f"you didn't place a bet, your account now has ${x.account}"}))
print("Every raccoon has finished the race.")
print(f"Starting new game! Leaving {BETTING_TIME} seconds for bets...")
game = RaccoonRun()
game.bet_end = time() + BETTING_TIME
for (id, connection) in connections.items():
connection.write_message(get_race_information(id))
connection.write_message(json.dumps({"type":"betting-starts","until":game.bet_end}))
tornado.ioloop.IOLoop.current().add_timeout(timedelta(seconds=BETTING_TIME), game_loop)
else:
tornado.ioloop.IOLoop.current().add_timeout(timedelta(seconds=STEP_TIME), game_loop)
if __name__ == "__main__":
tornado.ioloop.IOLoop.configure("tornado.platform.asyncio.AsyncIOLoop")
io_loop = tornado.ioloop.IOLoop.current()
asyncio.set_event_loop(io_loop.asyncio_loop)
game = RaccoonRun()
print(f"Starting new game! Leaving {BETTING_TIME} seconds for bets...")
game.bet_end = time() + BETTING_TIME
tornado.ioloop.IOLoop.current().add_timeout(timedelta(seconds=BETTING_TIME), game_loop)
application = tornado.web.Application([
(r"/ws", RRWebSocketHandler),
(r"/(.*)", tornado.web.StaticFileHandler, {"path": "./static", "default_filename": "index.html"})
])
application.listen(PORT)
io_loop.start() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/Rock_paper_scissors/client.py | ctfs/SanDiego/2023/crypto/Rock_paper_scissors/client.py | import hashlib, secrets, base64, sys
from pwnlib.tubes import remote
HOST = 'rps.sdc.tf'
PORT = 1337
def hash(m: bytes):
return hashlib.md5(m).digest()
r = remote.remote(HOST, PORT)
def send(msg: str) -> None:
r.sendline(msg.encode())
def send_data(msg: bytes) -> None:
r.sendline(base64.b64encode(msg))
def recv() -> str:
return r.recvline(keepends=False).decode()
def recv_command() -> 'tuple[str, str]':
cmd, arg = recv().split(maxsplit=1)
if cmd == '==': # skip proof-of-work if any
cmd, arg = recv().split(maxsplit=1)
return cmd, arg
def error(err: str):
print(f'Server error: {err}')
sys.exit(1)
def process_command():
cmd, arg = recv_command()
if cmd == 'ERROR':
error(arg)
elif cmd == 'MOVE':
print(f'Server move: {arg}')
elif cmd == 'VERDICT':
print(f'Server verdict: {arg}')
if arg == 'Client lost':
print('Game over!')
sys.exit(0)
elif cmd == 'FLAG':
print(f'You won the flag: {arg}')
sys.exit(0)
elif cmd == 'NEXT':
print('Your turn!')
else:
error(f'Unknown command: {cmd}')
process_command()
while True:
move = input('Input your move (R/P/S): ')
pad = secrets.token_bytes(16)
proof = move.encode() + pad
commitment = hash(proof)
send_data(commitment)
process_command()
send_data(proof)
process_command()
process_command()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/Rock_paper_scissors/server.py | ctfs/SanDiego/2023/crypto/Rock_paper_scissors/server.py | import base64
import hashlib
import secrets
import sys
import traceback
flag = open('flag.txt').read()
N_ATTEMPTS = 100
def hash(m: bytes):
return hashlib.md5(m).digest()
def command(cmd: str, arg: str):
print(cmd, arg)
def error(msg: str):
command('ERROR', msg)
sys.exit(1)
num = {'R': 0, 'P': 1, 'S': 2}
LOSE = 'Client lost'
def get_verdict(cm: str, sm: str):
nc = num[cm]
ns = num[sm]
if ns == (nc + 1) % 3:
return LOSE
elif ns == nc:
return 'Draw'
else:
return 'Client won'
try:
for i in range(N_ATTEMPTS):
command('NEXT', '_')
commit = base64.b64decode(input())
server_move = secrets.choice('RPS')
command('MOVE', server_move)
proof = base64.b64decode(input())
if len(proof) != 17:
error('Incorrect proof length')
if hash(proof) != commit:
error('Client has bad commitment')
client_move = chr(proof[0])
if client_move not in 'RPS':
error('Bad client move')
ver = get_verdict(client_move, server_move)
command('VERDICT', ver)
if ver == LOSE:
break
else:
command('FLAG', flag)
except Exception:
traceback.print_exc()
error('Exception')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/100-security-questions/questions.py | ctfs/SanDiego/2023/crypto/100-security-questions/questions.py | # questions taken from the IPIP personality test, which is in the public domain
questions = [
'I am afraid of many things.',
'I feel comfortable around people.',
'I love to daydream.',
'I trust what people say.',
'I handle tasks smoothly.',
'I get upset easily.',
'I enjoy being part of a group.',
'I see beauty in things that others might not notice.',
'I use flattery to get ahead.',
'I want everything to be "just right."',
'I am often down in the dumps.',
'I can talk others into doing things.',
'I am passionate about causes.',
'I love to help others.',
'I pay my bills on time.',
'I find it difficult to approach others.',
'I do a lot in my spare time.',
'I interested in many things.',
'I hate to seem pushy.',
'I turn plans into actions.',
'I do things i later regret.',
'I love action.',
'I have a rich vocabulary.',
'I consider myself an average person.',
'I start tasks right away.',
"I feel that i'm unable to deal with things.",
'I express childlike joy.',
'I believe that criminals should receive help rather than punishment.',
'I value cooperation over competition.',
'I stick to my chosen path.',
'I get stressed out easily.',
'I act comfortably with others.',
'I like to get lost in thought.',
'I believe that people are basically moral.',
'I am sure of my ground.',
'I am often in a bad mood.',
'I involve others in what i am doing.',
'I love flowers.',
'I use others for my own ends.',
'I love order and regularity.',
'I have a low opinion of myself.',
'I seek to influence others.',
'I enjoy examining myself and my life.',
'I am concerned about others.',
'I tell the truth.',
'I am afraid to draw attention to myself.',
'I can manage many things at the same time.',
'I like to begin new things.',
'I have a sharp tongue.',
'I plunge into tasks with all my heart.',
'I go on binges.',
'I enjoy being part of a loud crowd.',
'I can handle a lot of information.',
'I seldom toot my own horn.',
'I get to work at once.',
"I can't make up my mind.",
'I laugh my way through life.',
'I believe in one true religion.',
"I suffer from others' sorrows.",
'I jump into things without thinking.',
'I am afraid of many things.',
'I feel comfortable around people.',
'I love to daydream.',
'I trust what people say.',
'I handle tasks smoothly.',
'I get upset easily.',
'I enjoy being part of a group.',
'I see beauty in things that others might not notice.',
'I use flattery to get ahead.',
'I want everything to be "just right."',
'I am often down in the dumps.',
'I can talk others into doing things.',
'I am passionate about causes.',
'I love to help others.',
'I pay my bills on time.',
'I find it difficult to approach others.',
'I do a lot in my spare time.',
'I interested in many things.',
'I hate to seem pushy.',
'I turn plans into actions.',
'I do things i later regret.',
'I love action.',
'I have a rich vocabulary.',
'I consider myself an average person.',
'I start tasks right away.',
"I feel that i'm unable to deal with things.",
'I express childlike joy.',
'I believe that criminals should receive help rather than punishment.',
'I value cooperation over competition.',
'I stick to my chosen path.',
'I get stressed out easily.',
'I act comfortably with others.',
'I like to get lost in thought.',
'I believe that people are basically moral.',
'I am sure of my ground.',
'I am often in a bad mood.',
'I involve others in what i am doing.',
'I love flowers.',
'I use others for my own ends.',
'I love order and regularity.'
] | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/100-security-questions/client_lock.py | ctfs/SanDiego/2023/crypto/100-security-questions/client_lock.py | from KeyRecoveryScheme import KeyRecoveryScheme
from questions import questions
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import bcrypt
import json
import base64
from os import path
from sys import exit
from client_unlock import get_db_entry
def main():
print("Welcome to the password recovery wizard!")
username = input("Enter the username you want to save the password for: ")
entry = get_db_entry(username)
if (entry != None):
print("There already exists an entry in the password database with the same username.")
answer = input("Do you wish to proceed? The old entry will be replaced (Y/N): ")
if (answer.lower() != "y"):
print("Aborting.")
exit()
password = input("Enter the password you want to recover later on: ") # the password is the flag
print("Next, you will have to answer a series of 100 questions. For each question, answer either 'true' or 'false' (all lowercase).")
print("We will begin the questions now.")
print()
answers = []
for i in range(len(questions)):
ans = str(input(questions[i] + " "))
answers.append((i + 1, ans)) # (i + 1) because the question # is 1-indexed
krs = KeyRecoveryScheme(90, 100)
(aes_key, lock) = krs.Lock(answers)
aes_cipher = AES.new(aes_key, AES.MODE_ECB)
encrypted_password = aes_cipher.encrypt(pad(password.encode(), 16))
password_bcrypt = bcrypt(password, 12)
if (not path.isfile("data.json")):
with open("data.json", "w") as json_file:
json_file.write("[]")
with open("data.json") as json_file:
password_database = json.load(json_file)
new_entry = {
"username": username,
"encrypted_password": base64.b64encode(encrypted_password).decode(),
"lock": lock.decode(),
"password_bcrypt": password_bcrypt.decode()
}
if (entry == None):
password_database.append(new_entry)
else:
for i in range(len(password_database)):
if (password_database[i]["username"] == username):
password_database[i] = new_entry
break
with open("data.json", "w") as json_file:
json.dump(password_database, json_file, indent=4)
print("\nSaved the following parameters to data.json:")
print("--------------------------------------------------------------")
print(f"username = {username}")
print(f"encrypted_password = {base64.b64encode(encrypted_password).decode()}")
print(f"lock = {lock.decode()}")
print(f"password_bcrypt = {password_bcrypt.decode()}")
print("--------------------------------------------------------------")
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/SanDiego/2023/crypto/100-security-questions/KeyRecoveryScheme.py | ctfs/SanDiego/2023/crypto/100-security-questions/KeyRecoveryScheme.py | import hashlib
from fractions import Fraction
from Crypto.Random.random import randrange
from Crypto.Protocol.KDF import scrypt
from math import gcd
# this scheme is taken from a paper by Ellison, Hall, Milbert and Schneier
# titled "Protecting secret keys with personal entropy"
KEY_LENGTH = 16
p = 258641170704651026037450395747679449699 # picked as a safe prime, i.e. (p - 1) / 2 is also prime
class Cipher(): # It takes in an answer (encoded as (question #, answer)) as a key, and maps Z_n -> Z_n on a fixed key.
def __init__(self, share, n): # k is the share that is "derived" into an appropriate Pohlig-Hellman key
self.n = n # n should be prime, this function does not perform checks though
hasher = hashlib.sha256()
hasher.update(str(share).encode())
self.e = int(hasher.hexdigest(), 16) % (n - 1) # we make e fall into Z_m where m is the order of the group
while gcd(self.e, n - 1) != 1:
self.e += 1
self.d = pow(self.e, -1, n - 1)
def encrypt(self, M):
return pow(M, self.e, self.n)
def decrypt(self, C):
return pow(C, self.d, self.n)
def eval_polynomial(x, poly_coeff, n): # evaluate a polynomial on x over the field Z_n
result = 0
for i in range(len(poly_coeff)):
term = (poly_coeff[i] * pow(x, i, n)) % n
result = (result + term) % n
return result
def std_lagrange_coeff(i, x_lst, n): # get the ith standard Lagrange coefficient, under modulus n, where n is a prime (so order of group is (n - 1))
result = Fraction(1,1)
for j in range(len(x_lst)):
if (j == i): continue
result *= x_lst[j]
result *= pow(x_lst[j] - x_lst[i], -1, n)
return result
def h(j):
# referred to following URL to select parameters:
# https://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors
return scrypt(str(j), "", KEY_LENGTH, 1048576, 8, 1)
class KeyRecoveryScheme():
def __init__(self, k, n):
self.k = k
self.n = n
# answers are a list of tuples in the form (question #, answer string (NOT bytestring)). Note that the question # is 1-indexed.
def Lock(self, answers): # generate random 128-bit key to be used for AES, and also its locked counterpart.
assert(len(answers) == self.n)
poly_coeff = [randrange(p) for _ in range(self.k)] # generate random (k - 1) degree polynomial with coefficients in Z_p
s_i = [] # this is our lock, which contains all encrypted y-values for x = 1, 2, ..., n
for (j, a) in answers: # answers in form (1, "answer1"), (2, "answer2"), ...
y_val = eval_polynomial(j, poly_coeff, p) # evaluate polynomial on x = 1, 2, ..., n
s_i.append(Cipher((j, a), p).encrypt(y_val))
key = h(poly_coeff[0])
lock = ",".join(map(lambda x: str(x), s_i)).encode()
return (key, lock)
def Unlock(self, answers, lock):
assert(len(answers) >= self.k)
enc_y_lst = [int(x) for x in lock.decode().split(",")]
coordinates = []
for (j, t) in answers:
# note that the Cipher takes in the entire (question #, answer) tuple as the key, not just the answer.
coordinates.append((j, Cipher((j, t), p).decrypt(enc_y_lst[j - 1]))) # decrypt the y-values in the lock
assert(len(coordinates) == len(answers))
poly_0 = 0 # the evaluation of the polynomial at 0 (what we want to find)
# interpolate the polynomial to find its evaluation at x = 0, using Lagrange interpolation
x_lst = list(map(lambda x: x[0], coordinates))
for j in range(len(coordinates)):
lagrange_basis = (coordinates[j][1] * std_lagrange_coeff(j, x_lst, p)) % p
poly_0 = (poly_0 + lagrange_basis) % p
key = h(poly_0)
return key | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/100-security-questions/client_unlock.py | ctfs/SanDiego/2023/crypto/100-security-questions/client_unlock.py | from KeyRecoveryScheme import KeyRecoveryScheme
from questions import questions
from Crypto.Util.Padding import unpad
from Crypto.Protocol.KDF import bcrypt_check
from Crypto.Cipher import AES
import json
from sys import exit
import base64
def get_db_entry(username):
try:
with open("data.json") as json_file:
password_database = json.load(json_file)
for entry in password_database:
if (entry["username"] == username):
return entry
return None # if no match is found
except:
return None
def main():
print("Welcome to the password recovery wizard!")
username = input("Enter the username whose password you want to recover: ")
entry = get_db_entry(username)
if (entry == None):
print("Could not find username in database.")
exit()
encrypted_password = base64.b64decode(entry["encrypted_password"])
lock = entry["lock"].encode()
password_bcrypt = entry["password_bcrypt"].encode()
print("To recover your password, you will have to answer a series of questions. Answer either 'true' or 'false' (all lowercase).")
print("You only have to answer 90 of the 100 questions.")
print("To skip a question, simply hit Return without entering any input.")
print("We will begin the questions now.")
print()
answers = []
for i in range(len(questions)):
ans = str(input(questions[i] + " "))
if (ans == ""):
continue
answers.append((i + 1, ans)) # (i + 1) because the question # is 1-indexed
try:
krs = KeyRecoveryScheme(90, 100)
aes_key = krs.Unlock(answers, lock)
aes_cipher = AES.new(aes_key, AES.MODE_ECB)
password = unpad(aes_cipher.decrypt(encrypted_password), 16)
bcrypt_check(password, password_bcrypt)
print("Password recovery successful! Here is your password:")
print(password.decode())
except ValueError:
print("There was an error in unpadding.")
print("Password recovery failed.")
except AssertionError:
print(f"You need to answer at least 10 security questions to recover the password, but you only gave {len(answers)} answers.")
print("Password recovery failed.")
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/SanDiego/2023/crypto/12-security-questions/questions.py | ctfs/SanDiego/2023/crypto/12-security-questions/questions.py | questions = [
"What is your mother's maiden name?",
"What was the name of your first pet?",
"In which city were you born?",
"What's your favorite movie?",
"What's your second favorite movie?",
"What's your favorite song?",
"What's your second favorite song?",
"What was the first song you danced to?",
"What was your 8th-grade chemistry teacher's surname?",
"What was your 1st-grade English teacher's surname?",
"What was your 5th-grade Math teacher's surname?",
"What was the name of your childhood crush?"
] | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/12-security-questions/leak.py | ctfs/SanDiego/2023/crypto/12-security-questions/leak.py | # Psst!!!
# Using some of my 31337 OSINT 5ki11z I have been able to narrow down the answer to each question to 10 choices each.
# For each question, I have put down 10 of the possible answers, in a list.
leak = [
["thomas", "miku", "harris", "baltimore", "hipple", "ayer", "ashe", "arming", "acre", "beckinham"], # What is your mother's maiden name?
["russell", "tom", "jerry", "ashley", "johnny", "benjamin", "fred", "gerry", "dumbo", "sesame"], # What was the name of your first pet?
["san diego", "san jose", "sacramento", "san francisco", "new york city", "los angeles", "san bernandino", "trenton", "detroit", "columbus"], # In which city were you born?
["birdemic", "fateful findings", "the last airbender", "troll 2", "batman and robin", "fantastic four", "disaster movie", "manos", "catwoman", "secrets of dumbledore"], # What's your favorite movie?
["decision to leave", "oldboy", "memories of murder", "blade runner 2049", "puss in boots 2", "into the spider-verse", "blade runner", "mother", "parasite", "portrait of a lady on fire"], # What's your second favorite movie?
["barcarolle", "american boy", "gimme gimme gimme", "naatu naatu", "smells like teen spirit", "something in the way", "party in the usa", "thrift shop", "not afraid", "levels"],
["call me maybe", "fireflies", "polonaise-fantasie", "hey sister", "die for you", "blinding lights", "flowers", "painting pictures", "unstoppable", "in the air tonight"],
["plastic love", "earth angel", "johnny b goode", "canon in d", "the twist", "wake me up when september ends", "mr blue sky", "lake shore drive", "american idiot", "fare thee well"],
["meyer", "paxton", "stefansdottir", "phillips", "holland", "walker", "carr", "campbell", "dunn", "edwards"],
["armstrong", "porter", "riley", "morales", "stevenson", "ritter", "becker", "bryan", "delgado", "pham"],
["moyer", "soto", "zamora", "dean", "shah", "merritt", "walton", "klein", "mccormick", "buchanan"],
["bradley", "sarah", "anna", "cassandra", "henry", "thomas", "hatsune", "oscar", "chris", "veronica"],
]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/12-security-questions/client_lock.py | ctfs/SanDiego/2023/crypto/12-security-questions/client_lock.py | from KeyRecoveryScheme import KeyRecoveryScheme
from questions import questions
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import bcrypt
import json
import base64
from os import path
from sys import exit
from client_unlock import get_db_entry
def main():
print("Welcome to the password recovery wizard!")
username = input("Enter the username you want to save the password for: ")
entry = get_db_entry(username)
if (entry != None):
print("There already exists an entry in the password database with the same username.")
answer = input("Do you wish to proceed? The old entry will be replaced (Y/N): ")
if (answer.lower() != "y"):
print("Aborting.")
exit()
password = input("Enter the password you want to recover later on: ") # the password is the flag
print("Next, you will have to answer a series of 12 questions. The answers to these questions will be used to secure your password.")
print("We will begin the questions now.")
print()
answers = []
for i in range(len(questions)):
ans = str(input(questions[i] + " "))
answers.append((i + 1, ans)) # (i + 1) because the question # is 1-indexed
krs = KeyRecoveryScheme(10, 12)
(aes_key, lock) = krs.Lock(answers)
aes_cipher = AES.new(aes_key, AES.MODE_ECB)
encrypted_password = aes_cipher.encrypt(pad(password.encode(), 16))
password_bcrypt = bcrypt(password, 12)
if (not path.isfile("data.json")):
with open("data.json", "w") as json_file:
json_file.write("[]")
with open("data.json") as json_file:
password_database = json.load(json_file)
new_entry = {
"username": username,
"encrypted_password": base64.b64encode(encrypted_password).decode(),
"lock": lock.decode(),
"password_bcrypt": password_bcrypt.decode()
}
if (entry == None):
password_database.append(new_entry)
else:
for i in range(len(password_database)):
if (password_database[i]["username"] == username):
password_database[i] = new_entry
break
with open("data.json", "w") as json_file:
json.dump(password_database, json_file, indent=4)
print("\nSaved the following parameters to data.json:")
print("--------------------------------------------------------------")
print(f"username = {username}")
print(f"encrypted_password = {base64.b64encode(encrypted_password).decode()}")
print(f"lock = {lock.decode()}")
print(f"password_bcrypt = {password_bcrypt.decode()}")
print("--------------------------------------------------------------")
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/SanDiego/2023/crypto/12-security-questions/KeyRecoveryScheme.py | ctfs/SanDiego/2023/crypto/12-security-questions/KeyRecoveryScheme.py | import hashlib
from fractions import Fraction
from Crypto.Random.random import randrange
from Crypto.Protocol.KDF import scrypt
from math import gcd
# this scheme is taken from a paper by Ellison, Hall, Milbert and Schneier
# titled "Protecting secret keys with personal entropy"
KEY_LENGTH = 16
p = 258641170704651026037450395747679449699 # picked as a safe prime, i.e. (p - 1) / 2 is also prime
class Cipher(): # It takes in an answer (encoded as (question #, answer)) as a key, and maps Z_n -> Z_n on a fixed key.
def __init__(self, share, n): # k is the share that is "derived" into an appropriate Pohlig-Hellman key
self.n = n # n should be prime, this function does not perform checks though
hasher = hashlib.sha256()
hasher.update(str(share).encode())
self.e = int(hasher.hexdigest(), 16) % (n - 1) # we make e fall into Z_m where m is the order of the group
while gcd(self.e, n - 1) != 1:
self.e += 1
self.d = pow(self.e, -1, n - 1)
def encrypt(self, M):
return pow(M, self.e, self.n)
def decrypt(self, C):
return pow(C, self.d, self.n)
def eval_polynomial(x, poly_coeff, n): # evaluate a polynomial on x over the field Z_n
result = 0
for i in range(len(poly_coeff)):
term = (poly_coeff[i] * pow(x, i, n)) % n
result = (result + term) % n
return result
def std_lagrange_coeff(i, x_lst, n): # get the ith standard Lagrange coefficient, under modulus n, where n is a prime (so order of group is (n - 1))
result = Fraction(1,1)
for j in range(len(x_lst)):
if (j == i): continue
result *= x_lst[j]
result *= pow(x_lst[j] - x_lst[i], -1, n)
return result
def h(j):
# referred to following URL to select parameters:
# https://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors
return scrypt(str(j), "", KEY_LENGTH, 1048576, 8, 1)
class KeyRecoveryScheme():
def __init__(self, k, n):
self.k = k
self.n = n
# answers are a list of tuples in the form (question #, answer string (NOT bytestring)). Note that the question # is 1-indexed.
def Lock(self, answers): # generate random 128-bit key to be used for AES, and also its locked counterpart.
assert(len(answers) == self.n)
poly_coeff = [randrange(p) for _ in range(self.k)] # generate random (k - 1) degree polynomial with coefficients in Z_p
s_i = [] # this is our lock, which contains all encrypted y-values for x = 1, 2, ..., n
for (j, a) in answers: # answers in form (1, "answer1"), (2, "answer2"), ...
y_val = eval_polynomial(j, poly_coeff, p) # evaluate polynomial on x = 1, 2, ..., n
s_i.append(Cipher((j, a), p).encrypt(y_val))
key = h(poly_coeff[0])
lock = ",".join(map(lambda x: str(x), s_i)).encode()
return (key, lock)
def Unlock(self, answers, lock):
assert(len(answers) >= self.k)
enc_y_lst = [int(x) for x in lock.decode().split(",")]
coordinates = []
for (j, t) in answers:
# note that the Cipher takes in the entire (question #, answer) tuple as the key, not just the answer.
coordinates.append((j, Cipher((j, t), p).decrypt(enc_y_lst[j - 1]))) # decrypt the y-values in the lock
assert(len(coordinates) == len(answers))
poly_0 = 0 # the evaluation of the polynomial at 0 (what we want to find)
# interpolate the polynomial to find its evaluation at x = 0, using Lagrange interpolation
x_lst = list(map(lambda x: x[0], coordinates))
for j in range(len(coordinates)):
lagrange_basis = (coordinates[j][1] * std_lagrange_coeff(j, x_lst, p)) % p
poly_0 = (poly_0 + lagrange_basis) % p
key = h(poly_0)
return key | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/12-security-questions/client_unlock.py | ctfs/SanDiego/2023/crypto/12-security-questions/client_unlock.py | from KeyRecoveryScheme import KeyRecoveryScheme
from questions import questions
from Crypto.Util.Padding import unpad
from Crypto.Protocol.KDF import bcrypt_check
from Crypto.Cipher import AES
import json
from sys import exit
import base64
def get_db_entry(username):
with open("data.json") as json_file:
password_database = json.load(json_file)
for entry in password_database:
if (entry["username"] == username):
return entry
return None # if no match is found
def main():
print("Welcome to the password recovery wizard!")
username = input("Enter the username whose password you want to recover: ")
entry = get_db_entry(username)
if (entry == None):
print("Could not find username in database.")
exit()
encrypted_password = base64.b64decode(entry["encrypted_password"])
lock = entry["lock"].encode()
password_bcrypt = entry["password_bcrypt"].encode()
print("To recover your password, you will have to answer a series of questions.")
print("You only have to answer 10 of the 12 questions.")
print("To skip a question, simply hit Return without entering any input.")
print("We will begin the questions now.")
print()
answers = []
for i in range(len(questions)):
ans = str(input(questions[i] + " "))
if (ans == ""):
continue
answers.append((i + 1, ans)) # (i + 1) because the question # is 1-indexed
try:
krs = KeyRecoveryScheme(10, 12)
aes_key = krs.Unlock(answers, lock)
aes_cipher = AES.new(aes_key, AES.MODE_ECB)
password = unpad(aes_cipher.decrypt(encrypted_password), 16)
bcrypt_check(password, password_bcrypt)
print("Password recovery successful! Here is your password:")
print(password.decode())
except ValueError:
print("There was an error in unpadding.")
print("Password recovery failed.")
except AssertionError:
print(f"You need to answer at least 10 security questions to recover the password, but you only gave {len(answers)} answers.")
print("Password recovery failed.")
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/SanDiego/2023/crypto/Jumbled_snake/jumble.py | ctfs/SanDiego/2023/crypto/Jumbled_snake/jumble.py | #! /usr/bin/env python3
# Need print_flag.py (secret) in the same directory as this file
import print_flag
import os
import secrets
import string
def get_rand_key(charset: str = string.printable):
chars_left = list(charset)
key = {}
for char in charset:
val = secrets.choice(chars_left)
chars_left.remove(val)
key[char] = val
assert not chars_left
return key
def subs(msg: str, key) -> str:
return ''.join(key[c] for c in msg)
with open(os.path.join(os.path.dirname(__file__), 'print_flag.py')) as src, open('print_flag.py.enc', 'w') as dst:
key = get_rand_key()
print(key)
doc = print_flag.decode_flag.__doc__
assert doc is not None and '\n' not in doc
dst.write(doc + '\n')
dst.write(subs(src.read(), key))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SanDiego/2023/crypto/Lake_of_Pseudo_Random_Fire/game.py | ctfs/SanDiego/2023/crypto/Lake_of_Pseudo_Random_Fire/game.py | #!/bin/python3
from Crypto.Cipher import AES
from os import urandom
import random
import binascii
flag = open("flag.txt", "rb").read()
class PRFGame:
def __init__(self, mode):
self.plaintext_ciphertext = {}
self.key = urandom(16)
# mode = 1 is pseudorandom, move = 0 is random
# one of the doors will be in the pseudorandom mode, and the other door will be in random mode
self.mode = mode
def pseudorandom(self, msg): # pseudorandom function
msg_comp = bytes(x ^ 0xff for x in msg) # bitwise complement of msg
cipher = AES.new(self.key, AES.MODE_ECB)
ciphertext = cipher.encrypt(msg) + cipher.decrypt(msg_comp) # concatenation of cipher.encrypt(msg) and cipher.decrypt(msg_comp)
return ciphertext
def random(self, msg):
# random oracle has consistency: if the same plaintext was given to the oracle twice,
# the random oracle will return the same ciphertext on both queries
if (msg in self.plaintext_ciphertext):
return self.plaintext_ciphertext[msg]
random_string = urandom(32)
self.plaintext_ciphertext[msg] = random_string
return random_string
def oracle(self, msg): # msg is a bytestring that is 16 bytes long
if (len(msg) != 16):
return None
if (self.mode == 0):
return self.random(msg)
else: # mode = 1 (pseudorandom oracle)
return self.pseudorandom(msg)
def guess(self, mode_guess):
return (self.mode == mode_guess)
doors = """
┌---------┐ ┌---------┐
| | | |
| | | |
| | | |
| O | | O |
| | | |
| | | |
└---------┘ └---------┘
"""
enter_dialog = "You enter a room. Inside the room are two doors. How do you proceed?"
options = """1 - Choose left door
2 - Choose right door
3 - Call on Orycull the High Priest
Enter a number: """
options_fail = "Invalid option."
left_dialog = "You walk through the left door..."
right_dialog = "You walk through the right door..."
fail_dialog = "Oh no! You fell straight into the Lake of Pseudo-Random Fire. Better luck next time!"
succeed_dialog = "Phew! You didn't walk into the Lake of Pseudo-Random Fire."
orycull_dialog = "Enter your incantation for Orycull to utter: "
orycull_error_dialog = "Sorry, Orycull only utters 16-byte incantations, in hexspeak."
orycull_response_dialog = """The left door sings: {left_response}
The right door sings: {right_response}"""
orycull_run_out_dialog = "Oh no! Orycull's voice broke! They can't talk anymore for the rest of the quest..."
orycull_remaining_dialog = "Orycull can still speak {n:d} more times."
rooms_remaining_dialog = "There are {n:d} rooms remaining. Onwards..."
win_dialog = """Magnificent! You have braved the 50 rooms. Unfortunately, to your chagrin, the Beacon of True Randomness is in another castle...
Oh well. Here's a consolation prize:"""
def orycull(messages_left, left_game, right_game):
while True:
if (messages_left == 0):
print(orycull_run_out_dialog)
continue
hex_message = input(orycull_dialog)
try:
message = binascii.unhexlify(hex_message)
except binascii.Error:
print(orycull_error_dialog)
continue
if (len(message) != 16):
print(orycull_error_dialog)
continue
left_response = binascii.hexlify(left_game.oracle(message)).decode("utf-8")
right_response = binascii.hexlify(right_game.oracle(message)).decode("utf-8")
print(orycull_response_dialog.format(left_response=left_response, right_response=right_response))
print(orycull_remaining_dialog.format(n=(messages_left - 1)))
return (messages_left - 1)
def main():
rooms = 50
messages_left = 100
while (rooms > 0):
correct_door = random.getrandbits(1) # 0 is left, 1 is right
if (correct_door == 0):
left_game = PRFGame(0) # make the left door emit truly random signals
right_game = PRFGame(1) # make the right door emit pseudorandom signals
else:
left_game = PRFGame(1) # make the left door emit pseudorandom signals
right_game = PRFGame(0) # make the right door emit truly random signals
print(doors)
print(enter_dialog)
while True:
decision = input(options)
match decision:
case "1": # left door
if (left_game.guess(0)):
print(succeed_dialog)
rooms -= 1
print(rooms_remaining_dialog.format(n=rooms))
break
else:
print(fail_dialog)
return
case "2": # right door
if (right_game.guess(0)):
print(succeed_dialog)
rooms -= 1
print(rooms_remaining_dialog.format(n=rooms))
break
else:
print(fail_dialog)
return
case "3": # Orycull
messages_left = orycull(messages_left, left_game, right_game)
case other:
print(options_fail)
print(win_dialog)
print(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/SanDiego/2023/crypto/SHA256-CTR/sha256ctr.py | ctfs/SanDiego/2023/crypto/SHA256-CTR/sha256ctr.py | import hashlib
from random import SystemRandom
import secrets
from time import sleep
FLAG = open('flag.txt', 'rb').read()
# In bits
INITIAL_CTR_SIZE = 256
SHA256_SIZE = 32
counter = secrets.randbelow(2 ** INITIAL_CTR_SIZE)
# print(hex(counter)) # DEBUG
print('Welcome to the demo playground for my unbreakable SHA256-CTR encryption scheme')
print('It is inspired by AES-CTR + SHA256, none of which has been shown to be breakable')
def next_key_block():
global counter
cb = counter.to_bytes((counter.bit_length() + 7) // 8, 'little')
counter += 1
# print('cb:', cb.hex()) # DEBUG
# print('key:', hashlib.sha256(cb).digest().hex()) # DEBUG
return hashlib.sha256(cb).digest()
sleep_time_gen = SystemRandom()
def rate_limit():
print('Thinking...')
sleep((1 + sleep_time_gen.random()) / 4)
def xor(sa: bytes, sb: bytes):
return bytes([a ^ b for a, b in zip(sa, sb)])
def encrypt(b: bytes) -> bytes:
return b''.join(xor(b[i:i+SHA256_SIZE], next_key_block()) for i in range(0,len(b),SHA256_SIZE))
while True:
print('Menu:')
print('1. Encrypt the flag')
print('2. Encrypt your own message')
print('3. Simulate encrypting N blocks')
print('4. Exit')
try:
choice = input('> ')
except EOFError:
print()
break
if choice == '1':
rate_limit()
print(f'Ciphertext in hex: {encrypt(FLAG).hex()}')
elif choice == '2':
hx = input('Enter your message in hex: ')
try:
msg = bytes.fromhex(hx)
except ValueError:
print('Invalid hex sequence')
continue
rate_limit()
print(f'Ciphertext in hex: {encrypt(msg).hex()}')
elif choice == '3':
# Developer note:
# Debug feature, should have zero impact on security
# since you can just do those N-block encryptions yourself using option 1 and 2, right?
try:
i = int(input('N = '))
except ValueError:
print('You must enter a valid integer')
continue
if i >= 0:
rate_limit()
counter = counter + i
else:
print('N must be non-negative')
elif choice == '4':
print('Come back when you can break the unbreakable.')
break
else:
print('Unknown option!') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2023/crypto/PicoChip_1/picochip.py | ctfs/Cryptoverse/2023/crypto/PicoChip_1/picochip.py | from itertools import groupby
from Crypto.Util.number import *
from enum import Enum
from base64 import b64encode
from secret import flag
import plotly.express as px
import random
class State(Enum):
# PicoChip power states for hardware simulation.
FALLBACK = 0x0
SUCCESS = 0x1
ERROR = 0x2
class PicoChip:
def __init__(self, k: int, N: int, t: int):
self.states = []
self.k = k
self.N = N
self.t = t
self.r = self.gen_op()
def rec(self, s: State):
self.states.append(s)
def gen_op(self) -> list:
rs = []
i = 3
while len(rs) < self.N:
if isPrime(i):
self.rec(State.SUCCESS)
rs.append(i)
i += 2
return rs
def gen_secure_prime(self) -> int:
# More secure than getPrime() as indicated from my latest paper.
while True:
v0 = random.randint(2**(self.k-1), 2**self.k)
v = v0 + 1 - v0 % 2
while True:
is_prime = True
i = 0
while i < self.N:
if v % self.r[i] == 0:
v = v + 2
self.rec(State.FALLBACK)
break
i += 1
self.rec(State.SUCCESS)
if i == self.N:
for m in range(1, self.t+1):
if not miller_rabin(v):
is_prime = False
v = v + 2
self.rec(State.FALLBACK)
break
self.rec(State.SUCCESS)
if is_prime:
return v
def plot(self):
# For transparency, I will show you the internals of PicoChip.
power_states(self.states)
def power_states(states: list):
if State.ERROR in states:
raise Exception("PicoChip is broken!")
power = []
for k, g in groupby(states):
if k != State.FALLBACK:
power.append(sum(1 for _ in g))
else:
power.extend([0 for _ in g])
gx, gy = [], []
for i in range(len(power)):
gx.append(i)
gy.append(power[i])
gx.append(i + 1)
gy.append(power[i])
fig = px.line(x=gx, y=gy, title="PicoChip Power States")
fig.write_html("power_states.html")
def miller_rabin(n: int) -> bool:
if n <= 1 or n == 4:
return False
if n <= 3:
return True
d = n - 1
while d % 2 == 0:
d //= 2
a = 2 + random.randint(1, n - 4)
x = pow(a, d, n)
if x == 1 or x == n - 1:
return True
while d != n-1:
x = (x * x) % n
d *= 2
if x == 1:
return False
if x == n - 1:
return True
return False
if __name__ == "__main__":
pico = PicoChip(36, 60, 1)
p = pico.gen_secure_prime()
q = pico.gen_secure_prime()
assert p != q and isPrime(p) and isPrime(q)
assert flag.startswith(b"cvctf{") and flag.endswith(b"}")
flag = flag[6:-1]
N = p * q
e = 0x10001
m = bytes_to_long(flag)
ct = pow(m, e, N)
print("[+] PicoChip Encryption Parameters:")
# print(f"N = {N}")
print(f"e = {e}")
print(f"ct = {ct}")
pico.plot()
print("[+] PicoChip Power States saved.") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2023/crypto/Fractional_Flag/fractional_flag.py | ctfs/Cryptoverse/2023/crypto/Fractional_Flag/fractional_flag.py | from Crypto.Util.number import getPrime, inverse, bytes_to_long
from secret import flag
assert len(flag) == 99
assert flag.startswith(b"cvctf{") and flag.endswith(b"}")
class MyRSA:
def __init__(self, n = 2, nbits = 512):
self.p = getPrime(nbits)
self.q = getPrime(nbits)
self.N = self.p * self.q
self.d = getPrime(nbits//2 - 1)
self.my_phi = self.gen_phi(n)
self.e = inverse(self.d, self.my_phi)
def gen_phi(self, n):
return sum([self.p**i for i in range(n)]) * sum([self.q**i for i in range(n)])
def encrypt(self, m):
print("I am not going to encrypt anything...")
return m
def get_public(self):
print(f"N = {self.N}")
print(f"e = {self.e}\n")
def get_private(self):
# print(f"d = {self.d}")
return self.d
NPARTS = 3
fractions = [bytes_to_long(flag[len(flag)//NPARTS*i:len(flag)//NPARTS*(i+1)]) for i in range(NPARTS)]
print("[+] Here are my public keys:")
ns = [2, 3, 6]
rsas = [MyRSA(n) for n in ns]
private_exponents = [rsa.get_private() for rsa in rsas]
for rsa in rsas:
rsa.get_public()
print("[+] Here are my flag fractions:")
for i in range(NPARTS):
f = sum(fractions[j] * private_exponents[i]**(NPARTS-1-j) for j in range(NPARTS))
print(f"[!] Fraction {i+1}: {f}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2023/crypto/Baby_AES/challenge.py | ctfs/Cryptoverse/2023/crypto/Baby_AES/challenge.py | from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from secret import flag
KEY_LEN = 2
BS = 16
key = pad(open("/dev/urandom","rb").read(KEY_LEN), BS)
iv = open("/dev/urandom","rb").read(BS)
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(flag, 16))
print(f"iv = {iv.hex()}")
print(f"ct = {ct.hex()}")
# Output:
# iv = 1df49bc50bc2432bd336b4609f2104f7
# ct = a40c6502436e3a21dd63c1553e4816967a75dfc0c7b90328f00af93f0094ed62 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2023/crypto/LFSR_Explorer/lfsr.py | ctfs/Cryptoverse/2023/crypto/LFSR_Explorer/lfsr.py | from Crypto.Util.number import *
from secret import flag
assert flag.startswith("cvctf{")
assert flag.endswith("}")
flag = flag[6:-1].encode()
assert len(flag) == 8
def explore(state, mask):
curr = (state << 1) & 0xffffffff
i = state & mask & 0xffffffff
last = 0
while i != 0:
last ^= (i & 1)
i >>= 1
curr ^= last
return (curr, last)
states = [bytes_to_long(flag[4:]), bytes_to_long(flag[:4])]
mask = 0b10000100010010001000100000010101
output = []
for i in range(8):
tmp = 0
for j in range(8):
(states[i // 4], out) = explore(states[i // 4], mask)
tmp = (tmp << 1) ^ out
output.append(tmp)
with open("output.txt", "wb") as f:
f.write(bytes(output))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2023/crypto/Knapsack_vs_Backpack/challenge.py | ctfs/Cryptoverse/2023/crypto/Knapsack_vs_Backpack/challenge.py | from Crypto.Util.number import *
from math import gcd
from secret import flag
import random
NBITS = 32
print("=== Knapsack vs. Backpack ===")
class Knapsack:
def __init__(self, nbits):
W, P = [], []
for _ in range(nbits):
W.append(random.randint(1, 10))
P.append(random.randint(1, 100))
self.W, self.P = W, P
def fill(self, nbits):
r = getRandomNBitInteger(nbits)
pt = [int(i) for i in bin(r)[2:].zfill(nbits)]
self.A = sum([x * y for x, y in zip(pt, self.W)])
self.B = sum([x * y for x, y in zip(pt, self.P)])
try:
for _ in range(10):
challenge1 = Knapsack(NBITS*4)
challenge1.fill(NBITS*4)
print(challenge1.W)
print(challenge1.P)
print(f"Knapsack Capacity: {challenge1.A}")
inp = list(map(int, input("Items: ").strip().split()))
for i in inp:
if i < 0 or i >= len(challenge1.W):
print("Nope.")
exit(1)
if len(inp) != len(set(inp)):
print("Nope.")
exit(1)
weight = sum([challenge1.W[i] for i in inp])
profit = sum([challenge1.P[i] for i in inp])
if weight <= challenge1.A and profit >= challenge1.B:
print("Correct!")
else:
print("Nope.")
exit(1)
except:
exit(1)
print(flag[:len(flag)//2])
class Backpack:
def __init__(self, nbits):
r = [42]
for _ in range(nbits - 1):
r.append(random.randint(2*r[-1], 4*r[-1]))
B = random.randint(3*r[-1] + 1, 4*r[-1])
A = random.randint(2*r[-1] + 1, B - 1)
while gcd(A, B) != 1:
A = random.randint(2*r[-1] + 1, B - 1)
self.M = [A * _ % B for _ in r]
def fill(self, inp):
return sum([x * y for x, y in zip(inp, self.M)])
try:
for _ in range(10):
challenge2 = Backpack(NBITS)
r = getRandomNBitInteger(NBITS)
pt = [int(i) for i in bin(r)[2:].zfill(NBITS)]
ct = challenge2.fill(pt)
print(challenge2.M)
print(f"In your Knapsack: {ct}")
inp = int(input("Secret: ").strip())
if inp == r:
print("Correct!")
else:
print("Nope.")
exit(1)
except:
exit(1)
print(flag[len(flag)//2:]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2023/crypto/PicoChip_2/picochip.py | ctfs/Cryptoverse/2023/crypto/PicoChip_2/picochip.py | from Crypto.Util.number import *
from enum import Enum
from base64 import b64encode
from secret import flag
import random
import csv
class State(Enum):
# PicoChip power states for hardware simulation.
FALLBACK = 0x0
SUCCESS = 0x1
ERROR = 0x2
class PicoChip:
def __init__(self, k: int, N: int, t: int):
self.states = []
self.k = k
self.N = N
self.t = t
self.r = self.gen_op()
def rec(self, s: State):
self.states.append(s)
def gen_op(self) -> list:
rs = []
i = 3
while len(rs) < self.N:
if isPrime(i):
self.rec(State.SUCCESS)
rs.append(i)
i += 2
return rs
def gen_secure_prime(self) -> int:
# More secure than getPrime() as indicated from my latest paper.
while True:
v0 = random.randint(2**(self.k-1), 2**self.k)
v = v0 + 1 - v0 % 2
while True:
is_prime = True
i = 0
while i < self.N:
if v % self.r[i] == 0:
v = v + 2
self.rec(State.FALLBACK)
break
i += 1
self.rec(State.SUCCESS)
if i == self.N:
for m in range(1, self.t+1):
if not miller_rabin(v):
is_prime = False
v = v + 2
self.rec(State.FALLBACK)
break
self.rec(State.SUCCESS)
if is_prime:
return v
def save(self):
# For transparency, I will show you the internals of PicoChip.
power_states(self.states)
def power_states(states: list):
if State.ERROR in states:
raise Exception("PicoChip is broken!")
states = [s.value for s in states]
fields = ['Time', 'Signal']
rows = [[i, s] for i, s in enumerate(states)]
with open('power_states.csv', 'w') as f:
write = csv.writer(f)
write.writerow(fields)
write.writerows(rows)
def miller_rabin(n: int) -> bool:
if n <= 1 or n == 4:
return False
if n <= 3:
return True
d = n - 1
while d % 2 == 0:
d //= 2
a = 2 + random.randint(1, n - 4)
x = pow(a, d, n)
if x == 1 or x == n - 1:
return True
while d != n-1:
x = (x * x) % n
d *= 2
if x == 1:
return False
if x == n - 1:
return True
return False
if __name__ == "__main__":
pico = PicoChip(512, 100, 10)
p = pico.gen_secure_prime()
q = pico.gen_secure_prime()
assert p != q and isPrime(p) and isPrime(q)
assert flag.startswith(b"cvctf{") and flag.endswith(b"}")
flag = flag[6:-1]
N = p * q
e = 0x10001
m = bytes_to_long(flag)
ct = pow(m, e, N)
print("[+] PicoChip Encryption Parameters:")
print(f"N = {N}")
print(f"e = {e}")
print(f"ct = {ct}")
pico.save()
print("[+] PicoChip Power States saved.") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2022/crypto/RSA2/chall.py | ctfs/Cryptoverse/2022/crypto/RSA2/chall.py | from Crypto.Util.number import inverse, bytes_to_long, getPrime, isPrime
from math import gcd
from secret import flag
PBITS = 512
e = 0x10001
def stage_one(data: bytes):
m = bytes_to_long(data)
p = getPrime(PBITS)
q = getPrime(PBITS)
b = 7
n = p**b * q
print(f"p = {p}")
print(f"e = {e}")
print(f"dp = {inverse(e, p-1)}")
print(f"b = {b}")
print(f"ct = {pow(m, e, n)}\n")
def stage_two(data: bytes):
m = bytes_to_long(data)
p = getPrime(PBITS)
q = p + 2
while not isPrime(q):
q += 2
n = p * q
print(f"n = {n}")
print(f"e = {e}")
print(f"ct = {pow(m, e, n)}\n")
print("=== Stage 1 ===")
stage_one(flag[:len(flag)//2])
print("=== Stage 2 ===")
stage_two(flag[len(flag)//2:]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2022/crypto/Weird_dlog/chall.py | ctfs/Cryptoverse/2022/crypto/Weird_dlog/chall.py | from Crypto.Util.number import *
from secret import flag
NBITS = 1337
def keygen():
p = getPrime(NBITS)
q = p + 2
while not isPrime(q):
q += 2
n = p**2 * q
g = getRandomRange(2, n-1)
assert pow(g, p-1, p**2) != 1
return (g, n), p
(g, n), pk = keygen()
print(f"g = {g}")
print(f"n = {n}")
m = pow(g, bytes_to_long(flag), n)
print(f"m = {m}")
'''
g = 4217104162231108571881486363264502722577265670533700464292447122725884060865278499273749984084307890296655750169737247120115556105852793495207776085190125693574834744150776071626953537124287733539294768576947214664831668249537361880607900415980188224790377848428124695064324868240382228326860781143717838988468681317873292597463247890454032395659378742623078198171614526987958808613568346779857292295096270767472963769637419908101399359189794634298434235861743414985078720538901239212554829307311050121532457033249775247040962157091404814597818322567791804549931512078619168741053536240553838132062889112375399237994189289540471931223835109201969517169907064471393467949637030171468739827679615037096191102556235525038398343624846458755117043899170432849676184565935742212246568515988089821245576219250167380483425498097448081250808144546318744227429556017907249040862683999049166654695785359522913386597444234975046933660020802696704230400762773828356573597488744036818115263470798266879540313464252075039418721353291327500707724679404373330401143441889215673146351039551079579127929035980199349135110483207097742313251638620757710743549095431313120163844541459241899262156308740654917968060844284412082299
n = 10941888529432710302272044808172366177817083267353728387778251966266072287607755644721338043351870432706497693313492403987246128369454049222700884094312120262698229189208223218732275272981771624419914106314134685967783268356547329406040929859316975902966386276320517786973713050654580905181729305020144204934138012268416005803949005810888621349553556279807338189673928133725107444318753299258813428869755492871371365509253274275507785302703028229706104025231495516828413453372697736689315270600144033367988185883751955533145131820299821036099425033741978037404521469840343451728996005273312522454265432166678945758946508086710070492821787815923425038513533610548985733666276895713644320042830406173577168099532687994444950160159745610177551080984478286003952657902953582221120083238221655231826293209922243103643973158229947410799996443039134812980230923730059957532891088920291921544489491437892953022797147371056895427933338596342279801238281297736043937512612367418666450917035364442328787819461040287010570790023067874699031894369374666073884261229547448186848837461040401572755725068306333093138881471721393682218994576974011413807781411295540237225784367274045480384276599164320452991405168935726178669
m = 4576653037171661542042510858542458890428902270240861216961609304805830644888835861552943484827465024255946333173438385318547946480432546672274379127945737050221711664915718037389483818788255371177342813451318183796063859501483853616124820170927827054719451326957465962519367227753007179628370407849940782754428678471956932743015842138996456351682565775528904950367274203264025982858945560085867807654673726775851728189907590054081432299552285929407918297497972515287529506153936873120705301250301755547851988767682706931104344998515759782906834209711055747621306735557847407025512085632112612715677993856157667539100717815505576125450494688023610882544096421409195218600313621491935755995519193153556491442386466162185336840903547990417011020008723119132837593921370224096091218428827263318876330392141114596260431968349229888104149062981625468823935145842920387345948673405002062554960084883553497321014737635984993337888457310522533554029754162393609118195463217899952617045335297738291366080224287861881668432617054485772999546446076931624127877484962146375663168327918511556849268478695380248447621861402820926977211453653005530269636900365390125831754366239971553991824331582315041274983141065725144997
''' | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2022/crypto/ATaleOfTwoSystems/challenge.py | ctfs/Cryptoverse/2022/crypto/ATaleOfTwoSystems/challenge.py | from Crypto.Util.number import *
from secret import flag
NBITS = 1024
def system_one(m: bytes):
a, b = [getRandomNBitInteger(NBITS) for _ in range(2)]
p = getPrime(2 * NBITS)
q = getPrime(NBITS // 2)
g = inverse(a, p) * q % p
ct = (b * g + bytes_to_long(m)) % p
print(f"p = {p}")
print(f"g = {g}")
print(f"ct = {ct}\n")
def system_two(m: bytes):
p, q = [getPrime(NBITS // 2) for _ in range(2)]
n = p * q
e = 0x10001
ct = pow(bytes_to_long(m), e, n)
print(f"n = {n}")
print(f"e = {e}")
print(f"ct = {ct}")
# what if q is reversed?
q = int('0b' + ''.join(reversed(bin(q)[2:])), 2)
hint = p + q - 2 * (p & q)
print(f"hint = {hint}")
def main():
print("When you combine two insecure systems, you get an insecure system. (Cryptoverse CTF, 2022)")
print("[+] System 1")
system_one(flag[:len(flag) // 2])
print("[+] System 2")
system_two(flag[len(flag) // 2:])
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/Cryptoverse/2022/crypto/BigRabin/chall.py | ctfs/Cryptoverse/2022/crypto/BigRabin/chall.py | from Crypto.Util.number import *
from secret import flag
import os, functools
primes = []
e = 2
for _ in range(10):
primes.append(getPrime(1024))
n = functools.reduce((lambda x, y: x * y), primes)
m = bytes_to_long(os.urandom(256) + flag)
c = pow(m,e,n)
print(primes)
print(c) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cryptoverse/2022/crypto/RSA3/server.py | ctfs/Cryptoverse/2022/crypto/RSA3/server.py | from Crypto.Util.number import *
import random
from secret import flag
es = [17, 19, 23, 29, 31, 63357]
e = random.choice(es)
p = getPrime(1024)
q = getPrime(1024)
n = p * q
m = bytes_to_long(flag)
c = pow(m, e, n)
if not random.randint(0, 10):
c = (1 << len(bin(c)[2:])) | c
print(f"n = {n}\ne = {e}\nc = {c}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Defcamp/2022/crypto/algorithm/chall.py | ctfs/Defcamp/2022/crypto/algorithm/chall.py | flag = ' [test]'
hflag = flag.encode('hex')
iflag = int(hflag[2:], 16)
def polinom(n, m):
i = 0
z = []
s = 0
while n > 0:
if n % 2 != 0:
z.append(2 - (n % 4))
else:
z.append(0)
n = (n - z[i])/2
i = i + 1
z = z[::-1]
l = len(z)
for i in range(0, l):
s += z[i] * m ** (l - 1 - i)
return s
i = 0
r = ''
while i < len(str(iflag)):
d = str(iflag)[i:i+2]
nf = polinom(int(d), 3)
r += str(nf)
i += 2
print r
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Defcamp/2022/crypto/beauty/beast.py | ctfs/Defcamp/2022/crypto/beauty/beast.py |
from beast_tls import *
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect(("127.0.0.1", 4444))
secret = all_requests("flag: CTF{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}")
found = ''.join(secret)
print "\n" + found
connection.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Defcamp/2022/crypto/P2DPI/server.py | ctfs/Defcamp/2022/crypto/P2DPI/server.py | from Crypto.PublicKey import ECC
from Crypto.Random import get_random_bytes
from Crypto.Random.random import randint
from blake3 import blake3
import base64 as b64
import traffic
import ecdsa
secure_message = traffic.get_msg()
sign_pub= None
with open('key.pub','rb') as f:
sign_pub=f.read()
ver=ecdsa.VerifyingKey.from_pem(sign_pub)
def int_to_bytes(x: int) -> bytes:
return x.to_bytes()
def bytes_to_int(xbytes: bytes) -> int:
return int.from_bytes(xbytes, 'big')
def H1(msg):
hasher = blake3()
hasher.update(b'Salty')
hasher.update(msg)
return hasher.digest()
def H2(c, msg):
hasher = blake3()
hasher.update(int.to_bytes(c,32,'big'))
hasher.update(msg)
return hasher.digest()
def tokenize(msg):
return [msg[i:i+8] for i in range(len(msg)-8)]
class ECC_G():
def __init__(self):
pass
def generate(self):
self.g = ECC.generate(curve='p256').pointQ
self.h = ECC.generate(curve='p256').pointQ
def get_public(self):
return (self.g,self.h)
class SR_Oracle():
def __init__(self,g,h):
self.g = g
self.h = h
self.k_sr = bytes_to_int(get_random_bytes(32))
def compute_intermediate_rule(self,Ri):
return Ri*self.k_sr
def compute_obfuscated_tokens(self,ti_list):
Ti_list=[]
c = randint(0,2**32)
for i in range(len(ti_list)):
encrypted = int_to_bytes(self._encrypt(ti_list[i]).x)
Ti_list.append(H2(c+i,encrypted))
return (c,Ti_list)
def _encrypt(self,msg):
return (g*bytes_to_int(H1(msg))+h)*self.k_sr
if __name__ == '__main__':
n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
RG = ECC_G()
RG.generate()
g,h = RG.get_public()
SR = SR_Oracle(g,h)
print("Hello MiddleBox. Here is my g and h:")
print(hex(g.x)[2:],hex(g.y)[2:])
print(hex(h.x)[2:],hex(h.y)[2:])
n = 157
n_traf = True
try:
while True:
print("Menu:")
print("1. Obfuscate rule (Will accept exactly "+str(n)+" more)")
print("2. Get traffic")
i = input().strip()
if i == '1':
n-=1
if n < 1:
exit()
R = input().strip()
Rinit = R.encode('utf-8') # 2lazy2compress
R = R.split(' ')
R = ECC.EccPoint(int(R[0],16),int(R[1],16))
sig = b64.b64decode(input().strip())
if R == g or R == h:
print("Rule entropy too small.")
exit()
if not ver.verify(sig,Rinit):
exit()
s1 = SR.compute_intermediate_rule(R)
print(hex(s1.x)[2:],hex(s1.y)[2:])
elif i == '2':
if n_traf:
n_traf = False
c,Ti=SR.compute_obfuscated_tokens(tokenize(secure_message))
print(str(c)+'|',end='')
print(b64.b64encode(b''.join(Ti)).decode('utf-8'))
else:
exit()
except:
exit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/pwn/icefox/deploy/wrapper.py | ctfs/KITCTFCTF/2023/pwn/icefox/deploy/wrapper.py | import base64
import binascii
from pwn import *
import sys
import os
def main():
try:
b64 = input("Base64 encoded file: ").strip()
except EOFError:
return
try:
js = base64.b64decode(b64)
except binascii.Error:
print("Invalid input", flush=True)
return
if len(js) >= 50000:
print("Invalid input", flush=True)
return
fn = os.urandom(16).hex()
fpath = f"attempts/{fn}"
with open(fpath, "wb") as f:
f.write(js)
f.seek(0)
try:
p = process(["./js", fpath])
p.interactive()
sys.stdout.flush()
except Exception as e:
print(e, flush=True)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/pwn/type_THIS/deploy/visit.py | ctfs/KITCTFCTF/2023/pwn/type_THIS/deploy/visit.py | import validators
import subprocess
import time
import os
WGET_TIMEOUT = 10
exploit_url = input("URL: ")
if not validators.url(exploit_url):
print("Invalid URL!")
exit(0)
try:
fn = os.urandom(16).hex()
fpath = f"attempts/{fn}"
is_reachable = subprocess.call(["wget", "-p", "-k", "-P", fpath, exploit_url],
stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, timeout=WGET_TIMEOUT) == 0
if not is_reachable:
print("Can't seem to reach that URL!")
exit(0)
except subprocess.TimeoutExpired:
print("Can't seem to reach that URL!")
exit(0)
print(f"Visiting URL...")
subprocess.call(["./chrome/chrome", "--no-sandbox", "--disable-gpu", "--headless", "--virtual-time-budget=60000", exploit_url],
stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/rev/sup3r5ecur3N0tPh15hyF11e/sup3r5ecur3N0tPh15hyF11e.exe.py | ctfs/KITCTFCTF/2023/rev/sup3r5ecur3N0tPh15hyF11e/sup3r5ecur3N0tPh15hyF11e.exe.py | import marshal
__name__ = __file__.split("/")[-1].encode()
f = lambda x: sum([coefs[i]*pow(x,i,7573) for i,_ in enumerate(coefs)]) % 7573
d = lambda f,n: [42,3][int(n)] if n<2 else int(f(f,n/2) +f(f,n/2))
coefs = [227,
5236,
4304,
6403,
3327,
6974,
1789,
6826,
4659,
785,
337,
6446,
7475,
445,
1128,
326,
703,
4348,
1496,
4275,
5956,
3385,
2707,
442,
4743,
1315,
3146,
5988,
5987,
6598,
4507,
3755,
1822,
6887,
3437,
7532,
7544,
7384,
4484,
2851,
5311,
1520,
2102,
1207,
2217,
5009,
2714,
234,
7095,
5001,
3105,
2199,
3286,
3760,
5882,
3903,
1475,
2947,
3051,
7279,
4603,
6496,
4109,
4559,
5003,
5739,
7171,
3071,
777,
1872,
1987,
2315,
5328,
1323,
4063,
1292,
4457,
220,
2846,
1877,
6084,
7546,
2657,
4587,
4559,
6286,
3691,
4970,
3730,
6493,
2210,
6347,
2204,
6036,
7183,
6259,
2335,
5414,
2073,
3501,
115,
863,
397,
137,
149,
3617,
1308,
1240,
5232,
4364,
4100,
6667,
4531,
7260,
4599,
1734,
3498,
4437,
7557,
6042,
4081,
7304,
4947,
3463,
439,
6627,
6228,
7247,
1340,
2435,
594,
2238,
6199,
3649,
3742,
3791,
455,
4599,
1843,
1130,
7492,
136,
4219,
4284,
6586,
2504,
3914,
4466,
4102,
2869,
896,
6732,
6926,
5160,
2914,
6790,
6270,
2554,
6544,
7184,
6474,
4914,
4712,
3466,
5582,
6776,
3576,
558,
3570,
5802,
2467,
3721,
4771,
7200,
1126,
1476,
6177,
2981,
2759,
6312,
3436,
3417,
6306,
4354,
7476,
938,
6820,
272,
556,
2113,
5252,
6003,
7379,
2157,
2092,
7473,
2732,
1957,
2034,
3364,
1261,
7558,
5448,
6755,
2390,
3608,
830,
7121,
6198,
5667,
5415,
6241,
2166,
6781,
1425,
1189,
6540,
2836,
3092,
226,
1279,
5648,
7028,
2979,
5729,
1353,
1768,
3872,
703,
2386,
5984,
2322,
6865,
3360,
1786,
4198,
2101,
6864,
6401,
3810,
3866,
2533,
6189,
6064,
4009,
6513,
5249,
4039,
4617,
4699,
34,
5198,
3867,
1431,
80,
6775,
1639,
5065,
5021,
4776,
2982,
343,
6954,
272,
3661,
2277,
732,
3983,
6485,
6213,
6275,
648,
6957,
6738,
5680,
4364,
4025,
1860,
5711,
7153,
1787,
7193,
5545,
2476,
3224,
5969,
6463,
6624,
2750,
5100,
5216,
1165,
7061,
7506,
2700,
2387,
4602,
819,
7471,
1403,
561,
6305,
5670,
5952,
6702,
3400,
6516,
7150,
7292,
5472,
6829,
5020,
7183,
7371,
3644,
5867,
1614,
6493,
5256,
3402,
6708,
4491,
2918,
4023,
3306,
1438,
1714,
7259,
5438,
3514,
4313,
1087,
5237,
6034,
4112,
543,
5806,
2594,
2750,
6954,
3521,
1526,
1121,
2094,
673,
1132,
2777,
2138,
5057,
5421,
745,
2708,
4070,
4758,
2452,
5687,
7208,
5192,
6194,
477,
3665,
5959,
2685,
4523,
6864,
5281,
4299,
2767,
161,
913,
2347,
1703,
6935,
3683,
1050,
2482,
4602,
598,
3792,
2099,
6246,
999,
1197,
96,
1021,
7215,
5112,
1661,
4246,
4375,
3191,
1105,
3315,
3600,
7436,
6124,
512,
2458,
3296,
1298,
3226,
5074,
1654,
3853,
461,
6216,
6041,
5603,
314,
6950,
7307,
5354,
6648,
3150,
1141,
3659,
391,
261,
129,
2040,
5305,
2617,
1510,
6089,
1004,
2925,
6243,
2018,
5579,
4546,
2801,
1937,
5658,
5670,
240,
5947,
5933,
4574,
2645,
309,
1666,
6238,
4428,
3053,
4083,
3585,
6275,
2419,
706,
1574,
6786,
5694,
1205,
2101,
3600,
2805,
4625,
3169,
3011,
1475,
1830,
3568,
952,
3268,
2604,
2947,
2427,
2596,
5343,
7345,
7315,
6697,
1472,
4542,
3447,
3113,
804,
3616,
1377,
2359,
4225,
6406,
5829,
2546,
4416,
630,
4197,
5175,
1778,
4060,
2133,
2058,
2603,
85,
66,
1674,
4812,
2454,
3825,
5389,
5057,
5388,
5156,
6961,
7066,
2201,
2699,
1963,
4641,
1472,
7291,
5717,
7146,
2500,
5187,
1191,
1630,
3102,
6283,
4351,
4199,
5225,
958,
3111,
3038,
1496,
6608,
1106,
6421,
1422,
5854,
6108,
7176,
6372,
2476,
636,
187,
2641,
6790,
3736,
260,
5834,
4902,
5478,
4593,
2525,
6121,
4235,
4173,
1780,
5308,
3747,
871,
1710,
5166,
648,
2689,
159,
6208,
5714,
4904,
3878,
778,
3451,
13,
4672,
768,
2819,
4127,
6613,
1739,
5323,
6566,
7353,
4370,
5922,
4254,
5954,
5207,
1052,
6370,
3338,
3372,
1594,
3005,
558,
1203,
3211,
3717,
235,
3614,
4544,
1974,
5139,
7086,
4543,
2917,
2094,
2299,
3664,
5145,
6425,
7270,
298,
544,
6532,
4871,
2350,
4134,
2294,
4644,
4052,
928,
6052,
1265,
5672,
280,
3233,
5523,
6285,
5621,
1003,
1089,
2693,
528,
4439,
1561,
5367,
4736,
3423,
999,
4950,
6307,
1570,
140,
699,
5407,
6897,
4939,
6947,
3929,
1908,
26,
4569,
298,
1937,
3544,
5056,
327,
2497,
4589,
3031,
2367,
2881,
1734,
4108,
1663,
6719,
4837,
998,
3763,
5516,
6934,
1909,
5985,
7472,
6690,
902,
2688,
2459,
6607,
2442,
2859,
3974,
24,
1823,
2663,
6366,
5133,
2224,
6423,
2120,
1901,
6516,
276,
6030,
1378,
6704,
198,
5766,
7135,
3249,
36,
743,
599,
4559,
1395,
3127,
3412,
6591,
816,
6243,
3536,
5325,
1396,
3986,
6733,
6756,
4265,
2087,
2680,
527,
4563,
5832,
349,
2084,
5384,
498,
2165,
893,
1503,
4381,
1241,
3020,
2335,
1271,
5343,
3259,
1569,
2702,
4170,
2491,
3069,
1228,
4325,
3061,
1148,
1325,
982,
6923,
77,
1181,
3447,
2561,
1662,
5434,
3157,
2795,
7183,
873,
5680,
7321,
6420,
5527,
7320,
902,
48,
6465,
2943,
4417,
3853,
81,
2948,
3467,
3090,
2983,
5591,
1002,
5998,
1223,
6646,
760,
3723,
6386,
6216,
5541,
1351,
5942,
5967,
2142,
5925,
2463,
4786,
418,
2313,
83,
6111,
3174,
5961,
4402,
7008,
488,
3244,
3116,
292,
3006,
1700,
6272,
7159,
5224,
2315,
1936,
6120,
5383,
3692,
6620,
1096,
4336,
2256,
2470,
1683,
7184,
5037,
6541,
7098,
1171,
1452,
6443,
287,
6938,
986,
4235,
1709,
6054,
6406,
2354,
6761,
1869,
5983,
2827,
2953,
1691,
5838,
6767,
3657,
4906,
835,
135,
7220,
895,
3681,
1449,
5525,
4712,
3664,
376,
2256,
934,
5884,
2221,
2405,
4956,
636,
1856,
4041,
5041,
104,
6620,
1292,
5006,
861,
5036,
5889,
1134,
6404,
7474,
1279,
5933,
1708,
1516,
5454,
6583,
6060,
6108,
4692,
3224,
4487,
4104,
1142,
3067,
2077,
5745,
5016,
2601,
3834,
1468,
3700,
2783,
2995,
189,
6367,
5715,
638,
5883,
6168,
6869,
4974,
6168,
1297,
6500,
7358,
1989,
4,
7333,
7276,
888,
4281,
1080,
5025,
3375,
3147,
6251,
168,
970,
5877,
6402,
6759,
2182,
324,
1811,
3641,
5632,
2109,
4448,
5362,
960,
4105,
2815,
6525,
6081,
1684,
4818,
1367,
2955,
2966,
3749,
1361,
6246,
6720,
2477,
4340,
272,
5057,
2555,
7005,
127,
6154,
4897,
1525,
2295,
7415,
5956,
5962,
780,
6479,
5294,
1766,
1302,
3495,
3471,
5333,
6198,
141,
3484,
3316,
4092,
6894,
5112,
5127,
2746,
2915,
7531,
6426,
328,
3938,
1298,
5311,
3679,
2555,
6546,
6988,
4356,
4085,
2593,
423,
1585,
2151,
1558,
3552,
1628,
2128,
3782,
4876,
5469,
253,
2583,
5462,
7331,
777,
5802,
6943,
5696,
3613,
524,
1194,
719,
5340,
217,
1210,
4709,
4754,
2485,
3256,
1244,
1316,
423,
188,
4526,
5414,
924,
4580,
2630,
5201,
4901,
6906,
3271,
1940,
1372,
7472,
1231,
6582,
5445,
5011,
190,
7278,
4753,
3787,
4269,
6825,
3622,
3899,
415,
7352,
4648,
2603,
651,
1405,
2861,
5945,
3413,
4702,
5479,
1403,
3136,
4679,
3838,
7381,
6497,
2319,
4623,
10,
5614,
6361,
76,
7255,
5284,
4148,
4026,
5900,
2834,
5652,
3459,
898,
6257,
2778,
2678,
4258,
4703,
6529,
6940,
3173,
3768,
2938,
1133,
7411,
7220,
6117,
6343,
2905,
1450,
6857,
2136,
5804,
3608,
5272,
2743,
1862,
5973,
5267,
9,
6181,
4663,
2934,
2612,
2665,
6606,
193,
6617,
4938,
2086,
2967,
5684,
810,
3771,
1900,
1108,
7428,
6207,
1503,
3881,
624,
5994,
7309,
6263,
2498,
1806,
4330,
7520,
5493,
2982,
6814,
2019,
937,
5881,
7149,
1138,
7545,
6394,
7307,
6930,
597,
2694,
5751,
2049,
2040,
6407,
1628,
6088,
4512,
181,
5136,
1395,
3178,
5983,
5590,
1539,
826,
7476,
5245,
2652,
163,
757,
5581,
2332,
4784,
1483,
2194,
257,
2322,
238,
6365,
4955,
5882,
6266,
6190,
4267,
44,
2459,
6727,
7267,
5737,
761,
5211,
4630,
2485,
4075,
7083,
813,
6981,
4019,
2694,
6566,
6847,
2341,
6054,
1671,
2705,
3571,
5214,
6098,
3035,
3635,
4237,
2441,
1856,
3882,
1755,
1867,
6972,
3497,
5617,
7047,
357,
6959,
3418,
1619,
7538,
6147,
132,
3650,
363,
4605,
3207,
4880,
4059,
2403,
7051,
5594,
426,
1417,
3591,
7549,
2539,
2358,
4239,
5023,
1992,
875,
5013,
5106,
5360,
8,
1615,
5421,
6331,
3765,
927,
6662,
2523,
4766,
4497,
4867,
5807,
5335,
4993,
3746,
2030,
6760,
6154,
890,
2332,
3288,
7429,
3380,
6051,
3145,
1158,
794,
3956,
1392,
5021,
6335,
6909,
4024,
4398,
2188,
3186,
798,
6948,
3200,
839,
2490,
2445,
2209,
5074,
7547,
1476,
4990,
1226,
5094,
3055,
6739,
7483,
922,
6707,
3439,
4556,
2743,
4319,
5657,
5305,
6611,
6646,
5719,
1162,
5461,
3467,
5897,
4072,
2415,
5784,
4500,
6447,
3913,
590,
3824,
6612,
1184,
5779,
2925,
5984,
4004,
3622,
6737,
5138,
5874,
309,
3707,
5023,
4767,
2857,
5900,
135,
597,
1476,
2117,
7013,
2927,
2139,
3717,
5682,
5018,
5430,
3136,
6483,
6734,
5884,
2851,
3737,
659,
2277,
450,
7262,
500,
3011,
4586,
2023,
3491,
4965,
3187,
6863,
2135,
6365,
7083,
7152,
6576,
6017,
4017,
5754,
4766,
6777,
2601,
884,
1145,
7399,
544,
5505,
1004,
4129,
6555,
7328,
6983,
6367,
6844,
3271,
457,
5428,
3301,
5279,
295,
256,
7016,
2898,
6178,
2404,
2584,
7408,
2814,
2181,
1584,
2243,
4021,
5285,
6251,
6856,
688,
4609,
1220,
4100,
2720,
3097,
4095,
7267,
3500,
696,
5818,
2040,
5002,
1752,
5666,
224,
229,
4217,
2466,
1085,
2035,
4363,
6300,
1603,
71,
892,
4135,
4052,
6629,
6038,
6664,
3518,
297,
4309,
4174,
2294,
6799,
95,
4701,
1223,
1332,
2195,
6831,
6678,
2605,
5977,
6690,
4821,
5657,
7122,
5079,
6697,
4073,
923,
854,
2181,
473,
3618,
6418,
6679,
124,
5943,
3096,
2566,
7442,
5496,
2430,
2396,
1021,
648,
4793,
2345,
2075,
2525,
7531,
110,
2041,
2693,
5519,
76,
4642,
2143,
5697,
696,
7167,
2107,
4658,
7132,
3632,
3663,
4634,
1814,
1733,
3928,
2597,
692,
1965,
111,
3013,
5207,
3107,
6578,
2102,
5241,
2304,
2583,
3686,
7376,
4869,
5260,
1028,
6252,
5858,
1299,
2959,
2439,
5511,
6936,
4530,
7014,
5104,
5226,
935,
6501,
2507,
5687,
106,
885,
6184,
1239,
4622,
4292,
4605,
1075,
5442,
4833,
6517,
2902,
699,
6507,
5515,
7135,
7011,
705,
583,
6532,
7009,
2080,
6777,
6050,
2458,
2928,
1305,
3293,
3940,
4741,
6393,
1932,
4346,
7126,
7456,
1308,
2088,
2218,
1460,
3084,
3807,
2185,
1239,
3517,
385,
660,
7043,
725,
3257,
6314,
6660,
4118,
5395,
6824,
1896,
5782,
7052,
7164,
3010,
1401,
2856,
573,
6878,
7094,
3796,
4198,
5943,
922,
5757,
2571,
6356,
2170,
7210,
116,
6846,
3117,
5239,
6950,
4591,
4275,
97,
5866,
636,
5090,
1128,
3960,
4633,
4076,
6543,
6655,
1518,
7042,
438,
2066,
1650,
4151,
5488,
4160,
2208,
841,
1452,
6174,
6179,
6844,
3510,
3483,
6178,
3051,
4846,
3883,
1272,
737,
3630,
6446,
4495,
146,
5029,
5114,
3901,
5401,
6130,
6799,
6003,
7236,
4403,
5402,
2812,
13,
5116,
3925,
7142,
5969,
4852,
336,
3657,
2024,
6863,
5129,
2983,
4183,
5086,
5335,
1675,
1368,
283,
5408,
3048,
5974,
1434,
6191,
3523,
5292,
4307,
953,
1422,
4409,
1250,
4625,
5835,
2676,
6305,
6068,
3077,
5771,
1573,
5873,
4102,
3202,
94,
6214,
291,
4434,
6265,
803,
6225,
5046,
1316,
6875,
2245,
3819,
6503,
5359,
5385,
7276,
6186,
301,
5876,
4948,
1464,
2028,
3104,
1375,
7442,
2402,
2082,
1436,
4466,
6861,
1777,
6840,
6920,
756,
5128,
2585,
3262,
5612,
4814,
4878,
3672,
4973,
6708,
3631,
83,
1024,
3478,
3474,
6443,
3054,
4095,
2279,
2084,
314,
6048,
2469,
6128,
5606,
7224,
1493,
2107,
3478,
4543,
3467,
2272,
5335,
2659,
7442,
5096,
6257,
2709,
4463,
6198,
2633,
1764,
3416,
5609,
6120,
1545,
2225,
743,
3359,
643,
6881,
1588,
3826,
5641,
7269,
4450,
98,
1457,
5162,
1593,
980,
5241,
2633,
4193,
5242,
4810,
1051,
2794,
6072,
452,
2484,
1649,
5359,
2261,
5913,
234,
409,
5509,
749,
240,
1802,
4530,
2065,
6219,
1294,
2007,
1808,
2582,
6563,
1744,
4051,
2061,
326,
681,
2673,
5117,
1450,
2953,
655,
6649,
2294,
7316,
1474,
3811,
1176,
1679,
2616,
425,
2379,
4882,
5348,
6558,
7187,
4653,
4081,
7312,
574,
3231,
2376,
4446,
431,
5529,
4683,
5746,
3049,
4105,
5074,
2914,
863,
4618,
1053,
4067,
2972,
1310,
3320,
5673,
4494,
1840,
6543,
3346,
5614,
1841,
3186,
4731,
1388,
533,
2168,
589,
5540,
326,
3547,
5314,
154,
2782,
4980,
109,
6295,
3572,
6495,
1850,
6283,
5597,
872,
7222,
4349,
1621,
6179,
1533,
5706,
1560,
3258,
3970,
6158,
677,
4220,
5306,
5266,
7248,
2036,
6123,
6960,
2810,
3951,
25,
2818,
1714,
1354,
6312,
3972,
7112,
2447,
3378,
482,
6699,
1845,
5289,
131,
5385,
7106,
5522,
1237,
4256,
1662,
6399,
1263,
4771,
4421,
7287,
7185,
1854,
6286,
2829,
5086,
4843,
1937,
4590,
6611,
7229,
1442,
6232,
1063,
79,
189,
3232,
4871,
4768,
7219,
1459,
3534,
7258,
4095,
833,
6172,
1191,
5259,
1832,
3942,
5909,
6899,
6209,
2113,
4830,
6074,
6515,
4521,
2099,
1,
5261,
5136,
1200,
3199,
615,
819,
1874,
3181,
2180,
6968,
3407,
3720,
2976,
1664,
6435,
6629,
578,
580,
1826,
4468,
4864,
2307,
2125,
6882,
1080,
3637,
1423,
3307,
6559,
1647,
5795,
4593,
4988,
192,
4723,
3258,
6627,
1024,
95,
2495,
2282,
1170,
1161,
6213,
4500,
1050,
4847,
3732,
5227,
1618,
5759,
893,
2688,
3812,
1144,
6965,
4026,
1143,
1219,
4724,
6195,
1688,
3661,
2642,
1928,
692,
4492,
1885,
18,
911,
4505,
1723,
4794,
3848,
4237,
5296,
3652,
1208,
592,
3035,
671,
1119,
7316,
6540,
1993,
1607,
3355,
5041,
7237,
4869,
5268,
2168,
7026,
3747,
5395,
825,
4958,
5360,
614,
5701,
363,
2962,
4855,
6385,
7375,
2613,
3973,
6485,
2747,
4294,
1784,
4763,
3049,
6386,
7018,
4297,
24,
4497,
4718,
2440,
4790,
6364,
2724,
7262,
1411,
5710,
5474,
6969,
807,
7201,
1652,
235,
3603,
6782,
1774,
5918,
916,
3724,
5824,
3891,
2505,
3676,
1627,
6132,
4918,
1797,
7193,
4306,
340,
2375,
6650,
4768,
2214,
5094,
1326,
358,
2213,
5051,
3551,
3441,
3359,
3481,
156,
4523,
5379,
7259,
7153,
5167,
5504,
4785,
2376,
3183,
6683,
539,
23,
7107,
3949,
5848,
6414,
4766,
7183,
5367,
2106,
5142,
7034,
110,
1534,
922,
5640,
4814,
821,
6533,
3229,
3237,
3606,
649,
7126,
4605,
2877,
5054,
650,
3274,
5626,
7135,
1162,
2572,
395,
6542,
2280,
4282,
920,
3704,
2154,
3618,
6516,
429,
3412,
4404,
5218,
3085,
2787,
2143,
2929,
1515,
852,
1560,
4751,
2074,
5978,
4875,
2099,
5682,
4504,
2691,
1532,
1260,
2939,
2854,
3793,
761,
1497,
4477,
6274,
1638,
2131,
2741,
7257,
5583,
3869,
966,
6238,
6336,
976,
7306,
4553,
3408,
1357,
4828,
6842,
1401,
2545,
4589,
4210,
2950,
4707,
5726,
5819,
5743,
1818,
7011,
5346,
6252,
6406,
7106,
1864,
3395,
3580,
2123,
989,
2994,
3771,
1091,
6781,
2267,
3039,
1354,
5621,
3386,
7525,
2420,
177,
1472,
4388,
3872,
7488,
3158,
3655,
5474,
6432,
121,
3653,
3813,
4851,
3360,
6381,
3590,
6587,
5024,
6481,
2049,
3619,
3406,
3417,
4271,
5939,
3678,
3538,
4952,
3568,
5912,
7128,
7017,
7511,
5678,
5512,
5871,
4721,
625,
6238,
1091,
7123,
2120,
4155,
2038,
4630,
1666,
5668,
6060,
2607,
6035,
2174,
7216,
7047,
839,
7152,
6940,
7355,
5293,
2948,
277,
5075,
400,
2232,
2251,
7304,
1819,
3156,
6536,
585,
5442,
5495,
2890,
394,
365,
7539,
4190,
3095,
4718,
3968,
5118,
2826,
6085,
4394,
2899,
825,
898,
5703,
2401,
788,
388,
7210,
803,
3696,
6777,
6100,
6858,
7029,
572,
4428,
527,
7461,
820,
4203,
386,
1790,
2278,
7183,
4328,
1807,
7446,
4301,
2908,
4790,
2479,
1863,
2491,
1602,
3532,
6228,
1900,
2550,
4880,
5789,
5648,
461,
2796,
30,
4976,
4851,
5952,
7065,
2931,
7116,
1122,
25,
5116,
5957,
6928,
931,
524,
1956,
7136,
2215,
6496,
4166,
5148,
485,
2813,
3243,
2434,
3541,
5037,
576,
207,
5258,
4287,
6924,
5656,
7460,
6310,
5983,
4606,
3721,
2726,
1487,
3278,
619,
5952,
6266,
7409,
2642,
2337,
7500,
377,
4851,
2139,
5126,
2774,
3730,
6962,
1803,
3320,
1053,
199,
772,
2672,
2688,
4727,
5305,
4458,
6877,
4878,
3406,
5104,
5260,
3393,
241,
3002,
5155,
3360,
1782,
6500,
3226,
3358,
6454,
4681,
5472,
5784,
2463,
1940,
3476,
740,
6778,
2830,
922,
2263,
5031,
5763,
684,
4132,
5526,
5548,
4645,
4843,
6202,
1894,
5730,
7503,
732,
5142,
5979,
6436,
1516,
2525,
4990,
3634,
6702,
1892,
3983,
328,
6646,
2523,
1595,
5256,
2980,
2382,
3213,
7417,
533,
2626,
4196,
3058,
277,
6774,
1896,
1894,
6988,
4089,
4328,
232,
3917,
5544,
2535,
1290,
7490,
4319,
1760,
1047,
2818,
6950,
3618,
974,
2994,
3710,
1832,
4935,
6167,
1206,
793,
5047,
2458,
1082,
3159,
564,
894,
5063,
4829,
2886,
5946,
7545,
1240,
2037,
4023,
4754,
2184,
6065,
6473,
782,
2713,
3019,
6912,
1644,
4901,
5671,
3561,
2655,
5033,
163,
868,
2701,
5031,
1668,
6698,
147,
3091,
3118,
6701,
2528,
7181,
1763,
1545,
5805,
1168,
5742,
6972,
2562,
6715,
1902,
6427,
4422,
2479,
3491,
5931,
2575,
6758,
4631,
3942,
4469,
4000,
3607,
1904,
5095,
2299,
6342,
1758,
5665,
4816,
225,
5611,
3762,
6718,
4362,
612,
6762,
2449,
4548,
3298,
2088,
6273,
5925,
3877,
5233,
2703,
2499,
1832,
1948,
3958,
7482,
2561,
5119,
7508,
6356,
989,
3259,
7135,
1735,
4286,
5909,
2832,
7339,
5393,
1960,
862,
7052,
6141,
666,
932,
2683,
5309,
4082,
3916,
9,
7450,
6584,
808,
601,
7013,
407,
389,
136,
4462,
4178,
5268,
1795,
2883,
852,
2308,
392,
3182,
1904,
843,
40,
5492,
3934,
3403,
7210,
1666,
3369,
6915,
106,
811,
2023,
6697,
2360,
3280,
447,
2539,
6380,
3709,
7150,
298,
2996,
2976,
280,
5247,
4084,
2932,
6695,
4,
7389,
7224,
3236,
6292,
1679,
502,
1946,
1187,
2173,
1848,
274,
3481,
7076,
2162,
4934,
4668,
428,
6798,
3290,
4810,
2673,
3832,
3734,
601,
4189,
3695,
6109,
3973,
4233,
4004,
1991,
5385,
2153,
4562,
6104,
4401,
6368,
2494,
5122,
7022,
4499,
5481,
1841,
5683,
4270,
6587,
4329,
4403,
2197,
2387,
6416,
4409,
4563,
4396,
205,
6398,
87,
602,
4359,
5053,
2700,
2791,
2803,
1063,
5285,
3408,
1818,
6625,
392,
3510,
5667,
3108,
6407,
78,
4066,
6499,
5164,
2865,
6884,
2273,
2662,
2243,
1808,
1025,
5464,
2286,
4252,
3442,
6096,
6953,
2452,
7546,
5254,
3135,
4220,
3632,
6432,
4959,
5763,
5733,
3328,
3293,
1049,
3758,
6420,
2520,
2657,
692,
1284,
5602,
3639,
5720,
547,
4934,
430,
1099,
1552,
6847,
5978,
4850,
3038,
2885,
3336,
1582,
4275,
7492,
7395,
5668,
6445,
952,
4052,
3435,
3642,
3266,
4946,
636,
6830,
330,
1790,
577,
4460,
1517,
35,
5619,
604,
1525,
6540,
3367,
5288,
5844,
5572,
6553,
5054,
2998,
1043,
5216,
1391,
4856,
6807,
3024,
1664,
1069,
550,
3719,
335,
1680,
4781,
2766,
640,
6201,
5342,
1831,
2521,
358,
1519,
6104,
7095,
4384,
4162,
4671,
1681,
1362,
6999,
7299,
6583,
2991,
7275,
7029,
6082,
7197,
872,
7290,
5034,
6035,
6492,
339,
5817,
2149,
6666,
5573,
4491,
4459,
553,
5824,
1698,
733,
2441,
2567,
4766,
2305,
4341,
504,
2988,
1794,
1231,
64,
4833,
5842,
4850,
6907,
430,
6974,
5535,
4500,
3661,
723,
5792,
412,
3992,
7135,
2888,
4389,
5896,
7481,
5493,
4016,
4675,
7186,
2206,
3529,
4030,
3132,
3696,
2516,
7261,
1021,
1293,
840,
6081,
3987,
7554,
1071,
3085,
776,
3229,
67,
4307,
3726,
2286,
6721,
392,
6819,
7547,
6659,
209,
6390,
1345,
7112,
175,
360,
4523,
4791,
5520,
1260,
6414,
5773,
6145,
3562,
3584,
4203,
2790,
1364,
3620,
5889,
1786,
1390,
5474,
3335,
2773,
1978,
3663,
3712,
3684,
3430,
2357,
5593,
5187,
5307,
2134,
5909,
7185,
6209,
4793,
4978,
1974,
4974,
7138,
6649,
1497,
2402,
2577,
4094,
2412,
1902,
3135,
2206,
5677,
3393,
5717,
3192,
4589,
3595,
173,
2193,
4983,
5634,
3321,
3010,
3941,
1330,
2912,
5899,
2422,
1354,
7122,
7053,
6960,
4309,
5536,
607,
64,
714,
6638,
150,
5505,
447,
4694,
1027,
3498,
361,
1228,
6824,
2642,
95,
4129,
2675,
6968,
5317,
4353,
876,
2791,
4940,
2593,
5579,
3376,
5327,
6274,
115,
329,
4039,
3804,
6031,
4834,
3512,
2976,
6434,
2961,
88,
1924,
2952,
4242,
2053,
3323,
6316,
6104,
189,
3342,
1410,
2077,
3912,
5463,
5448,
6573,
6416,
6277,
1727,
4645,
4961,
6291,
4507,
2889,
6898,
453,
1691,
2378,
6376,
44,
838,
4228,
2488,
4526,
4654,
5682,
7506,
6598,
1025,
6642,
6234,
6748,
6294,
4779,
6402,
940,
2678,
6592,
5156,
1800,
6733,
3535,
7020,
4588,
4632,
1375,
7389,
100,
1289,
377,
7506,
2576,
28,
2664,
6920,
7121,
6167,
4754,
2019,
1588,
3434,
312,
6777,
4922,
6786,
4528,
976,
6837,
6413,
4842,
5401,
6603,
6699,
6335,
6287,
1061,
1087,
709,
426,
7473,
931,
1841,
4428,
6336,
6568,
3674,
5847,
5114,
7153,
1391,
6667,
3510,
557,
1848,
1345,
1049,
4252,
7094,
651,
2576,
6277,
1012,
4542,
1270,
6859,
6456,
2592,
2846,
3031,
6263,
1840,
6498,
3026,
550,
3630,
1651,
5266,
1099,
4107,
3468,
2656,
7117,
4063,
7291,
1229,
1382,
5804,
4698,
3181,
4767,
3044,
6907,
5390,
2379,
3781,
2238,
6887,
2146,
3541,
6123,
6547,
3864,
1121,
944,
924,
1431,
3709,
113,
5370,
2682,
5932,
2052,
651,
1120,
6162,
5036,
5184,
6148,
4557,
2100,
6866,
1129,
409,
3307,
7024,
5947,
3843,
289,
6026,
314,
780,
5694,
1765,
645,
6855,
2283,
4432,
4408,
7472,
3434,
2607,
847,
3023,
4450,
882,
6963,
488,
6451,
1463,
1908,
5773,
4728,
6748,
2743,
2531,
6409,
1625,
1106,
6255,
189,
1495,
1224,
7354,
1154,
3469,
6964,
3502,
763,
5527,
4032,
7112,
7341,
7398,
1079,
4987,
4844,
6073,
2700,
4609,
696,
4242,
4477,
7061,
102,
7524,
4708,
4083,
4094,
3374,
5515,
3187,
5101,
882,
3691,
1802,
4496,
4888,
480,
2409,
1802,
1588,
1185,
5828,
3576,
3133,
3025,
1453,
4953,
2241,
3790,
2285,
2950,
4134,
6195,
7073,
5925,
3602,
943,
4111,
7451,
4118,
6812,
2440,
5659,
6022,
534,
3704,
2667,
3422,
7244,
1649,
4027,
3231,
4107,
3903,
1105,
362,
6970,
6832,
5141,
1605,
1233,
5342,
5863,
1016,
3799,
5681,
5326,
6501,
3349,
3144,
99,
2515,
7385,
2482,
4707,
5914,
2005,
442,
3289,
2972,
2135,
4110,
220,
6113,
5348,
6224,
7137,
718,
1266,
333,
6115,
3059,
6045,
6516,
1617,
2559,
2301,
2938,
486,
5446,
1980,
2317,
3159,
856,
6863,
2355,
1916,
4044,
902,
5823,
3091,
290,
7442,
3681,
2528,
6741,
4173,
4186,
5517,
3276,
6621,
6785,
600,
1968,
3033,
5513,
1,
2323,
4311,
6723,
5751,
3339,
5535,
6596,
1151,
1698,
1947,
1415,
5743,
6880,
4752,
2081,
3905,
6338,
461,
6601,
861,
5764,
7224,
713,
5759,
5013,
6429,
2357,
7073,
1047,
1344,
3068,
712,
2024,
7064,
2511,
5263,
4786,
4187,
3191,
4251,
1645,
1234,
5741,
2902,
3070,
5711,
6154,
3538,
808,
1154,
2038,
5640,
5277,
332,
1463,
1375,
1798,
1367,
5618,
5825,
1387,
6875,
2808,
6390,
5110,
7183,
3391,
371,
5203,
2971,
6976,
4604,
1506,
7126,
2117,
5466,
5231,
3382,
4294,
5724,
3226,
7206,
4407,
551,
4775,
4539,
7016,
1610,
6873,
6651,
5191,
1697,
389,
2457,
6038,
3885,
676,
2460,
1574,
1547,
924,
3761,
6470,
5198,
4612,
6207,
2395,
7253,
5231,
7449,
4367,
318,
5451,
6354,
2646,
6208,
7225,
3880,
5975,
4220,
4567,
3435,
2430,
1497,
7287,
5060,
2349,
3526,
4133,
9,
1708,
5788,
6546,
3531,
7300,
5919,
7156,
3285,
2661,
4595,
3133,
4246,
5887,
4470,
3461,
3789,
7145,
2229,
4350,
7263,
4420,
2516,
865,
605,
1832,
4473,
3575,
5740,
417,
2191,
3491,
4082,
7079,
5088,
926,
1689,
3324,
4938,
5110,
6629,
2580,
1193,
6006,
3087,
3259,
1544,
4180,
5188,
6588,
2791,
6511,
6388,
5028,
132,
3810,
3833,
718,
2136,
5234,
133,
5806,
4844,
1813,
290,
4794,
2332,
5742,
6982,
4739,
5951,
2696,
4320,
2185,
3529,
2602,
3388,
2927,
1212,
2396,
3601,
7495,
1200,
1713,
1981,
5806,
4880,
189,
2311,
2120,
460,
998,
4048,
3536,
2716,
6097,
4156,
95,
2056,
247,
3403,
3625,
504,
5008,
4269,
1787,
3250,
2000,
3440,
5287,
3141,
3336,
5736,
2667,
1027,
2248,
6714,
3770,
6635,
556,
7189,
4735,
7482,
5928,
1004,
1237,
2215,
4191,
223,
1456,
5592,
6732,
4857,
2991,
7282,
3686,
2304,
6656,
1437,
1343,
252,
3051,
1726,
4661,
5762,
5383,
1476,
2460,
5466,
374,
1801,
782,
2704,
1521,
758,
1364,
4119,
784,
1145,
956,
3238,
1854,
7442,
3623,
6260,
2632,
3303,
1902,
5396,
985,
3631,
2779,
2914,
3316,
7472,
2946,
402,
4469,
8,
4853,
7490,
90,
6443,
4644,
4863,
5000,
7335,
4650,
6929,
4215,
4517,
1471,
7527,
562,
5036,
3987,
86,
7568,
705,
2138,
2464,
4304,
6192,
7033,
3499,
6291,
6985,
818,
3552,
6191,
6659,
5748,
751,
7247,
5614,
6614,
2199,
6042,
2031,
4295,
104,
3556,
2921,
721,
5055,
1538,
6569,
1134,
5214,
3055,
2117,
4589,
2712,
5588,
3592,
3948,
7,
1512,
6444,
4138,
3285,
2368,
1780,
1682,
5116,
1572,
7475,
5243,
6098,
6108,
2412,
6473,
5377,
6472,
5120,
6100,
204,
41,
1486,
4272,
3751,
5585,
4538,
1642,
2350,
5725,
5587,
3437,
778,
12,
1349,
3638,
3,
214,
2449,
5960,
5655,
2223,
4167,
6305,
7338,
5961,
7556,
5015,
1916,
1368,
6086,
4498,
824,
6689,
5799,
6929,
1858,
6918,
6640,
4770,
6288,
708,
7268,
5666,
3557,
1251,
2653,
4726,
767,
5110,
6557,
3957,
2664,
3035,
4075,
5540,
2943,
1440,
1201,
1792,
5573,
4558,
6183,
2368,
6591,
264,
4931,
5184,
286,
737,
5098,
5954,
2892,
517,
7093,
828,
1671,
433,
4983,
4513,
3244,
6504,
3400,
7099,
5299,
1847,
2853,
4615,
195,
2709,
4396,
2666,
1107,
5357,
7415,
1083,
1133,
4294,
6881,
4101,
4058,
6613,
6480,
3055,
5265,
325,
1037,
4737,
4660,
1906,
4766,
2245,
479,
5194,
5698,
5375,
4752,
2874,
5449,
639,
627,
6871,
5983,
3400,
2847,
7498,
5894,
1402,
2065,
6970,
829,
4688,
3050,
2548,
7071,
1192,
5323,
4216,
1152,
5294,
113,
2070,
7484,
5489,
4163,
5934,
1090,
2114,
3476,
5379,
6910,
2411,
3454,
1437,
7429,
6819,
1788,
36,
2655,
3071,
6654,
5947,
2728,
4235,
1379,
5414,
2178,
6230,
4686,
4548,
7340,
5047,
7051,
1903,
2961,
1842,
5653,
2838,
3831,
2526,
2516,
5385,
702,
3371,
5056,
1550,
97,
1026,
946,
2538,
4889,
2517,
383,
4393,
564,
2072,
4567,
3315,
7567,
2287,
2703,
5287,
2953,
6597,
6405,
3728,
7136,
422,
332,
3200,
693,
6593,
744,
5417,
1459,
6182,
7461,
530,
97,
5532,
826,
1252,
575,
2111,
5273,
152,
2230,
6282,
4112,
6736,
6048,
1979,
2392,
171,
7038,
2437,
2925,
4355,
1451,
200,
7004,
7068,
2999,
6671,
2432,
6845,
1119,
790,
7405,
5362,
1586,
5106,
5893,
4446,
1685,
6024,
2491,
4146,
3137,
5017,
4685,
7394,
908,
2812,
481,
1287,
4706,
4524,
5521,
2139,
2307,
2861,
3450,
292,
4866,
632,
3834,
1625,
7446,
896,
2783,
5100,
1755,
2576,
4210,
600,
5132,
4207,
5042,
5490,
3270,
6144,
4371,
7345,
1108,
5923,
5286,
6957,
2491,
7110,
2976,
4317,
4728,
6770,
7075,
2485,
5201,
2908,
687,
5048,
6340,
5828,
497,
4585,
3934,
3799,
3808,
4218,
2199,
4084,
4648,
2859,
5726,
6100,
5433,
4471,
3166,
5541,
1709,
2728,
7463,
4408,
1223,
636,
1416,
1775,
6879,
1124,
3307,
5869,
6411,
6786,
235,
740,
4852,
3485,
2457,
4723,
5064,
3013,
4946,
3711,
7284,
5107,
691,
6474,
6488,
1033,
5925,
5873,
3405,
4391,
3062,
5238,
7536,
7137,
5861,
2012,
4364,
3816,
6605,
4101,
989,
7151,
837,
4631,
5821,
4118,
2601,
501,
2391,
4758,
3286,
3556,
6371,
1830,
2361,
3103,
4591,
6797,
6127,
22,
201,
2504,
2315,
1241,
1502,
6641,
5897,
608,
5938,
4695,
95,
229,
1471,
1939,
190,
2444,
4193,
7054,
5311,
3370,
3520,
7105,
7568,
6596,
6313,
6018,
2870,
1102,
2103,
4822,
4082,
3225,
7122,
5282,
6970,
6134,
223,
2271,
2283,
2143,
3466,
2056,
3509,
3471,
1320,
2189,
3240,
4507,
5805,
722,
1385,
2185,
1735,
111,
3901,
4257,
6108,
5911,
2047,
3267,
912,
7282,
6687,
4024,
510,
2217,
6471,
2908,
363,
5048,
6865,
2057,
6877,
696,
5349,
3892,
2820,
7476,
2526,
3641,
2472,
514,
6771,
341,
3416,
5396,
706,
2228,
1930,
5080,
1194,
3351,
6454,
2615,
6660,
712,
945,
5099,
3935,
1880,
1827,
6251,
3715,
2876,
463,
909,
3020,
5766,
6327,
5543,
21,
1659,
988,
6045,
182,
3055,
413,
4209,
2614,
1502,
1158,
2366,
6441,
135,
604,
2968,
4192,
5870,
6067,
308,
5858,
623,
3986,
2314,
6477,
1827,
232,
2061,
4065,
6970,
5000,
7486,
4434,
5312,
5959,
5082,
706,
2213,
6238,
4398,
3336,
5311,
4522,
1735,
6029,
6096,
1111,
5060,
239,
7350,
4706,
6500,
2615,
4450,
7293,
7038,
2248,
355,
3446,
279,
6025,
1153,
1871,
819,
5483,
1700,
4238,
245,
6553,
3626,
2557,
6210,
2169,
1905,
3883,
6020,
1764,
1173,
7085,
3499,
5806,
1926,
1810,
402,
6741,
4209,
2096,
2199,
2486,
80,
1505,
3832,
3990,
2548,
3305,
2813,
6391,
7409,
1213,
2002,
5980,
4136,
7101,
3118,
159,
1952,
825,
7226,
5362,
3649,
607,
5897,
136,
6275,
2487,
7326,
123,
5347,
4470,
1763,
3214,
1165,
1135,
2716,
7197,
3324,
2395,
2026,
1810,
5101,
2707,
219,
873,
940,
5395,
3866,
5517,
309,
5452,
3073,
3949,
2207,
2583,
4824,
4733,
5489,
6519,
2355,
3135,
1367,
4621,
5272,
2423,
2764,
2415,
2938,
499,
2702,
2906,
7038,
3455,
7401,
7472,
2249,
5935,
7544,
5512,
6816,
3747,
936,
7349,
4905,
2365,
7461,
859,
4315,
6121,
2580,
952,
4872,
2846,
6252,
6907,
6530,
7033,
5921,
6653,
4644,
7330,
1892,
5927,
1268,
3432,
6889,
3548,
6624,
3855,
511,
4503,
5111,
6461,
2994,
1694,
4775,
5058,
5607,
1079,
351,
4822,
3992,
2322,
5152,
1265,
6708,
6692,
2925,
5720,
3473,
258,
1415,
1378,
4798,
1486,
7169,
5610,
3438,
2535,
4837,
648,
4962,
4204,
2956,
2265,
3448,
6999,
316,
2240,
3542,
6632,
1546,
5744,
401,
3675,
499,
4085,
4789,
5521,
2050,
179,
4625,
2102,
3050,
3600,
1487,
5616,
7481,
6673,
428,
4312,
2127,
3259,
4236,
4201,
6465,
4358,
4758,
3423,
4943,
1801,
3975,
3724,
5983,
1891,
6151,
5795,
4754,
5458,
7039,
835,
1564,
2087,
4552,
1932,
5227,
5023,
3127,
1584,
4530,
2977,
3636,
7440,
708,
2793,
6170,
2024,
446,
4859,
5217,
6294,
314,
1813,
6289,
4950,
4596,
3489,
612,
4132,
2809,
2907,
3898,
1968,
1198,
6461,
890,
4736,
3003,
5982,
3715,
4451,
4570,
4091,
5538,
762,
2881,
5716,
6413,
62,
1370,
4423,
793,
1040,
6887,
540,
6452,
1259,
5333,
3055,
6494,
5052,
5618,
4348,
724,
5464,
5639,
223,
2820,
5012,
86,
4452,
274,
5898,
1748,
4138,
6722,
6338,
5878,
766,
2674,
5073,
3009,
5973,
3322,
740,
3288,
2806,
904,
1065,
1665,
5767,
5429,
895,
149,
4679,
7409,
2360,
3563,
148,
4598,
2090,
7225,
2412,
2004,
3625,
4031,
4844,
6010,
159,
1359,
6049,
3560,
7305,
7335,
1016,
994,
4431,
3232,
2832,
5349,
4351,
2653,
2663,
4115,
2886,
482,
4141,
2515,
2,
5521,
3004,
1525,
2816,
3641,
2621,
3993,
549,
5118,
1903,
7570,
2016,
3501,
1486,
316,
7336,
2162,
2668,
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py | ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py | #!/usr/bin/env python3
import random
from binascii import unhexlify
"""
Original AES-128 implementation by Bo Zhu (http://about.bozhu.me) at
https://github.com/bozhu/AES-Python . PKCS#7 padding,
byte array and string support added by https://github.com/boppreh/aes.
"""
s_box = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
)
inv_s_box = (
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
)
def sub_bytes(s):
for i in range(4):
for j in range(4):
s[i][j] = s_box[s[i][j]]
def sub_bytes_defect(s):
b = random.randint(0,15)
for i in range(4):
for j in range(4):
if i*4 + j == b:
s[i][j] = random.randint(0,255)
else:
s[i][j] = s_box[s[i][j]]
def inv_sub_bytes(s):
for i in range(4):
for j in range(4):
s[i][j] = inv_s_box[s[i][j]]
def shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def inv_shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
# learned from https://web.archive.org/web/20100626212235/http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mix_single_column(a):
# see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
u = a[0]
a[0] ^= t ^ xtime(a[0] ^ a[1])
a[1] ^= t ^ xtime(a[1] ^ a[2])
a[2] ^= t ^ xtime(a[2] ^ a[3])
a[3] ^= t ^ xtime(a[3] ^ u)
def mix_columns(s):
for i in range(4):
mix_single_column(s[i])
def inv_mix_columns(s):
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
u = xtime(xtime(s[i][0] ^ s[i][2]))
v = xtime(xtime(s[i][1] ^ s[i][3]))
s[i][0] ^= u
s[i][1] ^= v
s[i][2] ^= u
s[i][3] ^= v
mix_columns(s)
r_con = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
def bytes2matrix(text):
""" Converts a 16-byte array into a 4x4 matrix. """
return [list(text[i:i+4]) for i in range(0, len(text), 4)]
def matrix2bytes(matrix):
""" Converts a 4x4 matrix into a 16-byte array. """
return bytes(sum(matrix, []))
def xor_bytes(a, b):
""" Returns a new byte array with the elements xor'ed. """
return bytes(i^j for i, j in zip(a, b))
def inc_bytes(a):
""" Returns a new byte array with the value increment by 1 """
out = list(a)
for i in reversed(range(len(out))):
if out[i] == 0xFF:
out[i] = 0
else:
out[i] += 1
break
return bytes(out)
def pad(plaintext):
"""
Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes.
Note that if the plaintext size is a multiple of 16,
a whole block will be added.
"""
padding_len = 16 - (len(plaintext) % 16)
padding = bytes([padding_len] * padding_len)
return plaintext + padding
class AES:
"""
Class for AES-128 encryption with CBC mode and PKCS#7.
This is a raw implementation of AES, without key stretching or IV
management. Unless you need that, please use `encrypt` and `decrypt`.
"""
rounds_by_key_size = {16: 10, 24: 12, 32: 14}
def __init__(self, master_key):
"""
Initializes the object with a given key.
"""
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
self.broken_rounds = []
def _expand_key(self, master_key):
"""
Expands and returns a list of key matrices for the given master_key.
"""
# Initialize round keys with raw key material.
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // 4
i = 1
while len(key_columns) < (self.n_rounds + 1) * 4:
# Copy previous word.
word = list(key_columns[-1])
# Perform schedule_core once every "row".
if len(key_columns) % iteration_size == 0:
# Circular shift.
word.append(word.pop(0))
# Map to S-BOX.
word = [s_box[b] for b in word]
# XOR with first byte of R-CON, since the others bytes of R-CON are 0.
word[0] ^= r_con[i]
i += 1
elif len(master_key) == 32 and len(key_columns) % iteration_size == 4:
# Run word through S-box in the fourth iteration when using a
# 256-bit key.
word = [s_box[b] for b in word]
# XOR with equivalent word from previous iteration.
word = xor_bytes(word, key_columns[-iteration_size])
key_columns.append(word)
# Group key words in 4x4 byte matrices.
return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
def encrypt_block(self, plaintext):
"""
Encrypts a single block of 16 byte long plaintext.
"""
assert len(plaintext) == 16
plain_state = bytes2matrix(plaintext)
add_round_key(plain_state, self._key_matrices[0])
for i in range(1, self.n_rounds):
if i in self.broken_rounds:
sub_bytes_defect(plain_state)
else:
sub_bytes(plain_state)
shift_rows(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[i])
if self.n_rounds+1 in self.broken_rounds:
sub_bytes_defect(plain_state)
else:
sub_bytes(plain_state)
shift_rows(plain_state)
add_round_key(plain_state, self._key_matrices[-1])
return matrix2bytes(plain_state)
def decrypt_block(self, ciphertext):
"""
Decrypts a single block of 16 byte long ciphertext.
"""
assert len(ciphertext) == 16
cipher_state = bytes2matrix(ciphertext)
add_round_key(cipher_state, self._key_matrices[-1])
inv_shift_rows(cipher_state)
inv_sub_bytes(cipher_state)
for i in range(self.n_rounds - 1, 0, -1):
add_round_key(cipher_state, self._key_matrices[i])
inv_mix_columns(cipher_state)
inv_shift_rows(cipher_state)
inv_sub_bytes(cipher_state)
add_round_key(cipher_state, self._key_matrices[0])
return matrix2bytes(cipher_state)
def start():
key = random.randbytes(16)
aes = AES(key)
messages = set()
for _ in range(40):
print("\nWhat do you want to do?")
print("1. Break Box \n2. Use Device \n3. Enter the Door")
choice = int(input(">> "))
print()
if choice == 1:
print("Which box do you want to break?")
choice2 = int(input(">> "))
if choice2 in aes.broken_rounds:
print("That would only hurt you")
else:
print("The box cracks")
aes.broken_rounds.append(choice2)
elif choice == 2:
print("input a message")
m = unhexlify(input(">> "))
if len(m) < 16:
m = pad(m)
messages.add(m)
c = aes.encrypt_block(m)
print(c.hex())
elif choice == 3:
m = random.randbytes(16)
while m in messages:
m = random.randbytes(16)
print("The display only shows a number, but you know it expects input:")
print(m.hex())
c = unhexlify(input(">> "))
if aes.decrypt_block(c) == m:
print("GPNCTF{fake_flag}")
else:
print("The alarm goes off and all doors shut tight")
exit()
print("The security catched you")
if __name__ == "__main__":
start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/crypto/ref4ctory/main.py | ctfs/KITCTFCTF/2023/crypto/ref4ctory/main.py | import sys
import ast
def check_factors(a,b,ab):
if abs(a)<=1 or abs(b)<=1:
print("too easy")
return False
if type(a*b) == float:
print("no floats please")
return False
return a*b == ab
factors = [4,10,0x123120,38201373467,247867822373,422943922809193529087,3741]
for composite in factors:
print(f"Factor {composite}")
a = ast.literal_eval(input("a:").strip())
b = ast.literal_eval(input("b:").strip())
if check_factors(a,b,composite):
continue
break
else:
print("Here is your Flag. Good Job!")
print(open("flag.txt").read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/crypto/one_true_pairing/main.py | ctfs/KITCTFCTF/2023/crypto/one_true_pairing/main.py | import sys
import random
from secret import get_next_seed, store_leaked_data, store_exec_status, get_flag, get_scheduled_cmds
RESEED_AFTER = 1000000
def xor_bytes(a, b):
return bytes(map(lambda x: x[0] ^ x[1], zip(a,b)))
class Handler:
def __init__(self) -> None:
self.handling = True
self.reseed()
def randbytes(self, n):
self.rng_used += n
b = self.rng.randbytes(n)
return b
def reseed(self):
seed_bytes = get_next_seed()
if len(seed_bytes) != 12:
self.send_raw(b'ERROR: No more pre-shared seeds')
exit()
self.rng = random.Random()
self.rng.seed(seed_bytes)
self.rng_used = 0
def recv_msg(self, length, default=None):
received = b''
while len(received) < length:
new_input = sys.stdin.buffer.read(length - len(received))
received += new_input.strip().replace(b' ', b'')
if len(received) == 0 and default:
return default
try:
return received
except:
return b''
def send_raw(self, msg):
sys.stdout.buffer.write(msg)
sys.stdout.buffer.flush()
def start_encrypted(self):
return
def end_encrypted(self):
if self.rng_used > RESEED_AFTER:
self.reseed()
def recv_encrypted(self):
msg = b''
try:
len_otp = self.randbytes(1)
len_encrypted = self.recv_msg(1, default=len_otp)
length = int.from_bytes(xor_bytes(len_otp, len_encrypted), 'little')
if length == 0:
self.end_encrypted()
return msg
otp = self.randbytes(length)
received = self.recv_msg(length)
msg = xor_bytes(otp, received)
except:
self.handling = False
finally:
self.end_encrypted()
return msg
def send_encrypted(self, msg):
try:
assert len(msg) < 256
otp = self.randbytes(1) + self.randbytes(len(msg)) # split for receiver
self.send_raw(xor_bytes(otp, len(msg).to_bytes(1, 'little') + msg))
except:
self.handling = False
self.send_raw(b'ERR: %d' % (len(msg)))
finally:
self.end_encrypted()
def process_commands(self, cmd_msg: bytes):
response = b''
while len(cmd_msg) > 0:
cursor = 4
current_cmd = cmd_msg[:cursor]
if current_cmd == b'LEAK':
length = cmd_msg[cursor]
cursor += 1
store_leaked_data(cmd_msg[cursor:cursor+length])
cursor += length
elif current_cmd == b'EXEC':
store_exec_status(cmd_msg[cursor])
cursor += 1
elif current_cmd == b'FLAG':
response += get_flag()
elif current_cmd == b'EXIT':
self.handling = False
else:
response += b'ERROR'
cmd_msg = cmd_msg[cursor:]
response = response[:255] # truncate response to max length
response += get_scheduled_cmds(255 - len(response))
return response
def handle(self):
self.send_raw(b'RDY')
while self.handling:
try:
cmd_msg = self.recv_encrypted()
if not self.handling: return
response = self.process_commands(cmd_msg)
self.send_encrypted(response)
if not self.handling: return
except:
return
def main():
srv = Handler()
srv.handle()
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/KITCTFCTF/2023/crypto/one_true_pairing/secret.py | ctfs/KITCTFCTF/2023/crypto/one_true_pairing/secret.py | import random
import os
FLAG_RESPONSE = b'Please keep this for me: ' + os.getenv('FLAG', 'GPNCTF{fake_flag}').encode()
def get_next_seed():
return os.urandom(12)
def store_leaked_data(data):
# store leaked data from remote for later processing
return
def store_exec_status(status):
# store or process exec result status
return
def get_flag():
return FLAG_RESPONSE
MAX_COMMANDS = 3
def get_scheduled_cmds(max_len):
cmds = b''
for _ in range(MAX_COMMANDS):
if max_len > 0 and random.random() > 0.7:
if max_len >= 16 and random.random() > 0.9:
cmds += b'\x05\x0enc -lvnp 31337'
cmds += bytes([random.randint(1, 4)])
else:
break
return cmds
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/crypto/winterfactory/winterfactory.py | ctfs/KITCTFCTF/2023/crypto/winterfactory/winterfactory.py | #!/usr/bin/env python3
import winternitz.signatures
import random
from binascii import unhexlify
class factory:
def __init__(self):
w = 2**16
self.wots = winternitz.signatures.WOTS(w, digestsize=256, hashfunction=winternitz.signatures.openssl_sha256)
self.factory_id = 831347528
init_message = bytes("surely no secret here"+str(self.factory_id), "utf-8")
self.certification = self.wots.sign(init_message)
self.p11 = None
self.p12 = None
self.p13 = None
self.p21 = None
self.p22 = None
self.p23 = None
def produce(self):
r1 = random.randbytes(16)
r2 = random.randbytes(16)
self.p11, self.p12, self.p13 = r1, self.p11, self.p12
self.p21, self.p22, self.p23 = r2, self.p21, self.p22
def run_factory(self):
print(f"You arrive at the factory to buy a new number for your room at home. At the door you read: 'This factory is certified:' followed by these numbers")
print()
output_array(self.certification["signature"])
print()
print(f"Going inside you see a conveyer belt presenting their newest numbers.")
while True:
self.produce()
self.print_belt()
answer = input("Do you want to buy one of the current numbers? >> ")
if answer == "yes":
self.accept_products()
exit()
def accept_products(self):
choice = int(input("Which number do you want to buy? >> "), 16)
product_of_choice = self.p11 if choice == 1 else self.p21
other_product = self.p21 if choice == 1 else self.p11
product_certification = self.wots.sign(product_of_choice)
print("You manage to see part of the signature from the customer in front of you:")
print(product_certification["signature"][-2].hex())
user_certificate = input("Please sign your order >> ")
user_certificate = [unhexlify(c) for c in user_certificate.split("|")]
if self.wots.verify(other_product, user_certificate):
print("GPNCTF{fake_flag}")
def print_belt(self):
print()
print("="*108)
s1 = f" | {self.p11.hex()} | "
s1 += f"{self.p12.hex() if self.p12 != None else ' '*32} | "
s1 += f"{self.p13.hex() if self.p13 != None else ' '*32} |"
print(s1)
print("="*108)
s2 = f" | {self.p21.hex()} | "
s2 += f"{self.p22.hex() if self.p22 != None else ' '*32} | "
s2 += f"{self.p23.hex() if self.p23 != None else ' '*32} |"
print(s2)
print("="*108)
print()
def output_array(arr):
s = "".join([a.hex()+"|" for a in arr])
print(s[:-1])
if __name__ == "__main__":
f = factory()
f.run_factory()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KITCTFCTF/2023/web/cross-site-python/app.py | ctfs/KITCTFCTF/2023/web/cross-site-python/app.py | from flask import Flask, redirect, make_response, render_template, request, abort, Response
from base64 import b64decode as decode
from base64 import b64encode as encode
from queue import Queue
import random
import string
app = Flask(__name__)
projects = {}
project_queue = Queue(1000)
def generate_id():
return ''.join(random.choice(string.digits) for i in range(15))
@app.after_request
def add_csp(res):
res.headers['Content-Security-Policy'] = "script-src 'self' 'wasm-unsafe-eval'; object-src 'none'; base-uri 'none';"
return res
@app.route('/')
def index():
return redirect("/new")
@app.route("/new")
def new():
if project_queue.full():
projects.pop(project_queue.get())
new_id = generate_id()
while new_id in projects.keys():
new_id = generate_id()
projects[new_id] = 'print("Hello World!")'
project_queue.put(new_id)
return redirect(f"/{new_id}/edit")
@app.route("/<code_id>/edit")
def edit_page(code_id):
if code_id not in projects.keys():
abort(404)
code = projects.get(code_id)
return render_template("edit.html", code=code)
@app.route('/<code_id>/save', methods=["POST"])
def save_code(code_id):
code = request.json["code"]
projects[code_id] = code
return {"status": "success"}
@app.route('/<code_id>/exec')
def code_page(code_id):
if code_id not in projects.keys():
abort(404)
code = projects.get(code_id)
# Genius filter to prevent xss
blacklist = ["script", "img", "onerror", "alert"]
for word in blacklist:
if word in code:
# XSS attempt detected!
abort(403)
res = make_response(render_template("code.html", code=code))
return res
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/KITCTFCTF/2023/web/Wanky_Mail/app.py | ctfs/KITCTFCTF/2023/web/Wanky_Mail/app.py | from flask import Flask, render_template_string, request, redirect, abort
from aiosmtpd.controller import Controller
from datetime import datetime
from base58 import b58decode, b58encode
import random
import string
import os
from datetime import datetime
import queue
mails = {}
active_addr = queue.Queue(1000)
def format_email(sender, rcpt, body, timestamp, subject):
return {"sender": sender, "rcpt": rcpt, 'body': body, 'subject': subject, "timestamp": timestamp}
def render_emails(address):
id = 0
render = """
<table>
<tr>
<th id="th-left">From</th>
<th>Subject</th>
<th id="th-right">Date</th>
</tr>
"""
overlays = ""
m = mails[address].copy()
for email in m:
render += f"""
<tr id="{id}">
<td>{email['sender']}</td>
<td>{email['subject']}</td>
<td>{email['timestamp']}</td>
</tr>
"""
overlays += f"""
<div id="overlay-{id}" class="overlay">
<div class="email-details">
<h1>{email['subject']} - from: {email['sender']} to {email['rcpt']}</h1>
<p>{email['body']}</p>
</div>
</div>
"""
id +=1
render += "</table>"
render += overlays
return render
def get_emails(id):
with open('templates/index.html') as f:
page = f.read()
return page.replace('{{$}}', render_emails(id))
def log_email(session, envelope):
print(f'{session.peer[0]} - - {repr(envelope.mail_from)}:{repr(envelope.rcpt_tos)}:{repr(envelope.content)}', flush=True)
def esc(s: str):
return "{% raw %}" + s + "{% endraw %}"
class Handler:
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
if not address.endswith(os.environ.get('HOSTNAME')):
return '550 not relaying to that domain'
envelope.rcpt_tos.append(address)
print(address, flush=True)
return '250 OK'
async def handle_DATA(self, server, session, envelope):
m = format_email(esc(envelope.mail_from), envelope.rcpt_tos[0], esc(envelope.content.decode()), datetime.now().strftime("%d-%m-%Y, %H:%M:%S"), "PLACEHOLDER")
log_email(session, envelope)
r = envelope.rcpt_tos[0]
if not mails.get(r):
if active_addr.full():
mails.pop(active_addr.get())
mails[r] = []
active_addr.put(r)
if len(mails[r]) > 10:
mails[r].pop(0)
mails[r].append(m)
return '250 OK'
c = Controller(Handler(), "0.0.0.0")
c.start()
app = Flask(__name__)
@app.route('/')
def index():
username = ''.join(random.choice(string.ascii_lowercase) for i in range(12))
address = f"{username}@{os.environ.get('HOSTNAME', 'example.com')}"
if not address in mails.keys():
if active_addr.full():
del mails[active_addr.get()]
mails[address] = []
active_addr.put(address)
id = b58encode(address).decode()
return redirect("/" + id)
@app.route('/<id>')
def mailbox(id):
address = b58decode(id).decode()
if not address in mails.keys():
abort(404)
return render_template_string(get_emails(address), address=address)
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/KITCTFCTF/2022/pwn/date/pow.py | ctfs/KITCTFCTF/2022/pwn/date/pow.py | import os
import subprocess
import sys
DIFFICULTY = 26
def check(r, token):
return subprocess.call(["hashcash", f"-cyqb{DIFFICULTY}", "-r", r, token]) == 0
def main():
if len(sys.argv) != 2:
print("No command provided", flush=True)
exit()
r = os.urandom(8).hex()
print(f"Send the result of: hashcash -mb{DIFFICULTY} {r}", flush=True)
token = input().replace("hashcash token: ", "").strip()
if check(r, token):
subprocess.call(sys.argv[1], shell=True)
else:
print("Token invalid", flush=True)
sys.exit(1)
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.