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/Paradigm/2023/pwn/100percent/challenge.py | ctfs/Paradigm/2023/pwn/100percent/challenge.py | from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
PwnChallengeLauncher(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Enterprise_Blockchain/challenge.py | ctfs/Paradigm/2023/pwn/Enterprise_Blockchain/challenge.py | from anvil_server.database import UserData
from anvil_server.socket import (
CreateInstanceRequest,
CreateInstanceResponse,
UnixClient,
)
from eth_abi import abi
from eth_launchers.launcher import ETH_RPC_URL
from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
from eth_launchers.utils import (
anvil_autoImpersonateAccount,
anvil_setCodeFromFile,
anvil_setStorageAt,
deploy,
)
from foundry.anvil import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def create_instance(self, client: UnixClient) -> CreateInstanceResponse:
return client.create_instance(
CreateInstanceRequest(
id=self.team,
instances={
"l1": LaunchAnvilInstanceArgs(
balance=1000,
chain_id=78704,
),
"l2": LaunchAnvilInstanceArgs(
path="/opt/foundry/bin/anvil-l2",
balance=1000,
chain_id=78705,
),
},
daemons=[
"/home/user/relayer.py",
],
)
)
def deploy(self, user_data: UserData) -> str:
l1_web3 = user_data.get_privileged_web3("l1")
l2_web3 = user_data.get_privileged_web3("l2")
anvil_autoImpersonateAccount(l2_web3, True)
challenge = deploy(
l1_web3,
self.project_location,
mnemonic=user_data.mnemonic,
env={
"L1_RPC": l1_web3.provider.endpoint_uri,
"L2_RPC": l2_web3.provider.endpoint_uri,
},
)
anvil_autoImpersonateAccount(l2_web3, False)
# deploy multisig
anvil_setCodeFromFile(
l2_web3,
"0x0000000000000000000000000000000000031337",
"MultiSig.sol:SimpleMultiSigGov",
)
for i in range(3):
owner_addr = user_data.get_additional_account(1 + i)
anvil_setStorageAt(
l2_web3,
"0x0000000000000000000000000000000000031337",
hex(i),
"0x" + owner_addr.address[2:].ljust(64, "0"),
)
return challenge
def is_solved(self, user_data: UserData, addr: str) -> bool:
web3 = user_data.get_privileged_web3("l1")
(result,) = abi.decode(
["bool"],
web3.eth.call(
{
"to": addr,
"data": web3.keccak(text="isSolved()")[:4],
}
),
)
return result
Challenge(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Enterprise_Blockchain/relayer.py | ctfs/Paradigm/2023/pwn/Enterprise_Blockchain/relayer.py | import json
import time
import traceback
from threading import Thread
from anvil_server.database import UserData
from eth_abi import abi
from eth_launchers.daemon import Daemon
from web3 import Web3
from web3.contract.contract import Contract
from web3.middleware.signing import construct_sign_and_send_raw_middleware
class Relayer(Daemon):
def __init__(self):
super().__init__(required_properties=["challenge_address"])
def _run(self, user_data: UserData):
with open("project/.cache/out/Bridge.sol/Bridge.json", "r") as f:
cache = json.load(f)
bridge_abi = cache["metadata"]["output"]["abi"]
challenge_addr = user_data.metadata["challenge_address"]
relayer = user_data.get_additional_account(0)
l1 = user_data.get_unprivileged_web3("l1")
l1.middleware_onion.add(construct_sign_and_send_raw_middleware(relayer))
l1.eth.default_account = relayer.address
l2 = user_data.get_unprivileged_web3("l2")
l2.middleware_onion.add(construct_sign_and_send_raw_middleware(relayer))
l2.eth.default_account = relayer.address
(bridge_address,) = abi.decode(
["address"],
l1.eth.call(
{
"to": l1.to_checksum_address(challenge_addr),
"data": l1.keccak(text="BRIDGE()")[:4].hex(),
}
),
)
l1_bridge = l1.eth.contract(
address=l1.to_checksum_address(bridge_address), abi=bridge_abi
)
l2_bridge = l2.eth.contract(
address=l2.to_checksum_address(bridge_address), abi=bridge_abi
)
Thread(target=self._relayer_worker, args=(l1, l1_bridge, l2_bridge)).start()
Thread(target=self._relayer_worker, args=(l2, l2_bridge, l1_bridge)).start()
def _relayer_worker(
self, src_web3: Web3, src_bridge: Contract, dst_bridge: Contract
):
_src_chain_id = src_web3.eth.chain_id
_dst_chain_id = dst_bridge.w3.eth.chain_id
_last_processed_block_number = src_web3.eth.block_number
while True:
try:
latest_block_number = src_web3.eth.block_number
if _last_processed_block_number > latest_block_number:
print(
f"chain {_src_chain_id} overran block {_last_processed_block_number} {latest_block_number}, wtf?"
)
_last_processed_block_number = latest_block_number
print(
f"chain {_src_chain_id} syncing {_last_processed_block_number + 1} {latest_block_number + 1}"
)
for i in range(
_last_processed_block_number + 1, latest_block_number + 1
):
_last_processed_block_number = i
found = False
for tx_hash in src_web3.eth.get_block(i).transactions:
tx = src_web3.eth.get_transaction(tx_hash)
print(
f'chain {_src_chain_id} checking block {i} tx {tx_hash.hex()} {tx["to"]} {src_bridge.address}'
)
if tx["to"] == src_bridge.address:
found = True
break
if found:
for event in src_bridge.events:
logs = event.get_logs(fromBlock=i, toBlock=i)
for log in logs:
print(
f"chain {_src_chain_id} got log {src_web3.to_json(log)}"
)
if log.event == "SendRemoteMessage":
try:
if _dst_chain_id == log.args["targetChainId"]:
tx_hash = dst_bridge.functions.relayMessage(
log.args["targetAddress"],
_src_chain_id,
log.args["sourceAddress"],
log.args["msgValue"],
log.args["msgNonce"],
log.args["msgData"],
).transact()
dst_bridge.w3.eth.wait_for_transaction_receipt(
tx_hash
)
time.sleep(1)
except Exception as e:
print(e)
except:
traceback.print_exc()
pass
finally:
time.sleep(1)
Relayer().start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Skill_Based_Game/challenge.py | ctfs/Paradigm/2023/pwn/Skill_Based_Game/challenge.py | from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
PwnChallengeLauncher(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Black_Sheep/challenge.py | ctfs/Paradigm/2023/pwn/Black_Sheep/challenge.py | import os
from typing import Optional
from anvil_server.database import UserData
from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
from eth_launchers.utils import deploy
def concat_env(a: Optional[str], b: Optional[str]):
if not a and not b:
return ""
if not a:
return b
if not b:
return a
return a + os.pathsep + b
class Challenge(PwnChallengeLauncher):
def deploy(self, user_data: UserData) -> str:
web3 = user_data.get_privileged_web3("main")
return deploy(
web3,
self.project_location,
user_data.mnemonic,
env={
"PATH": concat_env("/opt/huff/bin:/usr/bin", os.getenv("PATH")),
},
)
Challenge(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Dai++/challenge.py | ctfs/Paradigm/2023/pwn/Dai++/challenge.py | from anvil_server.socket import (
CreateInstanceRequest,
CreateInstanceResponse,
UnixClient,
)
from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
from eth_launchers.launcher import ETH_RPC_URL
from foundry.anvil import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def create_instance(self, client: UnixClient) -> CreateInstanceResponse:
return client.create_instance(
CreateInstanceRequest(
id=self.team,
instances={
"main": LaunchAnvilInstanceArgs(
balance=1000,
fork_url=ETH_RPC_URL,
fork_block_num=16_543_210,
),
},
)
)
Challenge(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Dai++/project/lib/chainlink/core/gethwrappers/generation/fastgen.py | ctfs/Paradigm/2023/pwn/Dai++/project/lib/chainlink/core/gethwrappers/generation/fastgen.py | #!/usr/bin/env python3
'''Quick-and-dirty (very quick!) compiler and generator of go contract wrappers
Usage: {fastgen_dir}/fastgen.py [<pkg_name> ...]
DO NOT check in the outputs from this script! Instead, run `go generate` in the
parent directory. We are using solc-select for compilation of solidity contracts, and
using the abi files it outputs as a single source of truth.
However, this is much faster and more reliable, for actual development of
contracts which interact in intricate ways with go code. Once you're done with
development, be a good citizen before you push and replace the wrappers from
this script with those generated by `go generate` as described above.
(`../go_generate_test.go` will remind you with a CI failure if you forget.)
This requires the correct versions of abigen and the correct version of solc on
your path, which can be installed as described in `../go_generate.go`.
'''
import os, pathlib, sys
thisdir = os.path.abspath(os.path.dirname(sys.argv[0]))
godir = os.path.dirname(thisdir)
gogenpath = os.path.join(godir, 'go_generate.go')
abigenpath = 'go run ./generation/generate/wrap.go'
pkg_to_src = {}
for line in open(gogenpath):
if abigenpath in line:
abipath, pkgname = line.split(abigenpath)[-1].strip().split()
srcpath = os.path.abspath(os.path.join(godir, abipath)).replace(
'/abi/', '/src/').replace('.json', '.sol')
if not os.path.exists(srcpath):
srcpath = os.path.join(os.path.dirname(srcpath), 'dev',
os.path.basename(srcpath))
if not os.path.exists(srcpath):
srcpath = srcpath.replace('/dev/', '/tests/')
if os.path.basename(srcpath) != 'OffchainAggregator.sol':
assert os.path.exists(srcpath), 'could not find ' + \
os.path.basename(srcpath)
pkg_to_src[pkgname] = srcpath
args = sys.argv[1:]
if len(args) == 0 or any(p not in pkg_to_src for p in args):
print(__doc__.format(fastgen_dir=thisdir))
print("Here is the list of packages you can build. (You can add more by")
print("updating %s)" % gogenpath)
print()
longest = max(len(p) for p in pkg_to_src)
colwidth = longest + 4
header = "Package name".ljust(colwidth) + "Contract Source"
print(header)
print('-' * len(header))
for pkgname, contractpath in pkg_to_src.items():
print(pkgname.ljust(colwidth) + contractpath)
sys.exit(1)
for pkgname in args:
solidity_path = pkg_to_src[pkgname]
outpath = os.path.abspath(os.path.join(godir, 'generated', pkgname,
pkgname + '.go'))
pathlib.Path(os.path.dirname(outpath)).mkdir(exist_ok=True)
# assert not os.system(
# f'abigen -sol {solidity_path} -pkg {pkgname} -out {outpath}')
cmd = f'abigen -sol {solidity_path} -pkg {pkgname} -out {outpath}'
assert not os.system(cmd), 'Command "%s" failed' % cmd
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Hopping_into_Place/challenge.py | ctfs/Paradigm/2023/pwn/Hopping_into_Place/challenge.py | from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
PwnChallengeLauncher(project_location="project", provider=get_team_provider()).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Token_Locker/challenge.py | ctfs/Paradigm/2023/pwn/Token_Locker/challenge.py | from anvil_server.database import UserData
from eth_account.account import LocalAccount
from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
from eth_launchers.utils import anvil_setCodeFromFile
class Challenge(PwnChallengeLauncher):
def deploy(self, user_data: UserData) -> str:
anvil_setCodeFromFile(
user_data.get_privileged_web3("main"),
"0x7f5C649856F900d15C83741f45AE46f5C6858234",
"UNCX_ProofOfReservesV2_UniV3.sol:UNCX_ProofOfReservesV2_UniV3",
)
return super().deploy(user_data)
Challenge(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Suspicious_Charity/watcher.py | ctfs/Paradigm/2023/pwn/Suspicious_Charity/watcher.py | import ast
import asyncio
import pickle
import sys
import time
import traceback
import typing
from anvil_server.database import UserData
from anvil_server.socket import GetInstanceRequest, UnixClient, UpdateMetadataRequest
from eth_account import Account
from eth_account.signers.local import LocalAccount
from web3 import AsyncHTTPProvider, AsyncWeb3
from web3.contract import AsyncContract
from web3.middleware.signing import async_construct_sign_and_send_raw_middleware
Account.enable_unaudited_hdwallet_features()
class Watcher:
def __init__(self, external_id: str, rpc_url: str, challenge_contract: str) -> None:
self.__external_id = external_id
self.__rpc_url = rpc_url
self.__challenge_contract = challenge_contract
self.__router_address = ""
self.__price_cache = {}
self.__pair_cache = {}
async def _init(self):
self.__router_address = (
await self.call(
await self.get_block_number(), self.__challenge_contract, "ROUTER()(address)"
)
).strip()
print("router address = ", self.__router_address)
async def run(self):
await self._init()
while True:
try:
block_number = await self.get_block_number()
flag_charity = await self.call(
block_number,
self.__router_address,
"flagCharity()(address)",
)
listing_tokens = await self.list_array(
block_number,
self.__router_address,
"listingTokensCount()(uint256)",
"listingTokens(uint256)(address)",
)
lp_tokens = await self.list_array(
block_number,
self.__router_address,
"lpTokensCount()(uint256)",
"lpTokensInfo(uint256)(string,address)",
)
lp_tokens = [info.rsplit("\n", 1) for info in lp_tokens]
async def calculate_token_price(addr):
price = await self.get_token_price(block_number, addr)
amount = await self.get_balance(block_number, addr, flag_charity)
return price * amount
async def calculate_lp_token_price(i, res):
pool, addr = res
amount = await self.get_balance(block_number, addr, flag_charity)
(
token_amount_a,
token_amount_b,
total_supply,
) = await self.get_pair_status(block_number, addr)
if total_supply == 0:
return 0
(price_a, price_b) = await self.get_pair_prices(
block_number, i, pool
)
return (
((price_a * token_amount_a) + (price_b * token_amount_b))
* amount
// total_supply
)
acc = 0
# Normal tokens
acc += sum(
await asyncio.gather(
*[calculate_token_price(addr) for addr in listing_tokens]
)
)
# LP tokens
acc += sum(
await asyncio.gather(
*[
calculate_lp_token_price(i, res)
for i, res in enumerate(lp_tokens)
]
)
)
print("user has donated", acc // 10**18)
UnixClient().update_metadata(UpdateMetadataRequest(
id=self.__external_id,
metadata={
'donated': acc,
},
))
except:
traceback.print_exc()
pass
finally:
await asyncio.sleep(1)
async def get_token_price(self, block_number, addr: str) -> int:
key = "token_%s" % addr
if key not in self.__price_cache:
self.__price_cache[key] = int(
await self.call(
block_number,
self.__router_address,
"priceOf(address)(uint256)",
addr,
)
)
return self.__price_cache[key]
async def get_pair_prices(
self, block_number: int, index: str, pool_id: str
) -> typing.Tuple[int, int]:
pool_name = "pool_%s" % pool_id
if pool_name not in self.__pair_cache:
token_a, token_b = (
await self.call(
block_number,
self.__router_address,
"lpTokenPair(uint256)(address,address)",
str(index),
)
).split()
self.__pair_cache[pool_name] = (token_a, token_b)
token_a, token_b = self.__pair_cache[pool_name]
return (
await self.get_token_price(block_number, token_a),
await self.get_token_price(block_number, token_b),
)
async def get_pair_status(
self, block_number: int, pair: str
) -> typing.Tuple[int, int, int]:
result = await self.call(
block_number,
self.__router_address,
"lpTokensStatus(address)(uint256,uint256,uint256)",
pair,
)
return [int(x, 0) for x in result.strip().split("\n")]
async def get_balance(self, block_number: int, token: str, who: str) -> int:
result = await self.call(block_number, token, "balanceOf(address)", who)
return int(result.strip(), 0)
async def list_array(
self, block_number, address, count_sig, element_sig
) -> typing.List[str]:
res = await self.call(
block_number,
address,
count_sig,
)
print("list array res", res)
count = int(res)
result = await asyncio.gather(
*[
self.call(
block_number,
address,
element_sig,
str(i),
)
for i in range(count)
]
)
return result
async def call(self, block_number: int, address: str, sig: str, *call_args) -> str:
proc = await asyncio.create_subprocess_exec(
"/opt/foundry/bin/cast", "call", "--rpc-url", self.__rpc_url, "-b", str(block_number), address, sig, *call_args,
stdout=asyncio.subprocess.PIPE,
)
stdout, _ = await proc.communicate()
return stdout.decode()[:-1]
async def get_block_number(self) -> int:
proc = await asyncio.create_subprocess_exec(
"/opt/foundry/bin/cast", "block-number", "--rpc-url", self.__rpc_url,
stdout=asyncio.subprocess.PIPE,
)
stdout, _ = await proc.communicate()
return int(stdout)
async def main(user_data: UserData):
r1 = Watcher(
user_data.external_id,
f"http://127.0.0.1:8545/{user_data.internal_id}/main",
user_data.metadata["challenge_address"],
)
t1 = asyncio.create_task(r1.run())
await t1
if __name__ == "__main__":
internal_id = sys.argv[1]
while True:
time.sleep(1)
resp = UnixClient().get_instance(GetInstanceRequest(id=internal_id))
print("got instance", internal_id, resp)
if not resp.ok or "challenge_address" not in resp.user_data.metadata:
print("instance not ready")
continue
break
asyncio.run(main(resp.user_data))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Suspicious_Charity/challenge.py | ctfs/Paradigm/2023/pwn/Suspicious_Charity/challenge.py | from anvil_server.database import UserData
from anvil_server.socket import (
CreateInstanceRequest,
CreateInstanceResponse,
UnixClient,
)
from eth_launchers.launcher import ETH_RPC_URL
from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
from foundry.anvil import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def create_instance(self, client: UnixClient) -> CreateInstanceResponse:
return client.create_instance(
CreateInstanceRequest(
id=self.team,
instances={
"main": LaunchAnvilInstanceArgs(
balance=1000,
fork_url=ETH_RPC_URL,
),
},
daemons=[
"/home/user/watcher.py",
],
)
)
def is_solved(self, user_data: UserData, addr: str) -> bool:
return user_data.metadata.get("donated", 0) > 100000000000000000000000000
Challenge(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/DODONT/challenge.py | ctfs/Paradigm/2023/pwn/DODONT/challenge.py | from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
PwnChallengeLauncher(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/crypto/Oven/challenge.py | ctfs/Paradigm/2023/crypto/Oven/challenge.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import random
import os
import hashlib
FLAG = os.getenv("FLAG", "PCTF{flag}").encode("utf8")
FLAG = bytes_to_long(FLAG[5:-1])
assert FLAG.bit_length() < 384
BITS = 1024
def xor(a, b):
return bytes([i ^ j for i, j in zip(a, b)])
# This doesn't really matter right???
def custom_hash(n):
state = b"\x00" * 16
for i in range(len(n) // 16):
state = xor(state, n[i : i + 16])
for _ in range(5):
state = hashlib.md5(state).digest()
state = hashlib.sha1(state).digest()
state = hashlib.sha256(state).digest()
state = hashlib.sha512(state).digest() + hashlib.sha256(state).digest()
value = bytes_to_long(state)
return value
def fiat_shamir():
p = getPrime(BITS)
g = 2
y = pow(g, FLAG, p)
v = random.randint(2, 2**512)
t = pow(g, v, p)
c = custom_hash(long_to_bytes(g) + long_to_bytes(y) + long_to_bytes(t))
r = (v - c * FLAG) % (p - 1)
assert t == (pow(g, r, p) * pow(y, c, p)) % p
return (t, r), (p, g, y)
while True:
resp = input("[1] Get a random signature\n[2] Exit\nChoice: ")
if "1" in resp:
print()
(t, r), (p, g, y) = fiat_shamir()
print(f"t = {t}\nr = {r}")
print()
print(f"p = {p}\ng = {g}\ny = {y}")
print()
elif "2" in resp:
print("Bye!")
exit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/crypto/Dragon_Tyrant/watcher.py | ctfs/Paradigm/2023/crypto/Dragon_Tyrant/watcher.py | import asyncio
import json
import sys
import time
from typing import List
import random
from anvil_server.database import UserData
from anvil_server.socket import GetInstanceRequest, UnixClient
from eth_abi import abi
from eth_account.signers.local import LocalAccount
from eth_launchers.daemon import Daemon
from web3 import Web3
from web3.middleware.signing import construct_sign_and_send_raw_middleware
class Watcher(Daemon):
def __init__(self):
super().__init__(required_properties=["challenge_address"])
def _run(self, user_data: UserData):
randomness_provider = user_data.get_additional_account(0)
web3 = user_data.get_unprivileged_web3("main")
web3.middleware_onion.add(
construct_sign_and_send_raw_middleware(randomness_provider)
)
(nft,) = abi.decode(
["address"],
web3.eth.call(
{
"to": user_data.metadata["challenge_address"],
"data": web3.keccak(text="TOKEN()")[:4].hex(),
}
),
)
from_number = web3.eth.block_number - 1
while True:
latest_number = web3.eth.block_number
print(f"from_number={from_number} latest={latest_number}")
if from_number > latest_number:
time.sleep(1)
continue
logs = web3.eth.get_logs(
{
"address": web3.to_checksum_address(nft),
"topics": [
web3.keccak(text="RequestOffchainRandomness()").hex(),
],
"fromBlock": from_number,
"toBlock": latest_number,
}
)
for log in logs:
print(f"fetched log={web3.to_json(log)}")
txhash = web3.eth.send_transaction(
{
"from": randomness_provider.address,
"to": web3.to_checksum_address(nft),
"data": (
web3.keccak(text="resolveRandomness(bytes32)")[:4]
+ random.randbytes(32)
).hex(),
"gas": 1_000_000,
"gasPrice": int(40e9),
}
)
print(f"resolved randomness txhash={txhash.hex()}")
from_number = latest_number + 1
Watcher().start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/crypto/Dragon_Tyrant/challenge.py | ctfs/Paradigm/2023/crypto/Dragon_Tyrant/challenge.py | from anvil_server.socket import (
CreateInstanceRequest,
CreateInstanceResponse,
UnixClient,
)
from eth_launchers.launcher import ETH_RPC_URL
from eth_launchers.pwn_launcher import PwnChallengeLauncher
from eth_launchers.team_provider import get_team_provider
from foundry.anvil import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def create_instance(self, client: UnixClient) -> CreateInstanceResponse:
return client.create_instance(
CreateInstanceRequest(
id=self.team,
instances={
"main": LaunchAnvilInstanceArgs(
balance=1000,
fork_url=ETH_RPC_URL,
),
},
daemons=[
"/home/user/watcher.py",
],
)
)
Challenge(
project_location="project",
provider=get_team_provider(),
).run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/just-in-time/deploy/chal.py | ctfs/Paradigm/2022/pwn/just-in-time/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"from": deployer_address,
"value": Web3.toWei(50, 'ether'),
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/rescue/deploy/chal.py | ctfs/Paradigm/2022/pwn/rescue/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"from": deployer_address,
"value": Web3.toWei(10, 'ether'),
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/vanity/deploy/chal.py | ctfs/Paradigm/2022/pwn/vanity/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"from": deployer_address,
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/cairo-proxy/deploy/chal.py | ctfs/Paradigm/2022/pwn/cairo-proxy/deploy/chal.py | import cairo_sandbox
from pathlib import Path
from starknet_py.net import AccountClient
from starknet_py.contract import Contract
from starkware.starknet.public.abi import get_storage_var_address
from starkware.starknet.core.os.contract_address.contract_address import calculate_contract_address_from_hash
async def deploy(client: AccountClient, player_address: int) -> int:
print("[+] deploying erc20")
erc20_deployment = await Contract.deploy(
client=client,
compiled_contract=Path("compiled/almost_erc20.cairo").read_text(),
salt=111111,
)
await erc20_deployment.wait_for_acceptance()
print("[+] deploying proxy")
proxy_deployment = await Contract.deploy(
client=client,
compiled_contract=Path("compiled/proxy.cairo").read_text(),
constructor_args=[await client.get_class_hash_at(erc20_deployment.deployed_contract.address)],
)
await proxy_deployment.wait_for_acceptance()
wrapper_contract = Contract(
proxy_deployment.deployed_contract.address,
erc20_deployment.deployed_contract.data.abi,
client,
)
print("[+] initializing contracts")
response = await client.execute(
calls=[
wrapper_contract.functions["initialize"].prepare(client.address, int(50000e18)),
wrapper_contract.functions["transfer"].prepare(1337, int(25000e18)),
wrapper_contract.functions["transfer"].prepare(7331, int(25000e18)),
],
max_fee=int(1e16)
)
await client.wait_for_tx(response.transaction_hash)
return proxy_deployment.deployed_contract.address
async def checker(client: AccountClient, proxy_contract: Contract, player_address: int) -> bool:
erc20_address = calculate_contract_address_from_hash(
salt=111111,
class_hash=await client.get_storage_at(proxy_contract.address, get_storage_var_address("implementation"), "latest"),
constructor_calldata=[],
deployer_address=0,
)
erc20_contract = await Contract.from_address(erc20_address, client)
wrapper_contract = Contract(
proxy_contract.address,
erc20_contract.data.abi,
client,
)
player_balance = (await wrapper_contract.functions["balanceOf"].call(player_address)).balance
return player_balance == int(50000e18)
cairo_sandbox.run_launcher([
cairo_sandbox.new_launch_instance_action(deploy),
cairo_sandbox.new_kill_instance_action(),
cairo_sandbox.new_get_flag_action(checker),
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/hint-finance/deploy/chal.py | ctfs/Paradigm/2022/pwn/hint-finance/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"gas": 15_000_000,
"from": deployer_address,
"value": Web3.toWei(30, 'ether'),
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/merkledrop/deploy/chal.py | ctfs/Paradigm/2022/pwn/merkledrop/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"from": deployer_address,
"value": Web3.toWei(50, 'ether'),
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/stealing-sats/deploy/chal.py | ctfs/Paradigm/2022/pwn/stealing-sats/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"from": deployer_address,
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/electric-sheep/deploy/chal.py | ctfs/Paradigm/2022/pwn/electric-sheep/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"from": deployer_address,
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/cairo-auction/deploy/chal.py | ctfs/Paradigm/2022/pwn/cairo-auction/deploy/chal.py | import cairo_sandbox
from pathlib import Path
from starknet_py.net import AccountClient
from starknet_py.contract import Contract
from starkware.python.utils import from_bytes
async def deploy(client: AccountClient, player_address: int) -> int:
print("[+] deploying erc20")
erc20_deployment = await Contract.deploy(
client=client,
compiled_contract=Path("compiled/erc20.cairo").read_text(),
constructor_args=[
from_bytes(b"Test Token"),
from_bytes(b"TTK"),
6,
int(1000000e6),
client.address,
],
)
await erc20_deployment.wait_for_acceptance()
print("[+] deploying auction")
auction_deployment = await Contract.deploy(
client=client,
compiled_contract=Path("compiled/auction.cairo").read_text(),
constructor_args=[
erc20_deployment.deployed_contract.address,
client.address,
],
)
await auction_deployment.wait_for_acceptance()
print("[+] creating bidders")
bidder_1 = await AccountClient.create_account(client.client)
bidder_2 = await AccountClient.create_account(client.client)
print("[+] initializing contracts")
response = await client.execute(
calls=[
erc20_deployment.deployed_contract.functions["transfer"].prepare(bidder_1.address, int(100000e6)),
erc20_deployment.deployed_contract.functions["transfer"].prepare(bidder_2.address, int(100000e6)),
erc20_deployment.deployed_contract.functions["transfer"].prepare(player_address, int(50000e6)),
auction_deployment.deployed_contract.functions["start_auction"].prepare(),
],
max_fee=int(1e16)
)
await client.wait_for_tx(response.transaction_hash)
response = await client.execute(
calls=[
erc20_deployment.deployed_contract.functions["approve"].prepare(auction_deployment.deployed_contract.address, int(100000e6)),
auction_deployment.deployed_contract.functions["increase_credit"].prepare(int(100000e6)),
auction_deployment.deployed_contract.functions["raise_bid"].prepare(1, int(100000e6)),
],
max_fee=int(1e16)
)
await bidder_1.wait_for_tx(response.transaction_hash)
response = await client.execute(
calls=[
erc20_deployment.deployed_contract.functions["approve"].prepare(auction_deployment.deployed_contract.address, int(100000e6)),
auction_deployment.deployed_contract.functions["increase_credit"].prepare(int(100000e6)),
auction_deployment.deployed_contract.functions["raise_bid"].prepare(1, int(100000e6)),
],
max_fee=int(1e16)
)
await bidder_2.wait_for_tx(response.transaction_hash)
return auction_deployment.deployed_contract.address
async def checker(client: AccountClient, auction_contract: Contract, player_address: int) -> bool:
winner = (await auction_contract.functions["current_winner"].call(1)).current_winner
return winner == player_address
cairo_sandbox.run_launcher([
cairo_sandbox.new_launch_instance_action(deploy),
cairo_sandbox.new_kill_instance_action(),
cairo_sandbox.new_get_flag_action(checker),
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/cairo-auction/contracts/openzeppelin/__init__.py | ctfs/Paradigm/2022/pwn/cairo-auction/contracts/openzeppelin/__init__.py | """StarkNet/Cairo development toolbelt."""
try:
from importlib import metadata as importlib_metadata
except ImportError:
import importlib_metadata
try:
__version__ = importlib_metadata.version("openzeppelin-cairo-contracts")
except importlib_metadata.PackageNotFoundError:
__version__ = None
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/pwn/trapdoor/deploy/chal.py | ctfs/Paradigm/2022/pwn/trapdoor/deploy/chal.py | import binascii
import os
import subprocess
import tempfile
import json
import requests
import eth_sandbox
from Crypto.Util import number
FLAG = os.getenv("FLAG", "PCTF{placeholder}")
def new_factorize_action():
def action() -> int:
ticket = eth_sandbox.check_ticket(input("ticket please: "))
if not ticket:
print("invalid ticket!")
return 1
if ticket.challenge_id != eth_sandbox.CHALLENGE_ID:
print("invalid ticket!")
return 1
runtime_code = input("runtime bytecode: ")
try:
binascii.unhexlify(runtime_code)
except:
print("runtime code is not hex!")
return 1
with tempfile.TemporaryDirectory() as tempdir:
with open("./Script.sol", "r") as f:
script = f.read()
a = number.getPrime(128)
b = number.getPrime(128)
script = script.replace("NUMBER", str(a * b)).replace("CODE", runtime_code)
with open(f"{tempdir}/Script.sol", "w") as f:
f.write(script)
p = subprocess.run(
args=[
"/root/.foundry/bin/forge",
"script",
"Script.sol",
"--tc",
"Script",
],
cwd=tempdir,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print()
if p.returncode != 0:
print("failed to run script")
return 1
result = p.stdout.decode("utf8").strip().split("\n")[-1].strip()
print(result)
if result.startswith("you factored the number!"):
print(FLAG)
return eth_sandbox.Action(name="factorize", handler=action)
eth_sandbox.run_launcher([
new_factorize_action(),
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2022/rev/fun-reversing-challenge/deploy/chal.py | ctfs/Paradigm/2022/rev/fun-reversing-challenge/deploy/chal.py | import json
from pathlib import Path
import eth_sandbox
from web3 import Web3
def deploy(web3: Web3, deployer_address: str, player_address: str) -> str:
rcpt = eth_sandbox.sendTransaction(web3, {
"from": deployer_address,
"data": json.loads(Path("compiled/Setup.sol/Setup.json").read_text())["bytecode"]["object"],
})
return rcpt.contractAddress
eth_sandbox.run_launcher([
eth_sandbox.new_launch_instance_action(deploy),
eth_sandbox.new_kill_instance_action(),
eth_sandbox.new_get_flag_action()
])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BDSec/2023/web/Injection/main.py | ctfs/BDSec/2023/web/Injection/main.py | from flask import Flask, request , render_template
import textwrap
import sqlite3
import os
import hashlib
os.environ['FLAG'] ='test{flag}'
app = Flask(__name__)
@app.route('/login', methods=['POST' , 'GET'])
def root_data():
data = request.form
if 'username' not in data or 'password' not in data:
error = 'Please Enter Both username and password'
return render_template('index.html' , error = error)
con = sqlite3.connect(':memory:')
cur = con.cursor()
cur.execute('CREATE TABLE users (username TEXT, password TEXT)')
cur.execute(
'INSERT INTO users VALUES ("admin", ?)',
[hashlib.md5(os.environ['FLAG'].encode()).hexdigest()]
)
output = cur.execute(
'SELECT * FROM users WHERE username = {data[username]!r} AND password = {data[password]!r}'
.format(data=data)
).fetchone()
if output is None:
error = "Ups! Wrong Creds!"
return render_template('index.html' , error = error)
username, password = output
if username != data["username"] or password != data["password"]:
error = 'You cant Hack Uss!!!'
return render_template('index.html' , error = error)
return f'Yooo!! {data["username"]}!'.format(data=data)
@app.route('/', methods=['GET'])
def root_get():
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=7777 , debug=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BDSec/2022/crypto/Dominoes/encrypt.py | ctfs/BDSec/2022/crypto/Dominoes/encrypt.py | #! /usr/bin/python3
def x(a, b):
h = ""
for i in range(len(a), len(b)):
t.push(y(b[i]))
return "".join(a)
def y(c):
a = list(c)
for i in range(len(c)):
b = c[i]
for j in range(i + 1, len(c)):
b = chr(ord(b) ^ ord(c[j]))
a[i] = b
return "".join(a)
def z():
flag = open("flag.txt", "r").read()
enc_flag = y(flag)
f = open("encrypted.txt", "w")
f.write(enc_flag)
f.close()
if __name__ == "__main__":
z()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BDSec/2022/crypto/LoopLover/enc.py | ctfs/BDSec/2022/crypto/LoopLover/enc.py | def f(t):
c = list(t)
for i in range(len(t)):
for j in range(i, len(t) - 1):
for k in range(j, len(t) - 2):
c[k], c[k+1] = c[k+1], c[k]
return "".join(c)
if __name__ == "__main__":
flag = open("flag.txt", "r").read()
open("ciphertext.txt", "w").write(f(flag))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BDSec/2022/web/Jungle_Templating/app.py | ctfs/BDSec/2022/web/Jungle_Templating/app.py | from flask import *
app = Flask(__name__)
@app.route('/',methods=['GET', 'POST'])
def base():
person = ""
if request.method == 'POST':
if request.form['name']:
person = request.form['name']
palte = '''
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Secure Search</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>
<body>
<h1 class="container my-3">Hi, %s</h1>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<div class="container my-3">
<form action="/" method="post">
<div class="mb-3">
<label for="text" class="form-label">Type your name here:- </label>
<input type="text" class="form-control" name="name" id="text" value="">
</div>
<button type="submit" class="btn btn-primary">See magic</button>
</form>
</div>
</body>
</html>'''% person
return render_template_string(palte)
if __name__=="__main__":
app.run("0.0.0.0",port=5000,debug=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/misc/Perfect_Score/chall.py | ctfs/bi0sCTF/2024/misc/Perfect_Score/chall.py | import random
import os
from math import gcd
flag = open("flag.txt").read().strip()
menu = """
╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ 50 shots, hit the spot! ║
║ ____________________________________________________________________________ ║
║ ║
║ 1. Verify divisibility ║
║ 2. Verify co-prime array ║
║ 3. Submit your guess ║
║ ║
╚══════════════════════════════════════════════════════════════════════════════╝
"""
def handle_client():
cnt = 0
for _ in range(10):
print(menu)
x = random.randint(1, 10000)
for _ in range(50):
print("╔══════════════════════════════════════════════════════════════════════════════╗")
print("║ [+] Choose an option (1, 2, or 3): ║")
print("╚══════════════════════════════════════════════════════════════════════════════╝")
print(">> ",end="")
option = input().strip()
if option == '1':
print("__________________________________________________")
print("▏[CHOICE 1] Enter a number to check divisibility: ▏")
print("▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔")
print("[+] Your number : ",end="")
y = int(input().strip())
response = "Yes" if x % y == 0 else "No"
print(f"[+] Is x divisible by {y}? {response}")
print("")
elif option == '2':
print("__________________________________________________")
print("▏[CHOICE 2] Enter an array (e.g. 2,3,5): ▏")
print("▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔")
print("Your Array : ",end="")
array_str = input().strip()
array = [int(num) for num in array_str.split(",")]
response = "Yes" if any(gcd(x, y) > 1 for y in array) else "No"
print(f"Is there a y in [{array_str}] such that gcd(x, y) > 1? {response}")
print("")
elif option == '3':
print("__________________________________________________")
print("▏[CHOICE 3] Submit your guess for x: ▏")
print("▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔")
print("Your guess : ",end="")
guess = int(input().strip())
if guess == x:
print("Congratulations! Your guess is correct.")
print("")
cnt += 1
break
else:
print("[+] Incorrect guess. Try again.")
exit(0)
else:
print("❯❯ Invalid option. Please select 1, 2, or 3.")
exit(0)
if cnt == 10:
print(f"Congratulations! You have guessed all 10 numbers correctly. Here is your flag: {flag}")
if __name__ == "__main__":
try:
handle_client()
except:
exit(0) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/misc/bfs/test.py | ctfs/bi0sCTF/2024/misc/bfs/test.py | #!/bin/python3
# THIS WOULD BE A TEST INTERPRETER PROGRAMME FOR BRAINF*CK THAT YOU CAN MODIFY AND USE
# TO TEST OUT YOUR SOLUTIONS TO THE GIVEN PROBLEMS
# THIS IS SIMILAR TO THE REMOTE VERSION BUT IS NOT THE SAME AND THE REMOTE HAS WAY MORE FUNCTIONALITY THAN THE FOLLOWING CODE
from time import *
import sys
import os
TAPESIZE = 30000
# ALLOCATING TAPE
# TAPE IS INITIALISED TO ZERO FOR EVERY RUN
tape = [0 for i in range (TAPESIZE)]
# SETTING AN INSTRUCTION PTR
dp = 0
pc = 0
loopstack = []
def banner():
os.system("clear")
print(
'''
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
\u258f ___ ___ _ ___ _ _ ___ \u258f
\u258f | _ ) _ \ /_\ |_ _| \| | __|/\_ \u258f
\u258f | _ \ / / _ \ | || .` | _|> < \u258f
\u258f |___/_|_\/_/ \_\___|_|\_|_| \/ \u258f
\u258f ___ ___ ___ ___ ___ _ __ __ __ __ ___ _ _ ___ \u258f
\u258f | _ \ _ \/ _ \ / __| _ \ /_\ | \/ | \/ |_ _| \| |/ __| \u258f
\u258f | _/ / (_) | (_ | / / _ \| |\/| | |\/| || || .` | (_ | \u258f
\u258f |_| |_|_\\\___/ \___|_|_\/_/ \_\_| |_|_| |_|___|_|\_|\___| \u258f
\u258f \u258f
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔'''
)
# BASIC CHECKS FOR OOB ARRAY ACCESS
def checkdp():
if (dp < 0 or dp > (TAPESIZE-1)):
print(" [ERROR] ")
print("----DATA-POINTER-WENT-OUT-THE-TAPE----")
exit(-1)
def parantherr():
print(" [ERROR] ")
print("-------UNMATCHED-LOOP-OPERATOR--------")
exit(-1)
def findmatch(code,pc,p):
tmp = []
offset = 1 if p == "[" else -1
idx = pc + offset
ptype = {"[":"]","]":"["}
while(idx < len(code) and idx >= 0):
if(code[idx] == p):
tmp.append(idx)
if(code[idx] == ptype[p]):
if(len(tmp)):
tmp.pop(-1)
else:
return idx
idx += offset
return parantherr()
# READING IN THE CODE WHICH IS TO BE RUN
def readincode(nbytes : int):
code = ""
for i in range (nbytes):
ins = sys.stdin.read(1)
if(type(ins) == bytes):
ins = ins.decode()
code += ins
if "\n" in code:
break
end = code.find("\n")
return code[0:end]
# JUST PRETTY PRINTS THE TAPE FOR YOU
def debug():
os.system("clear")
print("")
print("▕",end="")
for i in range (51):
print("▔▔",end="")
print("▔▏")
if(dp>=5):
print("▕ ",end="")
for i in range (10):
if(i-5==0):
print((f"\033[1;31m[\033[0m{dp+i-5}\033[1;31m]\033[0m".center(29," "))," ",end="")
continue
else: print((f"[{dp+i-5}]".center(7," "))," ",end="")
print(" << {dp} ▏")
print("▕ -",end="")
for i in range (10):
print("---------",end="")
print(" ▏")
print("▕ |",end="")
for i in range (10):
if(i-5==0):
print(((f"\033[1;31m{tape[dp+i-5]}\033[0m").center(18," ")),"|",end="")
continue
print((f"{tape[dp+i-5]}".center(7," ")),"|",end="")
print(" << {tape} ▏")
print("▕ ",end="")
for i in range (50):
print(" ",end="")
print(" ▏")
print(" ",end="")
for i in range (51):
print("▔▔",end="")
print("▔")
sleep(0.1)
else:
print("▕ ",end="")
for i in range (10):
if(i==dp):
print((f"\033[1;31m[\033[0m{dp}\033[1;31m]\033[0m".center(29," "))," ",end="")
continue
print((f"[{i}]".center(7," "))," ",end="")
print(" << {dp} ▏")
print("▕ -",end="")
for i in range (10):
print("---------",end="")
print(" ▏")
print("▕ |",end="")
for i in range (10):
if(i==dp):
print(((f"\033[1;31m{tape[dp]}\033[0m").center(18," ")),"|",end="")
continue
print((f"{tape[i]}".center(7," ")),"|",end="")
print(" << {tape} ▏")
print("▕ ",end="")
for i in range (50):
print(" ",end="")
print(" ▏")
print(" ",end="")
for i in range (51):
print("▔▔",end="")
print("▔")
sleep(0.1)
# BRAINF_CK INTERPRETER BUT WITHOUT THE . AND , INSTRUCTIONS
def run(code):
global pc,dp
pc = 0
while (pc != len(code)):
debug()
if(code[pc] == ">"):
dp += 1
checkdp()
pc += 1
continue
if(code[pc] == "<"):
dp -= 1
checkdp()
pc += 1
continue
if(code[pc] == "+"):
tape[dp] = (tape[dp] + 1) % 0x100
pc += 1
continue
if(code[pc] == "-"):
tape[dp] = (tape[dp] - 1) % 0x100
pc += 1
continue
if(code[pc] == "["):
if(tape[dp] == 0):
idx = findmatch(code,pc,"[")
pc = idx + 1
continue
else:
loopstack.append(pc)
pc += 1
continue
if(code[pc] == "]"):
if(tape[dp] != 0):
if(len(loopstack)):
pc = loopstack.pop(-1)
continue
else:
if(len(loopstack)):
loopstack.pop(-1)
else:
parantherr()
pc += 1
continue
else:
pc += 1
continue
def test():
print("▍>> DATA POINTER AT -",dp)
print("▍>> INPUT YOUR CODE : ",end="",flush=True)
code = readincode(0xff)
run(code)
debug()
def main():
banner()
test()
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/bi0sCTF/2024/pwn/ezv8/server.py | ctfs/bi0sCTF/2024/pwn/ezv8/server.py | #!/usr/bin/python3
import sys
import tempfile
import os
sys.stdout.write("File size >> ")
sys.stdout.flush()
size = int(sys.stdin.readline().strip())
if size > 1024*1024:
sys.stdout.write("Too large!")
sys.stdout.flush()
sys.exit(1)
sys.stdout.write("Data >> ")
sys.stdout.flush()
script = sys.stdin.read(size)
filename = tempfile.mktemp()
with open(filename, "w") as f:
f.write(script)
os.system("./d8 " + filename)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/pwn/ezv8_revenge/server.py | ctfs/bi0sCTF/2024/pwn/ezv8_revenge/server.py | #!/usr/bin/python3
import sys
import tempfile
import os
sys.stdout.write("File size >> ")
sys.stdout.flush()
size = int(sys.stdin.readline().strip())
if size > 1024*1024:
sys.stdout.write("Too large!")
sys.stdout.flush()
sys.exit(1)
sys.stdout.write("Data >> ")
sys.stdout.flush()
script = sys.stdin.read(size)
filename = tempfile.mktemp()
with open(filename, "w") as f:
f.write(script)
os.system("./d8 " + filename)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/pwn/tallocator/script.py | ctfs/bi0sCTF/2024/pwn/tallocator/script.py | #!/usr/bin/env python3
import os
import signal
import subprocess
import sys
import time
from random import randint
def PoW(l=25):
x = randint(2**(l-1), 2**l)
g = randint(2**16, 2**18)
p = 13066599629066242837866432762953247484957727495367990531898423457215621371972536879396943780920715025663601432044420507847680185816504728360166754093930541
target = pow(g, x, p)
print(f"+----------------------- POW -----------------------+")
print(f"{g}^x mod {p} == {target}")
print(f"+----------------------- POW -----------------------+")
try:
solution = int(input("x: "))
if solution == x:
return True
else:
return False
except:
return False
if (PoW() == False):
exit()
def sigterm_handler(_signo, _stack_frame):
os.system("kill -9 `pgrep qemu`")
os.system("kill -9 `pgrep adb`")
os.system("kill -9 `pgrep emulator`")
sys.exit(0)
signal.signal(signal.SIGTERM, sigterm_handler)
adb_port = 11000
emu_port = 11001
home = "/home/user"
apk_path = "/chall/app.apk"
ENV = {}
output = ["This website is the top one I have seen soo far", "This is just meh!!", "I would say quit your passion for web dev"]
def set_ENV(env):
env.update(os.environ)
env.update({
"ANDROID_ADB_SERVER_PORT" : f"{adb_port}",
"ANDROID_SERIAL": f"emulator-{emu_port}",
"ANDROID_SDK_ROOT": "/opt/android/sdk",
"ANDROID_SDK_HOME": home,
"ANDROID_PREFS_ROOT": home,
"ANDROID_EMULATOR_HOME": f"{home}/.android",
"ANDROID_AVD_HOME": f"{home}/.android/avd",
"JAVA_HOME": "/usr/lib/jvm/java-17-openjdk-amd64",
"PATH": "/opt/android/sdk/cmdline-tools/latest/bin:/opt/android/sdk/emulator:/opt/android/sdk/platform-tools:/bin:/usr/bin:" + os.environ.get("PATH", "")
})
def set_EMULATOR():
subprocess.call(
"avdmanager" +
" create avd" +
" --name 'Pixel_4_XL'" +
" --abi 'default/x86_64'" +
" --package 'system-images;android-30;default;x86_64'" +
" --device pixel_4_xl" +
" --force"+
" > /dev/null 2> /dev/null",
env=ENV,close_fds=True,shell=True)
return subprocess.Popen(
"emulator" +
" -avd Pixel_4_XL" +
" -no-cache" +
" -no-snapstorage" +
" -no-snapshot-save" +
" -no-snapshot-load" +
" -no-audio" +
" -no-window" +
" -no-snapshot" +
" -no-boot-anim" +
" -wipe-data" +
" -accel on" +
" -netdelay none" +
" -netspeed full" +
" -delay-adb" +
" -port {}".format(emu_port)+
" > /dev/null 2> /dev/null ",
env=ENV,close_fds=True,shell=True)
def ADB_Helper(args,var1=True):
return subprocess.run("adb {}".format(" ".join(args)),env=ENV,shell=True,close_fds=True,capture_output=var1).stdout
def install_apk():
ADB_Helper(["install","-r",apk_path])
def start_activity():
ADB_Helper(["shell","am","start","-n","bi0sctf.android.challenge/.MainActivity"])
def start_broadcast(action,extras=None):
ADB_Helper(["shell", "am", "broadcast", "-a", action, '--es', 'url',extras['url']])
def print_adb_logs():
logs = ADB_Helper(["logcat", "-d"])
for log in logs.decode("utf-8").strip().split("\n"):
print(log)
def push_file():
ADB_Helper(["root"])
ADB_Helper(["push", "/chall/flag", "/data/data/bi0sctf.android.challenge/"])
ADB_Helper(["unroot"])
def print_prompt(message):
print(message)
sys.stdout.flush()
try:
set_ENV(ENV)
print_prompt("+-------------------=============-------------------+")
print_prompt("+------------------ Website Rater ------------------+")
print_prompt("+-------------------=============-------------------+")
print_prompt("[+] Waking up the bot for testing your website...")
emulator = set_EMULATOR()
#print_adb_logs()
ADB_Helper(["wait-for-device"])
print_prompt("[+] Stats: Rated 100 websites today.")
install_apk()
print_prompt("[+] Status: Starting the analysing engine.")
start_activity()
push_file()
time.sleep(5)
print_prompt("[+] Enter your Website: ")
input_url = sys.stdin.readline().strip()
start_broadcast("bi0sctf.android.DATA", extras = {"url": input_url})
reply = output[randint(0, 2)]
print_prompt("[+] Opinion: " + reply)
time.sleep(10)
os.system("kill -9 `pgrep qemu`")
emulator.kill()
except:
print("nice try kid")
os.system("kill -9 `pgrep qemu`")
os.system("kill -9 `pgrep adb`")
emulator.kill()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/crypto/daisy_bell/chall.py | ctfs/bi0sCTF/2024/crypto/daisy_bell/chall.py | from Crypto.Util.number import *
from FLAG import flag
p = getPrime(1024)
q = getPrime(1024)
n = p*q
c = pow(bytes_to_long(flag), 65537, n)
print(f"{n = }")
print(f"{c = }")
print(f"{p>>545 = }")
print(f"{pow(q, -1, p) % 2**955 = }")
"""
n = 13588728652719624755959883276683763133718032506385075564663911572182122683301137849695983901955409352570565954387309667773401321714456342417045969608223003274884588192404087467681912193490842964059556524020070120310323930195454952260589778875740130941386109889075203869687321923491643408665507068588775784988078288075734265698139186318796736818313573197531378070122258446846208696332202140441601055183195303569747035132295102566133393090514109468599210157777972423137199252708312341156832737997619441957665736148319038440282486060886586224131974679312528053652031230440066166198113855072834035367567388441662394921517
c = 7060838742565811829053558838657804279560845154018091084158194272242803343929257245220709122923033772911542382343773476464462744720309804214665483545776864536554160598105614284148492704321209780195710704395654076907393829026429576058565918764797151566768444714762765178980092544794628672937881382544636805227077720169176946129920142293086900071813356620614543192022828873063643117868270870962617888384354361974190741650616048081060091900625145189833527870538922263654770794491259583457490475874562534779132633901804342550348074225239826562480855270209799871618945586788242205776542517623475113537574232969491066289349
p>>545 = 914008410449727213564879221428424249291351166169082040257173225209300987827116859791069006794049057028194309080727806930559540622366140212043574
pow(q, -1, p) % 2**955 = 233711553660002890828408402929574055694919789676036615130193612611783600781851865414087175789069599573385415793271613481055557735270487304894489126945877209821010875514064660591650207399293638328583774864637538897214896592130226433845320032466980448406433179399820207629371214346685408858
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/crypto/Katyushas_Campervan/chall.py | ctfs/bi0sCTF/2024/crypto/Katyushas_Campervan/chall.py | from Crypto.Util.number import *
from random import randint
from FLAG import flag
p = getPrime(1024)
q = getPrime(1024)
e = getPrime(132)
n = p*q
hint = pow(e, -1, (p-1)*(q-1))
hint %= p-1
hint %= 2**892
c = pow(3, int.from_bytes(flag), n**5) * pow(randint(0, n**5), n**4, n**5) % n**5
print(f"{n = }")
print(f"{e = }")
print(f"{c = }")
print(f"{hint = }")
"""
n = 9722343735487336242847355367175705096672092545117029199851527087227001665095112331406581010290318957921703096325328326862768861459201224096506317060919486835667369908780262880850949861734346363939614200227301344831209845565227637590016962469165064818450385339408084789219460490771570003649248250098125549751883777385917121014908647963900636814694225913533250242569263841750262192296795919177720443516042006972193940464844059718044438878017817432336475087436031866077325402373438547950481634275773767410248698596974769981162966656910136575149455523084473445761780201089182021418781347413453726696240548842411960178397
e = 5323153428600607366474827268153522064873
c = 9128106076400211790302891811252824557365859263295914819806672313027356017879597156259276057232557597614548050742418485365280305524694004426832069896531486671692562462063184624416012268348059935087037828161901243824582067161433586878141008884976330185561348052441637304755454643398179479215116505856245944555306345757777557395022121796068140566220391012921030768420736902592726104037200041403396506760483386523374366225161516294778224985920562226457769686733422726488624795847474711454397538514349555958637417188665977095558680525349235100286527905789576869572972662715040982208185436819557790062517857608731996417066519220133987864808243896151962316613504271341630230274953625158957103434031391582637694278277176886221304131078005240692954168656292222792833722555464070627220306776632641544334188357810067577550784029449834217848676080193960627138929032912578951880151284003878323853182114030012207949896373695734783631698004600675811512726913649141626146115066425891236975554237158682938964099745220780884079884347052906073216530490633243676915134831324804418410566989306886192743687590855529757605789691981493863292029273401139254934543448966341439303948513266699261650278938684067402860913507689842621595391519090227639907684629841162983852454124546030986411283762938101536264676221777904450717178547838152674410566294280937400196290368544481636850750666313771438253636667634601122561235018292316232335633111595474772273810349284893171480302604833719250453453781210093266339454843926482821341993360016434693250661347303203216948599305102121353574445652764255573536572077762409837628479280331295047290459975370026620838169978316921035609492162085052786943829915442906137063599836720584533200385074702683101049336194258783047318183521466098437420153628598968954236332678203275614402446435216223033804260963642393142002417568855964535316709986640977596845897721671783670070696907220894520837335160816494605130683705587464386202643385688263935088026204614056121745160246499509455752793089324629215884008499726564579763845757062068182946721730306128755414268910929410742220199282343421146810430121947827801171056425435942640932150535954546458772114121498557119913825127286832860975814307160175273154886250581960709573672488119996389986116735407178214281982766051391618187878672106737928646489671994503814871652107136752677107398141842179907758909246276653861569864776043204134345135427118784118473462309509988521112691717301811627018054555866015966545532047340607162395739241626423495285835953128906640802690450118128515355353064004001500408400502946613169130088974076348640048144323898309719773358195921400217897006053213222160549929081452233342133235896129215938411225808985658983546168950790935530147276940650250749733176085747359261765601961315474656996860052862883712183817510581189564814317141703276878435707070103680294131643312657511316154324112431403040644741385541670392956841467233434250239028068493523495064777560338358557481051862932373791428839612299758545173203569689546354726917373906408317003812591905738578665930636367780742749804408217333909091324486584514813293
hint = 27203100406560381632094006926903753857553395157680133688133088561775139188704414077278965969307544535945156850786509365882724900390893075998971604081115196824585813017775953048912421386424701714952968924065123981186929525951094688699758239739587719869990140385720389865
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/crypto/rr/chall.py | ctfs/bi0sCTF/2024/crypto/rr/chall.py | from Crypto.Util.number import *
from FLAG import flag
from random import randint
flag = bytes_to_long(flag)
n = 472993274721871037103726599805149366727531552333249750035977291933239067588481589544777397613192273114354221827196579379954069925604091911249655707080927769808587176515295614018992848517984372306879552247519117116110554431341268358177159108949791969262793325836353834899335531293329721598226413212541536002401507477776699642647348576111445702197483449777741566350285229621935507081895389023444249054515395783080003733803406382744631528246608154546123270319561514117323480441428953306734274538511770278887429407127143049023747710881993279361892937905382946820141513009017756811296722630617325141162244806884220212939955235410280899112731530527048274396186038160728562551536558223235783656985493518204710943916486379681906506757757594165379493317173050550893487151879681122510523721157284728808336110950008840684602353984682117748018347433177541603140491131603068512706893984834735290809952944273565203183330739252949245209529232254867201402656024997949207918675051941911990640248052951780195402390132237903538546705181463959793972284823588987652138458328270662652334799233015314673544813649692428544375538627858921763941533600553536579901589575693816746953261108022490849251974419402753031545629158199093099096735356165044275617408697
rr = 11898141078345200236264081467585899457224809417108457314508072413792599039332439547789237898270544336909458761754683941320649771736625000667170176071314483
ks = [randint(0, rr**(i+1)) for i in range(20)]
c1 = pow(sum(k*flag**i for i, k in enumerate(ks)), (1<<7)-1, n)
c2 = pow(flag, (1<<16)+1, n)
ks = [pow(69, k, rr**(i+2)) for i, k in enumerate(ks)]
print(f"{ks = }")
print(f"{c1 = }")
print(f"{c2 = }")
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/crypto/challengename/server.py | ctfs/bi0sCTF/2024/crypto/challengename/server.py | from ecdsa.ecdsa import Public_key, Private_key
from ecdsa import ellipticcurve
from hashlib import md5
import random
import os
import json
flag = open("flag", "rb").read()[:-1]
magic = os.urandom(16)
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = ###REDACTED###
b = ###REDACTED###
G = ###REDACTED###
q = G.order()
def bigsur(a,b):
a,b = [[a,b],[b,a]][len(a) < len(b)]
return bytes([i ^ j for i,j in zip(a,bytes([int(bin(int(b.hex(),16))[2:].zfill(len(f'{int(a.hex(), 16):b}'))[:len(a) - len(b)] + bin(int(b.hex(),16))[2:].zfill(len(bin(int(a.hex(), 16))[2:]))[:len(bin(int(a.hex(), 16))[2:]) - len(bin(int(b.hex(), 16))[2:])][i:i+8], 2) for i in range(0,len(bin(int(a.hex(), 16))[2:]) - len(bin(int(b.hex(), 16))[2:]),8)]) + b)])
def bytes_to_long(s):
return int.from_bytes(s, 'big')
def genkeys():
d = random.randint(1,q-1)
pubkey = Public_key(G, d*G)
return pubkey, Private_key(pubkey, d)
def sign(msg,nonce,privkey):
hsh = md5(msg).digest()
nunce = md5(bigsur(nonce,magic)).digest()
sig = privkey.sign(bytes_to_long(hsh), bytes_to_long(nunce))
return json.dumps({"msg": msg.hex(), "r": hex(sig.r), "s": hex(sig.s)})
def enc(privkey):
x = int(flag.hex(),16)
y = pow((x**3 + a*x + b) % p, (p+3)//4, p)
F = ellipticcurve.Point('--REDACTED--', x, y)
Q = F * privkey.secret_multiplier
return (int(Q.x()), int(Q.y()))
pubkey, privkey = genkeys()
print("Public key:",(int(pubkey.point.x()),int(pubkey.point.y())))
print("Encrypted flag:",enc(privkey))
nonces = set()
for _ in '01':
try:
msg = bytes.fromhex(input("Message: "))
nonce = bytes.fromhex(input("Nonce: "))
if nonce in nonces:
print("Nonce already used")
continue
nonces.add(nonce)
print(sign(msg,nonce,privkey))
except ValueError:
print("No hex?")
exit() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2024/web/bad_Notes/src/app.py | ctfs/bi0sCTF/2024/web/bad_Notes/src/app.py | from flask import Flask,render_template,request,session,redirect,Response
from flask_caching import Cache
import sqlite3
import os
from urllib.parse import urlsplit
import base64
import uuid
cache = Cache()
curr_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
UPLOAD_FOLDER = os.path.join(curr_dir,"user_uploads")
app.secret_key = str(uuid.uuid4())
app.config['MAX_CONTENT_LENGTH'] = 1 * 1000 * 1000
app.config['CACHE_TYPE'] = 'FileSystemCache'
app.config['CACHE_DIR'] = './caches'
app.config['CACHE_THRESHOLD'] = 100000
cache.init_app(app)
def getDB():
conn = sqlite3.connect(os.path.join(curr_dir,"docview.db"))
cursor = conn.cursor()
return cursor,conn
def isSecure(title):
D_extns = ['py','sh']
D_chars = ['*','?','[',']']
extension = title.split('.')[-1]
if(extension in D_extns):
return False
for char in title:
if char in D_chars:
return False
return True
@app.route('/',methods=["GET"])
def index():
return redirect("/login",code=302)
@app.route('/dashboard',methods=["GET"])
@cache.cached(timeout=1,query_string=True)
def home():
try:
if(session.get("loggedin") != "true"):
return redirect('/login',code=302)
file_path = os.path.join(UPLOAD_FOLDER,session.get('id'))
notes_list = os.listdir(file_path)
return render_template('dashboard.html',message=session.get('user'),notes=notes_list)
except Exception as e:
print(f"ERROR: {e}",flush=True)
return "You broke the server :(",400
@app.route('/login',methods=["GET","POST"])
def login():
try:
if(session.get("loggedin") == "true"):
return redirect('/dashboard',code=302)
if(request.method == "POST"):
user = request.form.get("username").strip()
passw = request.form.get("password").strip()
cursor,conn = getDB()
rows = cursor.execute("SELECT username,docid FROM accounts WHERE username = ? and password=?",(user,passw,)).fetchone()
if rows:
session["loggedin"] = "true"
session["user"] = user
session['id'] = rows[1]
file_path = os.path.join(UPLOAD_FOLDER,session.get('id'))
notes_list = os.listdir(file_path)
return render_template('dashboard.html',message=session.get("user"),notes=notes_list)
return render_template('login.html',message="Username/Password doesn't match")
return render_template('login.html')
except Exception as e:
print(f"ERROR: {e}",flush=True)
return "You broke the server :(",400
@app.route('/register',methods=["GET","POST"])
def register():
try:
if(request.method == "POST"):
user = request.form.get("username").strip()
passw = request.form.get("password").strip()
cursor,conn = getDB()
rows = cursor.execute("SELECT username FROM accounts WHERE username = ?",(user,)).fetchall()
if rows:
return render_template('register.html',message="user already exists")
direc_id = str(uuid.uuid4())
query = "INSERT INTO accounts VALUES(?,?,?)"
res = cursor.execute(query,(user,passw,direc_id))
conn.commit()
if(res):
os.mkdir(os.path.join(UPLOAD_FOLDER,direc_id))
return redirect('/login')
return render_template('register.html')
except Exception as e:
print(f"ERROR: {e}",flush=True)
return "You broke the server :(",400
@app.route('/makenote',methods=["POST"])
def upload():
try:
if(session.get("loggedin") != "true"):
return redirect('/login',code=302)
title = request.form.get('title')
content = base64.b64decode(request.form.get('content'))
if(title == None or title==""):
return render_template('dashboard.html',err_msg="title cannot be empty"),402
if(not isSecure(title)):
return render_template('dashboard.html',err_msg="invalid title")
file_path = os.path.join(UPLOAD_FOLDER,session.get('id'))
notes_list = os.listdir(file_path)
try:
file = os.path.join(file_path,title)
if('caches' in os.path.abspath(file)):
return render_template('dashboard.html',err_msg="invalid title",notes = notes_list),400
with open(file,"wb") as f:
f.write(content)
except Exception as e:
print(f"ERROR: {e}",flush=True)
return render_template('dashboard.html',err_msg="Some error occured",notes = notes_list),400
return redirect('/dashboard',code=302)
except Exception as e:
print(f"ERROR: {e}",flush=True)
return "You broke the server :(",400
@app.route('/viewnote/<title>',methods=["GET"])
def viewnote(title):
try:
if(session.get("loggedin") != "true"):
return redirect('/login',code=302)
cursor,conn = getDB()
res = cursor.execute("SELECT docid FROM accounts WHERE username=?",(session.get('user'),)).fetchone()
path = os.path.join(UPLOAD_FOLDER,res[0])
notes_list = os.listdir(path)
if(title in notes_list):
with open(os.path.join(path,title),"rb") as f:
return f.read()
return "The note doesn't exist/you dont have access",400
except Exception as e:
print(f"ERROR: {e}",flush=True)
return "You broke the server :(",400
@app.route("/logout",methods=["GET","POST"])
def logout():
session.pop('loggedin')
session.pop('id')
session.pop('user')
return redirect("/login",code=302)
if(__name__=="__main__"):
app.run(host="0.0.0.0",port=7000,debug=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2025/crypto/apna_AES/chall.py | ctfs/bi0sCTF/2025/crypto/apna_AES/chall.py | from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from os import urandom
import json
key = urandom(16)
iv1, iv2 = urandom(16), urandom(16)
class AES_APN:
def __init__(self):
self.key = key
def xor(self, a, b):
return bytes([x^y for x,y in zip(a,b)])
def encrypt(self, pt, iv1, iv2):
blocks = [pt[i:i+16] for i in range(0, len(pt), 16)]
ct = b""
state1, state2 = iv1, iv2
for i in range(len(blocks)):
block = self.xor(blocks[i], state1)
cipher = AES.new(self.key, AES.MODE_ECB)
enc = cipher.encrypt(block)
ct += self.xor(enc, state2)
state2 = block
state1 = enc
return ct
def decrypt(self, ct, iv1, iv2):
blocks = [ct[i:i+16] for i in range(0, len(ct), 16)]
pt = b""
state1, state2 = iv1, iv2
for i in range(len(blocks)):
block = self.xor(blocks[i], state2)
cipher = AES.new(self.key, AES.MODE_ECB)
dec = cipher.decrypt(block)
pt += self.xor(dec, state1)
state1 = block
state2 = dec
try:
unpad(pt, 16)
except:
return "Invalid padding"
else:
return "Valid padding"
def main():
s='''
+----------------------------------------------------------+
| ◦ APNA-AES v1.0 ◦ |
| > Decryption protocol active |
| > Encryption module: [offline] |
+----------------------------------------------------------+
'''
print(s)
custom = AES_APN()
message = open("message.txt","rb").read().strip()
enc_message = custom.encrypt(pad(message, 16), iv1, iv2)
token = {"IV1": iv1.hex(), "IV2": iv2.hex(), "ciphertext": enc_message.hex()}
print(f"Here is the encrypted message : {json.dumps(token)}")
while True:
try:
token = json.loads(input("Enter token: "))
ct = bytes.fromhex(token["ciphertext"])
iv1 = bytes.fromhex(token["IV1"])
iv2 = bytes.fromhex(token["IV2"])
pt = custom.decrypt(ct, iv1, iv2)
print("Decryption result: ", json.dumps({"result": pt}))
except:
exit(0)
if __name__ == "__main__":
try:
main()
except:
print("\nBYE")
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2025/crypto/...Like_PRNGS_to_Heaven/chall.py | ctfs/bi0sCTF/2025/crypto/...Like_PRNGS_to_Heaven/chall.py | from tinyec.ec import SubGroup, Curve
from RMT import R_MT19937_32bit as special_random
from decor import HP, death_message, menu_box, title_drop
from Crypto.Util.number import bytes_to_long as b2l
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random.random import getrandbits
from hashlib import sha256
from json import loads
import sys
import os
from secret import FLAG
CORE = 0xb4587f9bd72e39c54d77b252f96890f2347ceff5cb6231dfaadb94336df08dfd
class _1000_THR_Signing_System:
def __init__(self):
# secp256k1
self.p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
self.a = 0x0000000000000000000000000000000000000000000000000000000000000000
self.b = 0x0000000000000000000000000000000000000000000000000000000000000007
self.Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
self.Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
self.n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
self.h = 0x1
subgroup = SubGroup(self.p, (self.Gx, self.Gy), self.n, self.h)
self.curve = Curve(self.a, self.b, subgroup, name="CustomCurve")
self.cinit = 0
self.d = self.privkey_gen()
self.P = self.curve.g
self.Q = self.d * self.P
self.Max_Sec = special_random(getrandbits(32))
def sec_real_bits(self,bits: int) -> int:
if bits % 32 != 0:
raise ValueError("Bit length must be a multiple of 32")
exp = bits // 32
x = self.Max_Sec.get_num() ** exp
cyc_exhausted = 0
while x.bit_length() != bits:
x = self.Max_Sec.get_num() ** exp
cyc_exhausted += 1
return (x, cyc_exhausted)
@staticmethod
def real_bits(bits) -> int:
x = getrandbits(bits)
while x.bit_length() != bits:
x = getrandbits(bits)
return x
@staticmethod
def supreme_RNG(seed: int, length: int = 10):
while True:
str_seed = str(seed) if len(str(seed)) % 2 == 0 else '0' + str(seed)
sqn = str(seed**2)
mid = len(str_seed) >> 1
start = (len(sqn) >> 1) - mid
end = (len(sqn) >> 1) + mid
yield sqn[start : end].zfill(length)
seed = int(sqn[start : end])
def restart_level(self):
print("S T A R T I N G R O U T I N E . . .\n")
self.Max_Sec = special_random(getrandbits(32))
self.d = self.privkey_gen()
self.P = self.curve.g
self.Q = self.d * self.P
def sign(self, msg: bytes) -> tuple:
k, n1, n2, cycles = self.full_noncense_gen() # 全くナンセンスですが、日本語では
kG = k * self.P
r = kG.x % self.n
k = k % self.n
Hmsg = sha256()
Hmsg.update(msg)
s = ((b2l(Hmsg.digest()) + r * self.d) * pow(k, -1, self.n)) % self.n
return (r, s, n1, n2, cycles)
def partial_noncense_gen(self,bits: int, sub_bits: int, shift: int) -> int:
term = self.real_bits(bits)
_and = self.real_bits(bits - sub_bits)
equation = term ^ ((term << shift) & _and)
return (term,_and,equation)
def full_noncense_gen(self) -> tuple:
k_m1 = self.real_bits(24)
k_m2 = self.real_bits(24)
k_m3 = self.real_bits(69)
k_m4 = self.real_bits(30)
k_, cycle_1 = self.sec_real_bits(32)
_k, cycle_2 = self.sec_real_bits(32)
benjamin1, and1, eq1 = self.partial_noncense_gen(32, 16, 16)
benjamin2, and2, eq2 = self.partial_noncense_gen(32 ,16 ,16)
const_list = [k_m1, (benjamin1 >> 24 & 0xFF), k_m2, (benjamin1 >> 16 & 0xFF) , k_, (benjamin1 >> 8 & 0xFF), k_m3, (benjamin1 & 0xFF), k_m4, (benjamin2 >> 24 & 0xFFF), _k]
shift_list = [232, 224, 200, 192, 160, 152, 83, 75, 45, 33, 0]
n1 = [and1, eq1]
n2 = [and2, eq2]
cycles = [cycle_1, cycle_2]
noncense = 0
for const, shift in zip(const_list, shift_list):
noncense += const << shift
return noncense, n1, n2, cycles
def privkey_gen(self) -> int:
simple_lcg = lambda x: (x * 0xeccd4f4fea74c2b057dafe9c201bae658da461af44b5f04dd6470818429e043d + 0x8aaf15) % self.n
if not self.cinit:
RNG_seed = simple_lcg(CORE)
self.n_gen = self.supreme_RNG(RNG_seed)
RNG_gen = next(self.n_gen)
self.cinit += 1
else:
RNG_gen = next(self.n_gen)
p1 = hex(self.real_bits(108))
p2 = hex(self.real_bits(107))[2:]
priv_key = p1 + RNG_gen[:5] + p2 + RNG_gen[5:]
return int(priv_key, 16)
def gen_encrypted_flag(self) -> tuple:
sha2 = sha256()
sha2.update(str(self.d).encode('ascii'))
key = sha2.digest()[:16]
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(FLAG, 16))
return (ciphertext.hex(), iv.hex())
def _dead_coin_params(self) -> tuple:
base = 2
speed = getrandbits(128)
feedbacker_parry = int(next(self.n_gen))
style_bonus = feedbacker_parry ^ (feedbacker_parry >> 5)
power = pow(base, style_bonus, speed)
return (power, speed, feedbacker_parry)
def deadcoin_verification(self, tries):
if tries < 3:
print(f"Successfully perform a {"\33[33m"}deadcoin{"\33[0m"} and perform a {"\33[34m"}feedbacker{"\33[0m"} parry for getting {"\33[1;91m"}BLOOD{"\33[0m"} to survive.\n")
power, speed, feedbacker_parry = self._dead_coin_params()
print(f"Calculated power and speed for the number - {tries+1} deadcoin: {power, speed}")
try:
action_code = int(input("Action code: "))
if action_code == feedbacker_parry:
blood = self.Max_Sec.get_num()
print(f"[+ FISTFUL OF DOLLAR]")
print(f"Here's some {"\33[1;91m"}BLOOD{"\33[0m"} - ID: {blood}")
return True
else:
print("Missed.")
except:
print("Invalid action code")
else:
print("You're done.")
return False
class _1000_THR_EARTHMOVER:
def __init__(self):
self.Boss = _1000_THR_Signing_System()
def get_encrypted_flag(self):
ciphertext, iv = self.Boss.gen_encrypted_flag()
return {"ciphertext": ciphertext,"iv": iv}
def perform_deadcoin(self, tries):
return self.Boss.deadcoin_verification(tries)
def call_the_signer(self):
msg = input("What do you wish to speak? ").encode()
r, s, n1, n2, cycles = self.Boss.sign(msg)
return {"r": r, "s": s, "nonce_gen_consts": [n1, n2], "heat_gen": cycles}
def level_restart(self):
self.Boss.restart_level()
def level_quit(self):
sys.exit()
def main():
from time import sleep
LEVEL = _1000_THR_EARTHMOVER()
tries = 0
title_drop()
V1 = HP(100,100, "V1", HP.color_red)
while True:
try:
menu_box()
print(f'\n{V1}')
move = loads(input("\nExpecting Routine in JSON format: "))
if "event" not in move:
print({"Error": "Unrecognised event"})
continue
v1_action = move["event"]
survive = V1.check(v1_action)
if not survive:
death_message()
break
if v1_action == "get_encrypted_flag":
print(LEVEL.get_encrypted_flag())
V1.update(V1.current_health-50)
elif v1_action == "perform_deadcoin":
verify = LEVEL.perform_deadcoin(tries)
tries += 1
if verify:
V1.update(V1.current_health+20)
elif v1_action == "call_the_signer":
print(LEVEL.call_the_signer())
V1.update(V1.current_health-20)
elif v1_action == "level_restart":
LEVEL.level_restart()
V1.update(100)
elif v1_action == "level_quit":
LEVEL.level_quit()
else:
print({"Error": "Unrecognised V1 action"})
except Exception as e:
print({"Error": str(e)})
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2025/crypto/...Like_PRNGS_to_Heaven/decor.py | ctfs/bi0sCTF/2025/crypto/...Like_PRNGS_to_Heaven/decor.py | # Place for the brainrot
class HP:
bars = 20
remaining_health_symbol = "█"
lost_health_symbol = "░"
color_green = "\033[92m"
color_yellow = "\33[33m"
color_red = "\033[91m"
color_default = "\033[0m"
def __init__(self, max_health, current_health, name, health_color):
self.max_health = max_health
self.current_health = current_health
self.remaining_health_bars = round(self.current_health / self.max_health * HP.bars)
self.lost_health_bars = HP.bars - self.remaining_health_bars
self.health_color = health_color
self.name = name
def update(self, current):
self.current_health = current
self.remaining_health_bars = round(self.current_health / self.max_health * HP.bars)
self.lost_health_bars = HP.bars - self.remaining_health_bars
def check(self, move):
move_cost_dict = {"get_encrypted_flag": 50, "perform_deadcoin" : 0, "call_the_signer" : 20, "level_restart" : 0, "level_quit" : 0}
if (self.current_health - move_cost_dict[move]) <= 0 :
return False
return True
def __repr__(self):
return f"Your HP : ❤ {'\33[0;101m'}{self.current_health}{'\33[0m'}"f"{self.health_color}{self.remaining_health_bars * self.remaining_health_symbol}"f"{self.lost_health_bars * self.lost_health_symbol}{HP.color_default}"
def title_drop():
from time import sleep
title_drop = f'''{"\33[1;91m"}
██╗ ██╗██╗ ██████╗ ██╗ ███████╗███╗ ██╗ ██████╗███████╗ ██╗ ██╗ ███████╗███╗ ██╗ ██████╗ ██████╗ ██████╗ ███████╗
██║ ██║██║██╔═══██╗██║ ██╔════╝████╗ ██║██╔════╝██╔════╝ ██╔╝ ██╔╝ ██╔════╝████╗ ██║██╔════╝██╔═══██╗██╔══██╗██╔════╝
██║ ██║██║██║ ██║██║ █████╗ ██╔██╗ ██║██║ █████╗ ██╔╝ ██╔╝ █████╗ ██╔██╗ ██║██║ ██║ ██║██████╔╝█████╗
╚██╗ ██╔╝██║██║ ██║██║ ██╔══╝ ██║╚██╗██║██║ ██╔══╝ ██╔╝ ██╔╝ ██╔══╝ ██║╚██╗██║██║ ██║ ██║██╔══██╗██╔══╝
╚████╔╝ ██║╚██████╔╝███████╗███████╗██║ ╚████║╚██████╗███████╗ ██╔╝ ██╔╝ ███████╗██║ ╚████║╚██████╗╚██████╔╝██║ ██║███████╗
╚═══╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═══╝ ╚═════╝╚══════╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝
██╗ ██╗██╗ ██╗███████╗ ██████╗ ██████╗ ███╗ ██╗ ██████╗ ███████╗ ████████╗ ██████╗ ██╗ ██╗███████╗ █████╗ ██╗ ██╗███████╗███╗ ██╗
██║ ██║██║ ██╔╝██╔════╝ ██╔══██╗██╔══██╗████╗ ██║██╔════╝ ██╔════╝ ╚══██╔══╝██╔═══██╗ ██║ ██║██╔════╝██╔══██╗██║ ██║██╔════╝████╗ ██║
██║ ██║█████╔╝ █████╗ ██████╔╝██████╔╝██╔██╗ ██║██║ ███╗███████╗ ██║ ██║ ██║ ███████║█████╗ ███████║██║ ██║█████╗ ██╔██╗ ██║
██║ ██║██╔═██╗ ██╔══╝ ██╔═══╝ ██╔══██╗██║╚██╗██║██║ ██║╚════██║ ██║ ██║ ██║ ██╔══██║██╔══╝ ██╔══██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║
██╗██╗██╗███████╗██║██║ ██╗███████╗ ██║ ██║ ██║██║ ╚████║╚██████╔╝███████║ ██║ ╚██████╔╝ ██║ ██║███████╗██║ ██║ ╚████╔╝ ███████╗██║ ╚████║
╚═╝╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝
{"\33[0m"}'''
print(title_drop)
sleep(1.25)
print("S T A R T I N G R O U T I N E . . .\n")
sleep(1)
print(f'{"\33[1;91m"}WARNING: INTRUDER DETECTED')
sleep(0.25)
print(f'-- LIFESTEAL ENABLED --{"\33[0m"}')
sleep(1)
def menu_box():
rainbow_colors = ["\33[91m", "\33[33m", "\33[92m","\33[34m", "\33[36m", "\33[95m"]
text = "[+ FISTFUL OF DOLLAR]"
italy = '\x1B[3m'
r_c = "\33[0m"
colored_text = ''.join(f"{rainbow_colors[i % len(rainbow_colors)]}{italy}{char}{r_c}" for i, char in enumerate(text))
l_pre = "║ 2 - perform_deadcoin << "
l_suf = "║"
width = 54
text_width = width - len(l_pre) - len(l_suf)
padd = text_width - len(text)
res = colored_text + ' ' * padd
box = f"""
╔════════════════════════════════════════════════════╗
║ 1 - get_encrypted_flag ║
{l_pre}{res}{l_suf}
║ 3 - call_the_signer ║
║ 4 - level_restart ║
║ 5 - level_quit ║
╚════════════════════════════════════════════════════╝
"""
print(box)
def death_message():
print('''
▗▖ ▗▖▗▄▖ ▗▖ ▗▖ ▗▄▖ ▗▄▄▖ ▗▄▄▄▖ ▗▄▄▄ ▗▄▄▄▖ ▗▄▖ ▗▄▄▄
▝▚▞▘▐▌ ▐▌▐▌ ▐▌ ▐▌ ▐▌▐▌ ▐▌▐▌ ▐▌ █ ▐▌ ▐▌ ▐▌▐▌ █
▐▌ ▐▌ ▐▌▐▌ ▐▌ ▐▛▀▜▌▐▛▀▚▖▐▛▀▀▘ ▐▌ █ ▐▛▀▀▘▐▛▀▜▌▐▌ █
▐▌ ▝▚▄▞▘▝▚▄▞▘ ▐▌ ▐▌▐▌ ▐▌▐▙▄▄▖ ▐▙▄▄▀ ▐▙▄▄▖▐▌ ▐▌▐▙▄▄▀
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣤⣤⠴⠶⠶⠶⠶⠶⠶⠶⠶⢤⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⣤⠶⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠛⠶⣤⡀⠀⠀⠀⠀⠀
⠀⠀⢀⡴⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠛⢷⡄⠀⠀⠀
⠀⣰⠟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣦⠀⠀
⢰⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣧⠀
⣿⠀⠀⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡄⠀⢹⡄
⡏⠀⢰⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠀⢸⡇
⣿⠀⠘⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡟⠀⢸⡇
⢹⡆⠀⢹⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⠃⠀⣾⠀
⠈⢷⡀⢸⡇⠀⢀⣠⣤⣶⣶⣶⣤⡀⠀⠀⠀⠀⠀⢀⣠⣶⣶⣶⣶⣤⣄⠀⠀⣿⠀⣼⠃⠀
⠀⠈⢷⣼⠃⠀⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿⣿⣿⡇⠀⢸⡾⠃⠀⠀
⠀⠀⠈⣿⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⠁⠀⠀⠀⠀⢹⣿⣿⣿⣿⣿⣿⣿⠃⠀⢸⡇⠀⠀⠀
⠀⠀⠀⣿⠀⠀⠘⢿⣿⣿⣿⣿⡿⠃⠀⢠⠀⣄⠀⠀⠙⢿⣿⣿⣿⡿⠏⠀⠀⢘⡇⠀⠀⠀
⠀⠀⠀⢻⡄⠀⠀⠀⠈⠉⠉⠀⠀⠀⣴⣿⠀⣿⣷⠀⠀⠀⠀⠉⠁⠀⠀⠀⠀⢸⡇⠀⠀⠀
⠀⠀⠀⠈⠻⣄⡀⠀⠀⠀⠀⠀⠀⢠⣿⣿⠀⣿⣿⣇⠀⠀⠀⠀⠀⠀⠀⢀⣴⠟⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠘⣟⠳⣦⡀⠀⠀⠀⠸⣿⡿⠀⢻⣿⡟⠀⠀⠀⠀⣤⡾⢻⡏⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⢻⡄⢻⠻⣆⠀⠀⠀⠈⠀⠀⠀⠈⠀⠀⠀⢀⡾⢻⠁⢸⠁⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⢸⡇⠀⡆⢹⠒⡦⢤⠤⡤⢤⢤⡤⣤⠤⡔⡿⢁⡇⠀⡿⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠘⡇⠀⢣⢸⠦⣧⣼⣀⡇⢸⢀⣇⣸⣠⡷⢇⢸⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⣷⠀⠈⠺⣄⣇⢸⠉⡏⢹⠉⡏⢹⢀⣧⠾⠋⠀⢠⡇⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠻⣆⠀⠀⠀⠈⠉⠙⠓⠚⠚⠋⠉⠁⠀⠀⠀⢀⡾⠁⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠙⢷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡴⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⠳⠶⠦⣤⣤⣤⡤⠶⠞⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
''')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2025/crypto/...Like_PRNGS_to_Heaven/RMT.py | ctfs/bi0sCTF/2025/crypto/...Like_PRNGS_to_Heaven/RMT.py | class R_MT19937_32bit:
def __init__(self, seed=0):
self.f = 1812433253
(self.w, self.n, self.m, self.r) = (32, 624, 397, 31)
(self.u, self.s, self.t, self.l)= (11, 7, 15, 18)
(self.a, self.b, self.c) = (0x9908b0df, 0x9d2c5680, 0xefc60000)
(self.lower, self.upper, self.d) = (0x7fffffff, 0x80000000, 0xffffffff)
self.MT = [0 for i in range(self.n)]
self.seedMT(seed)
def seedMT(self, seed):
num = seed
self.index = self.n
for _ in range(0,51):
num = 69069 * num + 1
g_prev = num
for i in range(self.n):
g = 69069 * g_prev + 1
self.MT[i] = g & self.d
g_prev = g
return self.MT
def twist(self):
for i in range(0, self.n):
x = (self.MT[i] & self.upper) + (self.MT[(i + 1) % self.n] & self.lower)
xA = x >> 1
if (x % 2) != 0:
xA = xA ^ self.a
self.MT[i] = self.MT[(i + self.m) % self.n] ^ xA
self.index = 0
def get_num(self):
if self.index >= self.n:
self.twist()
y = self.MT[self.index]
y = y ^ ((y >> self.u) & self.d)
y = y ^ ((y << self.s) & self.b)
y = y ^ ((y << self.t) & self.c)
y = y ^ (y >> self.l)
self.index += 1
return y & ((1 << self.w) - 1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2025/crypto/Veiled_XOR/chall.py | ctfs/bi0sCTF/2025/crypto/Veiled_XOR/chall.py | from Crypto.Util.number import getPrime, bytes_to_long
n = (p := getPrime(1024)) * (q := getPrime(1024))
print(f"n : {n}\nc : {pow(bytes_to_long(flag), 65537, n)}\nVeil XOR: {p ^ int(bin(q)[2:][::-1], 2)}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/bi0sCTF/2025/forensic/Bombardino_Exfilrino/pow.py | ctfs/bi0sCTF/2025/forensic/Bombardino_Exfilrino/pow.py | import re
def solve_discrete_log(equation_text):
pattern = r'(\d+)\^x mod (\d+) == (\d+)'
match = re.search(pattern, equation_text)
if not match:
print("Could not parse equation. Expected format: base^x mod modulus == target")
return None
base = int(match.group(1))
modulus = int(match.group(2))
target = int(match.group(3))
print(f"Solving: {base}^x mod {modulus} == {target}")
for x in range(1, 1000000):
if pow(base, x, modulus) == target:
print(f"x = {x}")
return x
if x % 100000 == 0:
print(f"Checked up to x = {x}...")
print("No solution found")
return None
solve_discrete_log("your_equation_here")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/crypto/Alkaloid_Stream/gen.py | ctfs/perfectblue/pbctf/2021/crypto/Alkaloid_Stream/gen.py | #!/usr/bin/env python3
import random
from flag import flag
def keygen(ln):
# Generate a linearly independent key
arr = [ 1 << i for i in range(ln) ]
for i in range(ln):
for j in range(i):
if random.getrandbits(1):
arr[j] ^= arr[i]
for i in range(ln):
for j in range(i):
if random.getrandbits(1):
arr[ln - 1 - j] ^= arr[ln - 1 - i]
return arr
def gen_keystream(key):
ln = len(key)
# Generate some fake values based on the given key...
fake = [0] * ln
for i in range(ln):
for j in range(ln // 3):
if i + j + 1 >= ln:
break
fake[i] ^= key[i + j + 1]
# Generate the keystream
res = []
for i in range(ln):
t = random.getrandbits(1)
if t:
res.append((t, [fake[i], key[i]]))
else:
res.append((t, [key[i], fake[i]]))
# Shuffle!
random.shuffle(res)
keystream = [v[0] for v in res]
public = [v[1] for v in res]
return keystream, public
def xor(a, b):
return [x ^ y for x, y in zip(a, b)]
def recover_keystream(key, public):
st = set(key)
keystream = []
for v0, v1 in public:
if v0 in st:
keystream.append(0)
elif v1 in st:
keystream.append(1)
else:
assert False, "Failed to recover the keystream"
return keystream
def bytes_to_bits(inp):
res = []
for v in inp:
res.extend(list(map(int, format(v, '08b'))))
return res
def bits_to_bytes(inp):
res = []
for i in range(0, len(inp), 8):
res.append(int(''.join(map(str, inp[i:i+8])), 2))
return bytes(res)
flag = bytes_to_bits(flag)
key = keygen(len(flag))
keystream, public = gen_keystream(key)
assert keystream == recover_keystream(key, public)
enc = bits_to_bytes(xor(flag, keystream))
print(enc.hex())
print(public)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/crypto/GoodHash/main.py | ctfs/perfectblue/pbctf/2021/crypto/GoodHash/main.py | #!/usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Util.number import *
from flag import flag
import json
import os
import string
ACCEPTABLE = string.ascii_letters + string.digits + string.punctuation + " "
class GoodHash:
def __init__(self, v=b""):
self.key = b"goodhashGOODHASH"
self.buf = v
def update(self, v):
self.buf += v
def digest(self):
cipher = AES.new(self.key, AES.MODE_GCM, nonce=self.buf)
enc, tag = cipher.encrypt_and_digest(b"\0" * 32)
return enc + tag
def hexdigest(self):
return self.digest().hex()
if __name__ == "__main__":
token = json.dumps({"token": os.urandom(16).hex(), "admin": False})
token_hash = GoodHash(token.encode()).hexdigest()
print(f"Body: {token}")
print(f"Hash: {token_hash}")
inp = input("> ")
if len(inp) > 64 or any(v not in ACCEPTABLE for v in inp):
print("Invalid input :(")
exit(0)
inp_hash = GoodHash(inp.encode()).hexdigest()
if token_hash == inp_hash:
try:
token = json.loads(inp)
if token["admin"] == True:
print("Wow, how did you find a collision?")
print(f"Here's the flag: {flag}")
else:
print("Nice try.")
print("Now you need to set the admin value to True")
except:
print("Invalid input :(")
else:
print("Invalid input :(")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/crypto/Steroid_Stream/gen.py | ctfs/perfectblue/pbctf/2021/crypto/Steroid_Stream/gen.py | #!/usr/bin/env python3
import random
from flag import flag
def keygen(ln):
# Generate a linearly independent key
arr = [ 1 << i for i in range(ln) ]
for i in range(ln):
for j in range(i):
if random.getrandbits(1):
arr[j] ^= arr[i]
for i in range(ln):
for j in range(i):
if random.getrandbits(1):
arr[ln - 1 - j] ^= arr[ln - 1 - i]
return arr
def gen_keystream(key):
ln = len(key)
assert ln > 50
# Generate some fake values based on the given key...
fake = [0] * ln
for i in range(ln - ln // 3):
arr = list(range(i + 1, ln))
random.shuffle(arr)
for j in arr[:ln // 3]:
fake[i] ^= key[j]
# Generate the keystream
res = []
for i in range(ln):
t = random.getrandbits(1)
if t:
res.append((t, [fake[i], key[i]]))
else:
res.append((t, [key[i], fake[i]]))
# Shuffle!
random.shuffle(res)
keystream = [v[0] for v in res]
public = [v[1] for v in res]
return keystream, public
def xor(a, b):
return [x ^ y for x, y in zip(a, b)]
def recover_keystream(key, public):
st = set(key)
keystream = []
for v0, v1 in public:
if v0 in st:
keystream.append(0)
elif v1 in st:
keystream.append(1)
else:
assert False, "Failed to recover the keystream"
return keystream
def bytes_to_bits(inp):
res = []
for v in inp:
res.extend(list(map(int, format(v, '08b'))))
return res
def bits_to_bytes(inp):
res = []
for i in range(0, len(inp), 8):
res.append(int(''.join(map(str, inp[i:i+8])), 2))
return bytes(res)
flag = bytes_to_bits(flag)
key = keygen(len(flag))
keystream, public = gen_keystream(key)
assert keystream == recover_keystream(key, public)
enc = bits_to_bytes(xor(flag, keystream))
print(enc.hex())
print(public)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/crypto/Yet_Another_PRNG/gen.py | ctfs/perfectblue/pbctf/2021/crypto/Yet_Another_PRNG/gen.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import random
import os
from flag import flag
def urand(b):
return int.from_bytes(os.urandom(b), byteorder='big')
class PRNG:
def __init__(self):
self.m1 = 2 ** 32 - 107
self.m2 = 2 ** 32 - 5
self.m3 = 2 ** 32 - 209
self.M = 2 ** 64 - 59
rnd = random.Random(b'rbtree')
self.a1 = [rnd.getrandbits(20) for _ in range(3)]
self.a2 = [rnd.getrandbits(20) for _ in range(3)]
self.a3 = [rnd.getrandbits(20) for _ in range(3)]
self.x = [urand(4) for _ in range(3)]
self.y = [urand(4) for _ in range(3)]
self.z = [urand(4) for _ in range(3)]
def out(self):
o = (2 * self.m1 * self.x[0] - self.m3 * self.y[0] - self.m2 * self.z[0]) % self.M
self.x = self.x[1:] + [sum(x * y for x, y in zip(self.x, self.a1)) % self.m1]
self.y = self.y[1:] + [sum(x * y for x, y in zip(self.y, self.a2)) % self.m2]
self.z = self.z[1:] + [sum(x * y for x, y in zip(self.z, self.a3)) % self.m3]
return o.to_bytes(8, byteorder='big')
if __name__ == "__main__":
prng = PRNG()
hint = b''
for i in range(12):
hint += prng.out()
print(hint.hex())
assert len(flag) % 8 == 0
stream = b''
for i in range(len(flag) // 8):
stream += prng.out()
out = bytes([x ^ y for x, y in zip(flag, stream)])
print(out.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/crypto/Yet_Another_RSA/gen.py | ctfs/perfectblue/pbctf/2021/crypto/Yet_Another_RSA/gen.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import random
def genPrime():
while True:
a = random.getrandbits(256)
b = random.getrandbits(256)
if b % 3 == 0:
continue
p = a ** 2 + 3 * b ** 2
if p.bit_length() == 512 and p % 3 == 1 and isPrime(p):
return p
def add(P, Q, mod):
m, n = P
p, q = Q
if p is None:
return P
if m is None:
return Q
if n is None and q is None:
x = m * p % mod
y = (m + p) % mod
return (x, y)
if n is None and q is not None:
m, n, p, q = p, q, m, n
if q is None:
if (n + p) % mod != 0:
x = (m * p + 2) * inverse(n + p, mod) % mod
y = (m + n * p) * inverse(n + p, mod) % mod
return (x, y)
elif (m - n ** 2) % mod != 0:
x = (m * p + 2) * inverse(m - n ** 2, mod) % mod
return (x, None)
else:
return (None, None)
else:
if (m + p + n * q) % mod != 0:
x = (m * p + (n + q) * 2) * inverse(m + p + n * q, mod) % mod
y = (n * p + m * q + 2) * inverse(m + p + n * q, mod) % mod
return (x, y)
elif (n * p + m * q + 2) % mod != 0:
x = (m * p + (n + q) * 2) * inverse(n * p + m * q + r, mod) % mod
return (x, None)
else:
return (None, None)
def power(P, a, mod):
res = (None, None)
t = P
while a > 0:
if a % 2:
res = add(res, t, mod)
t = add(t, t, mod)
a >>= 1
return res
def random_pad(msg, ln):
pad = bytes([random.getrandbits(8) for _ in range(ln - len(msg))])
return msg + pad
p, q = genPrime(), genPrime()
N = p * q
phi = (p ** 2 + p + 1) * (q ** 2 + q + 1)
print(f"N: {N}")
d = getPrime(400)
e = inverse(d, phi)
k = (e * d - 1) // phi
print(f"e: {e}")
to_enc = input("> ").encode()
ln = len(to_enc)
print(f"Length: {ln}")
pt1, pt2 = random_pad(to_enc[: ln // 2], 127), random_pad(to_enc[ln // 2 :], 127)
M = (bytes_to_long(pt1), bytes_to_long(pt2))
E = power(M, e, N)
print(f"E: {E}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/web/WYSIWYG/web/app.py | ctfs/perfectblue/pbctf/2021/web/WYSIWYG/web/app.py | #!/usr/bin/env python3
import os
import socket
from flask import Flask
from flask import render_template
from flask import request
from flask_recaptcha import ReCaptcha
app = Flask(__name__)
app.config["RECAPTCHA_SITE_KEY"] = os.environ["RECAPTCHA_SITE_KEY"]
app.config["RECAPTCHA_SECRET_KEY"] = os.environ["RECAPTCHA_SECRET_KEY"]
recaptcha = ReCaptcha(app)
@app.route("/tinymce/")
def tinymce():
return render_template("tinymce.html")
@app.route("/froala/")
def froala():
return render_template("froala.html")
@app.route("/ckeditor/")
def ckeditor():
return render_template("ckeditor.html")
@app.route("/", methods=["GET", "POST"])
def main():
if request.method == "GET":
return render_template("main.html")
else:
if recaptcha.verify():
text = request.form.get("text")
if not text:
return "The text parameter is required", 422
s = socket.create_connection(("bot", 8000))
s.sendall(text.encode())
resp = s.recv(100)
s.close()
return resp.decode(), 200
else:
return "Invalid captcha", 422
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/web/Vault/web/app.py | ctfs/perfectblue/pbctf/2021/web/Vault/web/app.py | #!/usr/bin/env python3
import os
import socket
from flask import Flask
from flask import render_template
from flask import request
from flask_caching import Cache
from flask_recaptcha import ReCaptcha
app = Flask(__name__)
app.config["RECAPTCHA_SITE_KEY"] = os.environ["RECAPTCHA_SITE_KEY"]
app.config["RECAPTCHA_SECRET_KEY"] = os.environ["RECAPTCHA_SECRET_KEY"]
recaptcha = ReCaptcha(app)
cache = Cache(config={'CACHE_TYPE': 'FileSystemCache', 'CACHE_DIR':'/tmp/vault', 'CACHE_DEFAULT_TIMEOUT': 300})
cache.init_app(app)
@app.route("/<path:vault_key>", methods=["GET", "POST"])
def vault(vault_key):
parts = list(filter(lambda s: s.isdigit(), vault_key.split("/")))
level = len(parts)
if level > 15:
return "Too deep", 422
if not cache.get("vault"):
cache.set("vault", {})
main_vault = cache.get("vault")
c = main_vault
for v in parts:
c = c.setdefault(v, {})
values = c.setdefault("values", [])
if level > 8 and request.method == "POST":
value = request.form.get("value")
value = value[0:50]
values.append(value)
cache.set("vault", main_vault)
return render_template("vault.html", values = values, level = level)
@app.route("/", methods=["GET", "POST"])
def main():
if request.method == "GET":
return render_template("main.html")
else:
if recaptcha.verify():
url = request.form.get("url")
if not url:
return "The url parameter is required", 422
if not url.startswith("https://") and not url.startswith("http://"):
return "The url parameter is invalid", 422
s = socket.create_connection(("bot", 8000))
s.sendall(url.encode())
resp = s.recv(100)
s.close()
return resp.decode(), 200
else:
return "Invalid captcha", 422
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2021/web/TBDXSS/app/app.py | ctfs/perfectblue/pbctf/2021/web/TBDXSS/app/app.py | from flask import Flask, request, session, jsonify, Response
import json
import redis
import random
import os
import time
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY", "tops3cr3t")
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
)
HOST = os.environ.get("CHALL_HOST", "localhost:5000")
r = redis.Redis(host='redis')
@app.after_request
def add_XFrame(response):
response.headers['X-Frame-Options'] = "DENY"
return response
@app.route('/change_note', methods=['POST'])
def add():
session['note'] = request.form['data']
session.modified = True
return "Changed succesfully"
@app.route("/do_report", methods=['POST'])
def do_report():
cur_time = time.time()
ip = request.headers.get('X-Forwarded-For').split(",")[-2].strip() #amazing google load balancer
last_time = r.get('time.'+ip)
last_time = float(last_time) if last_time is not None else 0
time_diff = cur_time - last_time
if time_diff > 6:
r.rpush('submissions', request.form['url'])
r.setex('time.'+ip, 60, cur_time)
return "submitted"
return "rate limited"
@app.route('/note')
def notes():
print(session)
return """
<body>
{}
</body>
""".format(session['note'])
@app.route("/report", methods=['GET'])
def report():
return """
<head>
<title>Notes app</title>
</head>
<body>
<h3><a href="/note">Get Note</a> <a href="/">Change Note</a> <a href="/report">Report Link</a></h3>
<hr>
<h3>Please report suspicious URLs to admin</h3>
<form action="/do_report" id="reportform" method=POST>
URL: <input type="text" name="url" placeholder="URL">
<br>
<input type="submit" value="submit">
</form>
<br>
</body>
"""
@app.route('/')
def index():
return """
<head>
<title>Notes app</title>
</head>
<body>
<h3><a href="/note">Get Note</a> <a href="/">Change Note</a> <a href="/report">Report Link</a></h3>
<hr>
<h3> Add a note </h3>
<form action="/change_note" id="noteform" method=POST>
<textarea rows="10" cols="100" name="data" form="noteform" placeholder="Note's content"></textarea>
<br>
<input type="submit" value="submit">
</form>
<br>
</body>
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/pwn/babygc/upload.py | ctfs/perfectblue/pbctf/2023/pwn/babygc/upload.py | from pwn import *
import sys
if len(sys.argv) < 2:
print("provide path to js source")
raise Exception
r = remote("babygc.chal.perfect.blue", 1337)
f = open(sys.argv[1],"r")
src = f.read()
f.close()
r.sendlineafter("Your js file size:",str(len(src)))
r.sendlineafter(":",src)
r.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/pwn/babygc/wrapper.py | ctfs/perfectblue/pbctf/2023/pwn/babygc/wrapper.py | #!/usr/bin/python3 -u
# (script from hitcon..)
import atexit
import os
import random
import signal
import string
import subprocess
import sys
import tempfile
MAX_INPUT = 100 * 1024
TIMEOUT = 120
JSC_PATH = "/home/user/jsc"
LIB_PATH = "/home/user/lib/"
def main():
size = None
try:
print(f"Your js file size: ( MAX: {MAX_INPUT} bytes ) ", end='')
size = int(sys.stdin.readline())
except:
print("Not a valid size !")
return
if size > MAX_INPUT:
print("Too large !")
return
print("Input your js file:")
src = sys.stdin.read(size)
tmp = tempfile.mkdtemp(dir="/tmp", prefix=bytes.hex(os.urandom(8)))
full_path = os.path.join(tmp, "exp.js")
with open(full_path, "w") as f:
f.write(src)
cmd = f"LD_LIBRARY_PATH={LIB_PATH} {JSC_PATH} {full_path}"
try:
subprocess.check_call(cmd, stderr=sys.stdout, shell=True)
except subprocess.CalledProcessError as e:
print("Execution error:")
print(f"Return code: {e.returncode}")
if __name__ == '__main__':
try:
main()
except Exception as e:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-4/Cipher.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-4/Cipher.py | from GF import GF
SBOX, INV_SBOX = dict(), dict()
for i in range(3 ** 5):
v = GF(23) + (GF(0) if i == 0 else GF(i).inverse())
SBOX[GF(i)] = v
INV_SBOX[v] = GF(i)
class BlockCipher:
def __init__(self, key: bytes, rnd: int):
assert len(key) == 9
sks = [GF(b) for b in key]
for i in range(rnd * 9):
sks.append(sks[-1] + SBOX[sks[-9]])
self.subkeys = [sks[i:i+9] for i in range(0, (rnd + 1) * 9, 9)]
self.rnd = rnd
def _add_key(self, l1, l2):
return [x + y for x, y in zip(l1, l2)]
def _sub_key(self, l1, l2):
return [x - y for x, y in zip(l1, l2)]
def _sub(self, l):
return [SBOX[x] for x in l]
def _sub_inv(self, l):
return [INV_SBOX[x] for x in l]
def _shift(self, b):
return [
b[0], b[1], b[2],
b[4], b[5], b[3],
b[8], b[6], b[7]
]
def _shift_inv(self, b):
return [
b[0], b[1], b[2],
b[5], b[3], b[4],
b[7], b[8], b[6]
]
def _mix(self, b):
b = b[:] # Copy
for i in range(3):
x = GF(7) * b[i] + GF(2) * b[3 + i] + b[6 + i]
y = GF(2) * b[i] + b[3 + i] + GF(7) * b[6 + i]
z = b[i] + GF(7) * b[3 + i] + GF(2) * b[6 + i]
b[i], b[3 + i], b[6 + i] = x, y, z
return b
def _mix_inv(self, b):
b = b[:] # Copy
for i in range(3):
x = GF(86) * b[i] + GF(222) * b[3 + i] + GF(148) * b[6 + i]
y = GF(222) * b[i] + GF(148) * b[3 + i] + GF(86) * b[6 + i]
z = GF(148) * b[i] + GF(86) * b[3 + i] + GF(222) * b[6 + i]
b[i], b[3 + i], b[6 + i] = x, y, z
return b
def encrypt(self, inp: bytes):
assert len(inp) == 9
b = [GF(x) for x in inp]
b = self._add_key(b, self.subkeys[0])
for i in range(self.rnd):
b = self._sub(b)
b = self._shift(b)
if i < self.rnd - 1:
b = self._mix(b)
b = self._add_key(b, self.subkeys[i + 1])
return bytes([x.to_int() for x in b])
def decrypt(self, inp: bytes):
assert len(inp) == 9
b = [GF(x) for x in inp]
for i in reversed(range(self.rnd)):
b = self._sub_key(b, self.subkeys[i + 1])
if i < self.rnd - 1:
b = self._mix_inv(b)
b = self._shift_inv(b)
b = self._sub_inv(b)
b = self._sub_key(b, self.subkeys[0])
return bytes([x.to_int() for x in b])
if __name__ == "__main__":
import random
key = bytes(random.randint(0, 242) for i in range(9))
cipher = BlockCipher(key, 4)
for _ in range(100):
pt = bytes(random.randint(0, 242) for i in range(9))
ct = cipher.encrypt(pt)
pt_ = cipher.decrypt(ct)
assert pt == pt_
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-4/task.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-4/task.py | #!/usr/bin/env python3
import os
import signal
from Cipher import BlockCipher
def handler(_signum, _frame):
print("Time out!")
exit(0)
def get_key():
key = b''
while len(key) < 9:
b = os.urandom(1)
if b[0] < 243:
key += b
return key
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(60)
key = get_key()
with open('flag', 'rb') as f:
flag = f.read()
flag += b'\x00' * ((-len(flag)) % 9)
flag_cipher = BlockCipher(key, 20)
enc_flag = b''
for i in range(0, len(flag), 9):
enc_flag += flag_cipher.encrypt(flag[i:i+9])
print(f"enc_flag: {enc_flag.hex()}")
cipher = BlockCipher(key, 4)
while True:
inp = bytes.fromhex(input("> "))
assert len(inp) < (3 ** 7)
assert all(b < 243 for b in inp)
enc = b''
for i in range(0, len(inp), 9):
enc += cipher.encrypt(inp[i:i+9])
print(f"Result: {enc.hex()}")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-4/GF.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-4/GF.py | class GF:
def __init__(self, value):
if type(value) == int:
self.value = [(value // (3 ** i)) % 3 for i in range(5)]
elif type(value) == list and len(value) == 5:
self.value = value
else:
assert False, "Wrong input to the constructor"
def __str__(self):
return f"GF({self.to_int()})"
def __repr__(self):
return str(self)
def __hash__(self):
return hash(tuple(self.value))
def __eq__(self, other):
assert type(other) == GF
return self.value == other.value
def __add__(self, other):
assert type(other) == GF
return GF([(x + y) % 3 for x, y in zip(self.value, other.value)])
def __sub__(self, other):
assert type(other) == GF
return GF([(x - y) % 3 for x, y in zip(self.value, other.value)])
def __mul__(self, other):
assert type(other) == GF
arr = [0 for _ in range(9)]
for i in range(5):
for j in range(5):
arr[i + j] = (arr[i + j] + self.value[i] * other.value[j]) % 3
# Modulus: x^5 + 2*x + 1
for i in range(8, 4, -1):
arr[i - 4] = (arr[i - 4] - 2 * arr[i]) % 3
arr[i - 5] = (arr[i - 5] - arr[i]) % 3
return GF(arr[:5])
def __pow__(self, other):
assert type(other) == int
base, ret = self, GF(1)
while other > 0:
if other & 1:
ret = ret * base
other >>= 1
base = base * base
return ret
def inverse(self):
return self ** 241
def __div__(self, other):
assert type(other) == GF
return self * other.inverse()
def to_int(self):
return sum([self.value[i] * (3 ** i) for i in range(5)])
if __name__ == "__main__":
assert GF(3) * GF(3) == GF(9)
assert GF(9) * GF(27) == GF(5)
assert GF(5).inverse() == GF(240) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/My_ECC_Service/challenge.py | ctfs/perfectblue/pbctf/2023/crypto/My_ECC_Service/challenge.py | from Crypto.Util.number import inverse
from hashlib import sha256
import os
import signal
class NonceGenerator:
def __init__(self):
self.state = os.urandom(10)
self.db = {}
def gen(self):
self.state = sha256(self.state + b'wow').digest()[:10]
key = sha256(self.state).digest()[:8]
self.db[key] = self.state
return int.from_bytes(self.state, 'big'), key
def get(self, key: str):
if key not in self.db:
print("Wrong key :(")
exit(0)
return int.from_bytes(self.db[key], 'big')
class ECPoint:
def __init__(self, point, mod):
self.x = point[0]
self.y = point[1]
self.mod = mod
def inf(self):
return ECPoint((0, 0), self.mod)
def _is_inf(self):
return self.x == 0 and self.y == 0
def __eq__(self, other):
assert self.mod == other.mod
return self.x == other.x and self.y == other.y
def __add__(self, other):
assert self.mod == other.mod
P, Q = self, other
if P._is_inf() and Q._is_inf():
return self.inf()
elif P._is_inf():
return Q
elif Q._is_inf():
return P
if P == Q:
lam = (3 * P.x**2 - 3) * inverse(2 * P.y, self.mod) % self.mod
elif P.x == Q.x:
return self.inf()
else:
lam = (Q.y - P.y) * inverse(Q.x - P.x, self.mod) % self.mod
x = (lam**2 - P.x - Q.x) % self.mod
y = (lam * (P.x - x) - P.y) % self.mod
return ECPoint((x, y), self.mod)
def __rmul__(self, other: int):
base, ret = self, self.inf()
while other > 0:
if other & 1:
ret = ret + base
other >>= 1
base = base + base
return ret
class MyECCService:
BASE_POINT = (2, 3)
MODS = [
942340315817634793955564145941,
743407728032531787171577862237,
738544131228408810877899501401,
1259364878519558726929217176601,
1008010020840510185943345843979,
1091751292145929362278703826843,
793740294757729426365912710779,
1150777367270126864511515229247,
763179896322263629934390422709,
636578605918784948191113787037,
1026431693628541431558922383259,
1017462942498845298161486906117,
734931478529974629373494426499,
934230128883556339260430101091,
960517171253207745834255748181,
746815232752302425332893938923,
]
def __init__(self):
self.nonce_gen = NonceGenerator()
def get_x(self, nonce: int) -> bytes:
ret = b""
for mod in self.MODS:
p = ECPoint(self.BASE_POINT, mod)
x = (nonce * p).x
ret += x.to_bytes(13, "big")
return ret
def gen(self) -> bytes:
nonce, key = self.nonce_gen.gen()
x = self.get_x(nonce)
return b"\x02\x03" + key + x
def verify(self, inp: bytes) -> bool:
assert len(inp) == 218
nonce = self.nonce_gen.get(inp[2:10])
self.BASE_POINT = (inp[0], inp[1])
x = self.get_x(nonce)
return inp[10:] == x
def handler(_signum, _frame):
print("Time out!")
exit(0)
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
service = MyECCService()
for _ in range(100):
service.gen()
while True:
inp = input("> ")
if inp == "G":
payload = service.gen()
print(f"Payload: {payload.hex()}")
elif inp == "V":
payload = bytes.fromhex(input("Payload: "))
result = service.verify(payload)
print(f"Result: {result}")
elif inp == "P":
payload = bytes.fromhex(input("Payload: "))
answer = service.gen()
if payload == answer:
with open("flag.txt", "r") as f:
print(f.read())
else:
print("Wrong :(")
exit(0)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/My_ECC_Service2/challenge.py | ctfs/perfectblue/pbctf/2023/crypto/My_ECC_Service2/challenge.py | from Crypto.Util.number import inverse
from hashlib import sha256
import os
import signal
class NonceGenerator:
def __init__(self, count):
self.state = os.urandom(16)
self.count = count
self.db = {}
def gen(self):
new_state = b''
res = []
last = 0
for i in range(self.count - 1):
hsh = sha256(self.state + i.to_bytes(1, 'big')).digest()[:10]
new_state += hsh
v = int.from_bytes(hsh, 'big')
last ^= v
res.append(v)
hsh = last.to_bytes(10, 'big')
new_state += hsh
res.append(last)
self.state = new_state
key = sha256(self.state).digest()[:8]
self.db[key] = res
return res, key
def get(self, key: str):
if key not in self.db:
print("Wrong key :(")
exit(0)
return self.db[key]
class ECPoint:
def __init__(self, point, mod):
self.x = point[0]
self.y = point[1]
self.mod = mod
def inf(self):
return ECPoint((0, 0), self.mod)
def _is_inf(self):
return self.x == 0 and self.y == 0
def __eq__(self, other):
assert self.mod == other.mod
return self.x == other.x and self.y == other.y
def __add__(self, other):
assert self.mod == other.mod
P, Q = self, other
if P._is_inf() and Q._is_inf():
return self.inf()
elif P._is_inf():
return Q
elif Q._is_inf():
return P
if P == Q:
lam = (3 * P.x**2 - 3) * inverse(2 * P.y, self.mod) % self.mod
elif P.x == Q.x:
return self.inf()
else:
lam = (Q.y - P.y) * inverse(Q.x - P.x, self.mod) % self.mod
x = (lam**2 - P.x - Q.x) % self.mod
y = (lam * (P.x - x) - P.y) % self.mod
return ECPoint((x, y), self.mod)
def __rmul__(self, other: int):
base, ret = self, self.inf()
while other > 0:
if other & 1:
ret = ret + base
other >>= 1
base = base + base
return ret
class MyECCService:
BASE_POINT = (2, 3)
MODS = [
942340315817634793955564145941,
743407728032531787171577862237,
738544131228408810877899501401,
1259364878519558726929217176601,
1008010020840510185943345843979,
1091751292145929362278703826843,
793740294757729426365912710779,
1150777367270126864511515229247,
763179896322263629934390422709,
636578605918784948191113787037,
1026431693628541431558922383259,
1017462942498845298161486906117,
734931478529974629373494426499,
934230128883556339260430101091,
960517171253207745834255748181,
746815232752302425332893938923,
]
def __init__(self):
self.nonce_gen = NonceGenerator(len(self.MODS))
def get_x(self, nonces: list[int]) -> bytes:
ret = b""
for nonce, mod in zip(nonces, self.MODS):
p = ECPoint(self.BASE_POINT, mod)
x = (nonce * p).x
ret += x.to_bytes(13, "big")
return ret
def gen(self) -> bytes:
nonces, key = self.nonce_gen.gen()
x = self.get_x(nonces)
return b"\x02\x03" + key + x
def verify(self, inp: bytes) -> bool:
assert len(inp) == 218
nonces = self.nonce_gen.get(inp[2:10])
self.BASE_POINT = (inp[0], inp[1])
x = self.get_x(nonces)
return inp[10:] == x
def handler(_signum, _frame):
print("Time out!")
exit(0)
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(300)
service = MyECCService()
for _ in range(100):
service.gen()
while True:
inp = input("> ")
if inp == "G":
payload = service.gen()
print(f"Payload: {payload.hex()}")
elif inp == "V":
payload = bytes.fromhex(input("Payload: "))
result = service.verify(payload)
print(f"Result: {result}")
elif inp == "P":
payload = bytes.fromhex(input("Payload: "))
answer = service.gen()
if payload == answer:
with open("flag.txt", "r") as f:
print(f.read())
else:
print("Wrong :(")
exit(0)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-5/Cipher.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-5/Cipher.py | from GF import GF
SBOX, INV_SBOX = dict(), dict()
for i in range(3 ** 5):
v = GF(23) + (GF(0) if i == 0 else GF(i).inverse())
SBOX[GF(i)] = v
INV_SBOX[v] = GF(i)
class BlockCipher:
def __init__(self, key: bytes, rnd: int):
assert len(key) == 9
sks = [GF(b) for b in key]
for i in range(rnd * 9):
sks.append(sks[-1] + SBOX[sks[-9]])
self.subkeys = [sks[i:i+9] for i in range(0, (rnd + 1) * 9, 9)]
self.rnd = rnd
def _add_key(self, l1, l2):
return [x + y for x, y in zip(l1, l2)]
def _sub_key(self, l1, l2):
return [x - y for x, y in zip(l1, l2)]
def _sub(self, l):
return [SBOX[x] for x in l]
def _sub_inv(self, l):
return [INV_SBOX[x] for x in l]
def _shift(self, b):
return [
b[0], b[1], b[2],
b[4], b[5], b[3],
b[8], b[6], b[7]
]
def _shift_inv(self, b):
return [
b[0], b[1], b[2],
b[5], b[3], b[4],
b[7], b[8], b[6]
]
def _mix(self, b):
b = b[:] # Copy
for i in range(3):
x = GF(7) * b[i] + GF(2) * b[3 + i] + b[6 + i]
y = GF(2) * b[i] + b[3 + i] + GF(7) * b[6 + i]
z = b[i] + GF(7) * b[3 + i] + GF(2) * b[6 + i]
b[i], b[3 + i], b[6 + i] = x, y, z
return b
def _mix_inv(self, b):
b = b[:] # Copy
for i in range(3):
x = GF(86) * b[i] + GF(222) * b[3 + i] + GF(148) * b[6 + i]
y = GF(222) * b[i] + GF(148) * b[3 + i] + GF(86) * b[6 + i]
z = GF(148) * b[i] + GF(86) * b[3 + i] + GF(222) * b[6 + i]
b[i], b[3 + i], b[6 + i] = x, y, z
return b
def encrypt(self, inp: bytes):
assert len(inp) == 9
b = [GF(x) for x in inp]
b = self._add_key(b, self.subkeys[0])
for i in range(self.rnd):
b = self._sub(b)
b = self._shift(b)
if i < self.rnd - 1:
b = self._mix(b)
b = self._add_key(b, self.subkeys[i + 1])
return bytes([x.to_int() for x in b])
def decrypt(self, inp: bytes):
assert len(inp) == 9
b = [GF(x) for x in inp]
for i in reversed(range(self.rnd)):
b = self._sub_key(b, self.subkeys[i + 1])
if i < self.rnd - 1:
b = self._mix_inv(b)
b = self._shift_inv(b)
b = self._sub_inv(b)
b = self._sub_key(b, self.subkeys[0])
return bytes([x.to_int() for x in b])
if __name__ == "__main__":
import random
key = bytes(random.randint(0, 242) for i in range(9))
cipher = BlockCipher(key, 5)
for _ in range(100):
pt = bytes(random.randint(0, 242) for i in range(9))
ct = cipher.encrypt(pt)
pt_ = cipher.decrypt(ct)
assert pt == pt_
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-5/task.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-5/task.py | #!/usr/bin/env python3
import os
import signal
from Cipher import BlockCipher
def handler(_signum, _frame):
print("Time out!")
exit(0)
def get_key():
key = b''
while len(key) < 9:
b = os.urandom(1)
if b[0] < 243:
key += b
return key
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(60)
key = get_key()
with open('flag', 'rb') as f:
flag = f.read()
flag += b'\x00' * ((-len(flag)) % 9)
flag_cipher = BlockCipher(key, 20)
enc_flag = b''
for i in range(0, len(flag), 9):
enc_flag += flag_cipher.encrypt(flag[i:i+9])
print(f"enc_flag: {enc_flag.hex()}")
cipher = BlockCipher(key, 5)
while True:
inp = bytes.fromhex(input("> "))
assert len(inp) < (3 ** 7)
assert all(b < 243 for b in inp)
enc = b''
for i in range(0, len(inp), 9):
enc += cipher.encrypt(inp[i:i+9])
print(f"Result: {enc.hex()}")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-5/GF.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-5/GF.py | class GF:
def __init__(self, value):
if type(value) == int:
self.value = [(value // (3 ** i)) % 3 for i in range(5)]
elif type(value) == list and len(value) == 5:
self.value = value
else:
assert False, "Wrong input to the constructor"
def __str__(self):
return f"GF({self.to_int()})"
def __repr__(self):
return str(self)
def __hash__(self):
return hash(tuple(self.value))
def __eq__(self, other):
assert type(other) == GF
return self.value == other.value
def __add__(self, other):
assert type(other) == GF
return GF([(x + y) % 3 for x, y in zip(self.value, other.value)])
def __sub__(self, other):
assert type(other) == GF
return GF([(x - y) % 3 for x, y in zip(self.value, other.value)])
def __mul__(self, other):
assert type(other) == GF
arr = [0 for _ in range(9)]
for i in range(5):
for j in range(5):
arr[i + j] = (arr[i + j] + self.value[i] * other.value[j]) % 3
# Modulus: x^5 + 2*x + 1
for i in range(8, 4, -1):
arr[i - 4] = (arr[i - 4] - 2 * arr[i]) % 3
arr[i - 5] = (arr[i - 5] - arr[i]) % 3
return GF(arr[:5])
def __pow__(self, other):
assert type(other) == int
base, ret = self, GF(1)
while other > 0:
if other & 1:
ret = ret * base
other >>= 1
base = base * base
return ret
def inverse(self):
return self ** 241
def __div__(self, other):
assert type(other) == GF
return self * other.inverse()
def to_int(self):
return sum([self.value[i] * (3 ** i) for i in range(5)])
if __name__ == "__main__":
assert GF(3) * GF(3) == GF(9)
assert GF(9) * GF(27) == GF(5)
assert GF(5).inverse() == GF(240) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-0/Cipher.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-0/Cipher.py | from GF import GF
SBOX, INV_SBOX = dict(), dict()
for i in range(3 ** 5):
v = GF(23) + (GF(0) if i == 0 else GF(i).inverse())
SBOX[GF(i)] = v
INV_SBOX[v] = GF(i)
class BlockCipher:
def __init__(self, key: bytes, rnd: int):
assert len(key) == 9
sks = [GF(b) for b in key]
for i in range(rnd * 9):
sks.append(sks[-1] + SBOX[sks[-9]])
self.subkeys = [sks[i:i+9] for i in range(0, (rnd + 1) * 9, 9)]
self.rnd = rnd
def _add_key(self, l1, l2):
return [x + y for x, y in zip(l1, l2)]
def _sub_key(self, l1, l2):
return [x - y for x, y in zip(l1, l2)]
def _sub(self, l):
return [SBOX[x] for x in l]
def _sub_inv(self, l):
return [INV_SBOX[x] for x in l]
def _shift(self, b):
return [
b[0], b[1], b[2],
b[4], b[5], b[3],
b[8], b[6], b[7]
]
def _shift_inv(self, b):
return [
b[0], b[1], b[2],
b[5], b[3], b[4],
b[7], b[8], b[6]
]
def _mix(self, b):
b = b[:] # Copy
for i in range(3):
x = GF(7) * b[i] + GF(2) * b[3 + i] + b[6 + i]
y = GF(2) * b[i] + b[3 + i] + GF(7) * b[6 + i]
z = b[i] + GF(7) * b[3 + i] + GF(2) * b[6 + i]
b[i], b[3 + i], b[6 + i] = x, y, z
return b
def _mix_inv(self, b):
b = b[:] # Copy
for i in range(3):
x = GF(86) * b[i] + GF(222) * b[3 + i] + GF(148) * b[6 + i]
y = GF(222) * b[i] + GF(148) * b[3 + i] + GF(86) * b[6 + i]
z = GF(148) * b[i] + GF(86) * b[3 + i] + GF(222) * b[6 + i]
b[i], b[3 + i], b[6 + i] = x, y, z
return b
def encrypt(self, inp: bytes):
assert len(inp) == 9
b = [GF(x) for x in inp]
b = self._add_key(b, self.subkeys[0])
for i in range(self.rnd):
b = self._sub(b)
b = self._shift(b)
if i < self.rnd - 1:
b = self._mix(b)
b = self._add_key(b, self.subkeys[i + 1])
return bytes([x.to_int() for x in b])
def decrypt(self, inp: bytes):
assert len(inp) == 9
b = [GF(x) for x in inp]
for i in reversed(range(self.rnd)):
b = self._sub_key(b, self.subkeys[i + 1])
if i < self.rnd - 1:
b = self._mix_inv(b)
b = self._shift_inv(b)
b = self._sub_inv(b)
b = self._sub_key(b, self.subkeys[0])
return bytes([x.to_int() for x in b])
if __name__ == "__main__":
import random
key = bytes(random.randint(0, 242) for i in range(9))
cipher = BlockCipher(key, 4)
for _ in range(100):
pt = bytes(random.randint(0, 242) for i in range(9))
ct = cipher.encrypt(pt)
pt_ = cipher.decrypt(ct)
assert pt == pt_
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/crypto/Blocky-0/task.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-0/task.py | #!/usr/bin/env python3
import hashlib
import os
import signal
from Cipher import BlockCipher
from GF import GF
def handler(_signum, _frame):
print("Time out!")
exit(0)
def get_random_block():
block = b''
while len(block) < 9:
b = os.urandom(1)
if b[0] < 243:
block += b
return block
def get_mac(pt):
mac = hashlib.sha256(pt).digest()[:9]
return bytes([x % 243 for x in mac])
def pad(pt):
mac = get_mac(pt)
v = 9 - len(pt) % 9
return pt + bytes([v] * v) + mac
def unpad(pt):
if len(pt) < 18 or len(pt) % 9 != 0:
return
pt, mac = pt[:-9], pt[-9:]
if not (1 <= pt[-1] <= 9):
return
pt = pt[:-pt[-1]]
if mac == get_mac(pt):
return pt
def add(a, b):
return bytes([(GF(x) + GF(y)).to_int() for x, y in zip(a, b)])
def sub(a, b):
return bytes([(GF(x) - GF(y)).to_int() for x, y in zip(a, b)])
def main():
signal.signal(signal.SIGALRM, handler)
signal.alarm(60)
key = get_random_block()
cipher = BlockCipher(key, 20)
while True:
inp = input("> ")
if inp == 'E':
inp = input("Input (in hex): ")
inp = bytes.fromhex(inp)
assert len(inp) < 90
assert all(b < 243 for b in inp)
if inp == 'gimmeflag':
print("Result: None")
continue
pt = pad(inp)
iv = get_random_block()
enc = iv
for i in range(0, len(pt), 9):
t = add(pt[i:i+9], iv)
iv = cipher.encrypt(t)
enc += iv
print(f"Result: {enc.hex()}")
elif inp == 'D':
inp = input("Input (in hex): ")
inp = bytes.fromhex(inp)
assert len(inp) < 108
assert all(b < 243 for b in inp)
iv, ct = inp[:9], inp[9:]
dec = b''
for i in range(0, len(ct), 9):
t = cipher.decrypt(ct[i:i+9])
dec += sub(t, iv)
iv = ct[i:i+9]
pt = unpad(dec)
if pt == b'gimmeflag':
with open('flag', 'r') as f:
flag = f.read()
print(flag)
exit(0)
elif pt:
print(f"Result: {pt.hex()}")
else:
print("Result: None")
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/perfectblue/pbctf/2023/crypto/Blocky-0/GF.py | ctfs/perfectblue/pbctf/2023/crypto/Blocky-0/GF.py | class GF:
def __init__(self, value):
if type(value) == int:
self.value = [(value // (3 ** i)) % 3 for i in range(5)]
elif type(value) == list and len(value) == 5:
self.value = value
else:
assert False, "Wrong input to the constructor"
def __str__(self):
return f"GF({self.to_int()})"
def __repr__(self):
return str(self)
def __hash__(self):
return hash(tuple(self.value))
def __eq__(self, other):
assert type(other) == GF
return self.value == other.value
def __add__(self, other):
assert type(other) == GF
return GF([(x + y) % 3 for x, y in zip(self.value, other.value)])
def __sub__(self, other):
assert type(other) == GF
return GF([(x - y) % 3 for x, y in zip(self.value, other.value)])
def __mul__(self, other):
assert type(other) == GF
arr = [0 for _ in range(9)]
for i in range(5):
for j in range(5):
arr[i + j] = (arr[i + j] + self.value[i] * other.value[j]) % 3
# Modulus: x^5 + 2*x + 1
for i in range(8, 4, -1):
arr[i - 4] = (arr[i - 4] - 2 * arr[i]) % 3
arr[i - 5] = (arr[i - 5] - arr[i]) % 3
return GF(arr[:5])
def __pow__(self, other):
assert type(other) == int
base, ret = self, GF(1)
while other > 0:
if other & 1:
ret = ret * base
other >>= 1
base = base * base
return ret
def inverse(self):
return self ** 241
def __div__(self, other):
assert type(other) == GF
return self * other.inverse()
def to_int(self):
return sum([self.value[i] * (3 ** i) for i in range(5)])
if __name__ == "__main__":
assert GF(3) * GF(3) == GF(9)
assert GF(9) * GF(27) == GF(5)
assert GF(5).inverse() == GF(240) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/web/Makima/cdn/app.py | ctfs/perfectblue/pbctf/2023/web/Makima/cdn/app.py | from flask import *
import requests
app = Flask(__name__)
@app.errorhandler(requests.exceptions.MissingSchema)
@app.errorhandler(requests.exceptions.InvalidSchema)
def bad_schema(e):
return 'no HTTP/S?', 400
@app.errorhandler(requests.exceptions.ConnectionError)
def no_connect(e):
print("CONNECT ERR")
return 'I did not understand that URL', 400
@app.route("/cdn/<path:url>")
def cdn(url):
mimes = ["image/png", "image/jpeg", "image/gif", "image/webp"]
r = requests.get(url, stream=True)
if r.headers["Content-Type"] not in mimes:
print("BAD MIME")
return "????", 400
img_resp = make_response(r.raw.read(), 200)
for header in r.headers:
if header == "Date" or header == "Server":
continue
img_resp.headers[header] = r.headers[header]
return img_resp
if __name__ == "__main__":
app.run(debug=False, port=8081)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2023/web/XSPS/app/app.py | ctfs/perfectblue/pbctf/2023/web/XSPS/app/app.py | from flask import Flask, request, session, jsonify, Response, make_response, g
import json
import redis
import random
import os
import binascii
import time
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY", "tops3cr3t")
app.config.update(
SESSION_COOKIE_SECURE=False,
SESSION_COOKIE_HTTPONLY=True,
# SESSION_COOKIE_SAMESITE='Lax',
)
HOST = os.environ.get("CHALL_HOST", "localhost:5000")
r = redis.Redis(host='redis')
@app.route("/do_report", methods=['POST'])
def do_report():
cur_time = time.time()
ip = request.headers.get('X-Forwarded-For').split(",")[-2].strip() #amazing google load balancer
last_time = r.get('time.'+ip)
last_time = float(last_time) if last_time is not None else 0
time_diff = cur_time - last_time
if time_diff > 6:
r.rpush('submissions', request.form['url'])
r.setex('time.'+ip, 60, cur_time)
return "submitted"
return "rate limited"
@app.route("/report", methods=['GET'])
def report():
return """
<head>
<title>Notes app</title>
</head>
<body>
<h3><a href="/note">Get Note</a> <a href="/">Change Note</a> <a href="/report">Report Link</a></h3>
<hr>
<h3>Please report suspicious URLs to admin</h3>
<form action="/do_report" id="reportform" method=POST>
URL: <input type="text" name="url" placeholder="URL">
<br>
<input type="submit" value="submit">
</form>
<br>
</body>
"""
@app.before_request
def rand_nonce():
g.nonce = binascii.b2a_hex(os.urandom(15)).decode()
@app.after_request
def add_CSP(response):
response.headers['Content-Security-Policy'] = f"default-src 'self'; script-src 'nonce-{g.nonce}'"
return response
@app.route('/add_note', methods=['POST'])
def add():
if 'notes' not in session:
session['notes'] = {}
session['notes'][request.form['name']] = request.form['data']
if 'highlight_note' in request.form and request.form['highlight_note'] == "YES":
session['highlighted_note'] = request.form['name']
session.modified = True
return "Changed succesfully"
@app.route('/notes')
def notes():
if 'notes' not in session:
return []
return [X for X in session['notes']]
@app.route("/highlighted_note")
def highlighted_note():
if 'highlighted_note' not in session:
return {'name':False}
return session['highlighted_note']
@app.route('/note/<path:name>')
def get_note(name):
if 'notes' not in session:
return ""
if name not in session['notes']:
return ""
return session['notes'][name]
@app.route('/static/<path:filename>')
def static_file(filename):
return send_from_directory('static', filename)
@app.route('/')
def index():
return f"""
<head>
<title>Notes app</title>
</head>
<body>
<script nonce='{g.nonce}' src="/static/js/main.js"></script>
<h3><a href="/report">Report Link</a></h3>
<hr>
<h3> Highlighted Note </h3>
<div id="highlighted"></div>
<hr>
<h3> Add a note </h3>
<form action="/add_note" id="noteform" method=POST>
<input type=text name="name" placeholder="Note's name">
<br>
<br>
<textarea rows="10" cols="100" name="data" form="noteform" placeholder="Note's content"></textarea>
<br>
<br>
<input type="checkbox" name="highlight_note" value="YES">
<label for="vehicle1">Highlight Note</label><br>
<br>
<input type="submit" value="submit">
</form>
<hr>
<h3>Search Note</h3>
<a id=search_result></a>
<input id='search_content' type=text name="name" placeholder="Content to search">
<input id='search_open' type="checkbox" name="open_after" value="YES">
<label for="open">Open</label><br>
<br>
<input id='search_button' type="submit" value="submit">
</body>
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/perfectblue/pbctf/2020/blacklist/genfiles.py | ctfs/perfectblue/pbctf/2020/blacklist/genfiles.py | import string, random, os, sys
pool = string.ascii_letters + string.digits
random.seed(open('/dev/random', 'rb').read(16))
flag_parts = ['F', 'f', 'L', 'l', 'A', 'a', 'G', 'g', '70', '102', '76', '108',
'65', '97', '71', '103', '0x46', '0x66', '0x4c', '0x6c', '0x41', '0x61',
'0x47', '0x67', 'fl', 'la', 'ag', 'fla', 'lag', 'flag', 'FLAG', 'FLA',
'LAG', 'FL', 'LA', 'AG']
def randint(x):
return random.randint(0, x - 1)
def randstr():
msg = ''
for i in range(25):
msg += pool[randint(len(pool))]
return msg
def main():
if len(sys.argv) != 2:
print('Usage: {} FLAG_VALUE'.format(sys.argv[0]))
exit(1)
flag = open(sys.argv[1], 'r').read().strip()
def flatten(aval, bval, cval):
return aval * 50 + bval * 5 + cval
base = 'flag_dir'
os.mkdir(base)
flagpos = randint(len(flag_parts) * 50)
for a in range(len(flag_parts)):
aa = base + '/' + flag_parts[a]
os.mkdir(aa)
for b in range(10):
bb = aa + '/' + randstr()
os.mkdir(bb)
for c in range(5):
cc = bb + '/' + randstr()
with open(cc, 'w') as f:
if flatten(a, b, c) == flagpos:
print('Flag is located at: ./' + cc)
f.write(flag + '\n')
else:
f.write(randstr() + '\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/BlackhatMEA/2022/Quals/crypto/UrsaMinor/ursaminor.py | ctfs/BlackhatMEA/2022/Quals/crypto/UrsaMinor/ursaminor.py | #!/usr/local/bin/python
#
# Polymero
#
# Imports
from Crypto.Util.number import isPrime, getPrime, inverse
import hashlib, time, os
# Local import
FLAG = os.environ.get('FLAG').encode()
class URSA:
# Upgraded RSA (faster and with cheap key cycling)
def __init__(self, pbit, lbit):
p, q = self.prime_gen(pbit, lbit)
self.public = {'n': p * q, 'e': 0x10001}
self.private = {'p': p, 'q': q, 'f': (p - 1)*(q - 1), 'd': inverse(self.public['e'], (p - 1)*(q - 1))}
def prime_gen(self, pbit, lbit):
# Smooth primes are FAST primes ~ !
while True:
qlst = [getPrime(lbit) for _ in range(pbit // lbit)]
if len(qlst) - len(set(qlst)) <= 1:
continue
q = 1
for ql in qlst:
q *= ql
Q = 2 * q + 1
if isPrime(Q):
break
while True:
plst = [getPrime(lbit) for _ in range(pbit // lbit)]
if len(plst) - len(set(plst)) <= 1:
continue
p = 1
for pl in plst:
p *= pl
P = 2 * p + 1
if isPrime(P):
break
return P, Q
def update_key(self):
# Prime generation is expensive, so we'll just update d and e instead ^w^
self.private['d'] ^= int.from_bytes(hashlib.sha512((str(self.private['d']) + str(time.time())).encode()).digest(), 'big')
self.private['d'] %= self.private['f']
self.public['e'] = inverse(self.private['d'], self.private['f'])
def encrypt(self, m_int):
c_lst = []
while m_int:
c_lst += [pow(m_int, self.public['e'], self.public['n'])]
m_int //= self.public['n']
return c_lst
def decrypt(self, c_int):
m_lst = []
while c_int:
m_lst += [pow(c_int, self.private['d'], self.public['n'])]
c_int //= self.public['n']
return m_lst
# Challenge setup
print("""|
| ~ Welcome to URSA decryption services
| Press enter to start key generation...""")
input("|")
print("""|
| Please hold on while we generate your primes...
|\n|""")
oracle = URSA(256, 12)
print("| ~ You are connected to an URSA-256-12 service, public key ::")
print("| id = {}".format(hashlib.sha256(str(oracle.public['n']).encode()).hexdigest()))
print("| e = {}".format(oracle.public['e']))
print("|\n| ~ Here is a free flag sample, enjoy ::")
for i in oracle.encrypt(int.from_bytes(FLAG, 'big')):
print("| {}".format(i))
MENU = """|
| ~ Menu (key updated after {} requests)::
| [E]ncrypt
| [D]ecrypt
| [U]pdate key
| [Q]uit
|"""
# Server loop
CYCLE = 0
while True:
try:
if CYCLE % 4:
print(MENU.format(4 - CYCLE))
choice = input("| > ")
else:
choice = 'u'
if choice.lower() == 'e':
msg = int(input("|\n| > (int) "))
print("|\n| ~ Encryption ::")
for i in oracle.encrypt(msg):
print("| {}".format(i))
elif choice.lower() == 'd':
cip = int(input("|\n| > (int) "))
print("|\n| ~ Decryption ::")
for i in oracle.decrypt(cip):
print("| {}".format(i))
elif choice.lower() == 'u':
oracle.update_key()
print("|\n| ~ Key updated succesfully ::")
print("| id = {}".format(hashlib.sha256(str(oracle.public['n']).encode()).hexdigest()))
print("| e = {}".format(oracle.public['e']))
CYCLE = 0
elif choice.lower() == 'q':
print("|\n| ~ Closing services...\n|")
break
else:
print("|\n| ~ ERROR - Unknown command")
CYCLE += 1
except KeyboardInterrupt:
print("\n| ~ Closing services...\n|")
break
except:
print("|\n| ~ Please do NOT abuse our services.\n|")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlackhatMEA/2022/Quals/crypto/NothingUpMySbox/nothingupmysbox.py | ctfs/BlackhatMEA/2022/Quals/crypto/NothingUpMySbox/nothingupmysbox.py | #!/usr/local/bin/python
#
# Polymero
#
# Imports
import os, time
from secrets import randbelow
from hashlib import sha256
# Local imports
FLAG = os.environ.get('FLAG').encode()
class NUMSBOX:
def __init__(self, seed, key):
self.sbox = self.gen_box('SBOX :: ' + seed)
self.pbox = self.gen_box(str(time.time()))
self.key = key
def gen_box(self, seed):
box = []
i = 0
while len(box) < 16:
i += 1
h = sha256(seed.encode() + i.to_bytes(2, 'big')).hexdigest()
for j in h:
b = int(j, 16)
if b not in box:
box += [b]
return box
def subs(self, x):
return [self.sbox[i] for i in x]
def perm(self, x):
return [x[i] for i in self.pbox]
def kxor(self, x, k):
return [i ^ j for i,j in zip(x, k)]
def encrypt(self, msg):
if len(msg) % 16:
msg += (16 - (len(msg) % 16)) * [16 - (len(msg) % 16)]
blocks = [msg[i:i+16] for i in range(0, len(msg), 16)]
cip = []
for b in blocks:
x = self.kxor(b, self.key)
for _ in range(4):
x = self.subs(x)
x = self.perm(x)
x = self.kxor(x, self.key)
cip += x
return ''.join([hex(i)[2:] for i in cip])
KEY = [randbelow(16) for _ in range(16)]
OTP = b""
while len(OTP) < len(FLAG):
OTP += sha256(b" :: ".join([b"OTP", str(KEY).encode(), len(OTP).to_bytes(2, 'big')])).digest()
encflag = bytes([i ^ j for i,j in zip(FLAG, OTP)]).hex()
print("|\n| ~ In order to prove that I have nothing up my sleeve, I let you decide on the sbox!")
print("| I am so confident, I will even stake my flag on it ::")
print("| flag = {}".format(encflag))
print("|\n| ~ Now, player, what should I call you?")
seed = input("|\n| > ")
oracle = NUMSBOX(seed, KEY)
print("|\n| ~ Well {}, here are your s- and p-box ::".format(seed))
print("| s-box = {}".format(oracle.sbox))
print("| p-box = {}".format(oracle.pbox))
MENU = """|
| ~ Menu ::
| [E]ncrypt
| [Q]uit
|"""
while True:
try:
print(MENU)
choice = input("| > ")
if choice.lower() == 'e':
msg = [int(i, 16) for i in input("|\n| > (hex) ")]
print("|\n| ~ {}".format(oracle.encrypt(msg)))
elif choice.lower() == 'q':
print("|\n| ~ Sweeping the boxes back up my sleeve...\n|")
break
else:
print("|\n| ~ Sorry I do not know what you mean...")
except KeyboardInterrupt:
print("\n| ~ Sweeping the boxes back up my sleeve...\n|")
break
except:
print("|\n| ~ Hey, be nice to my code, okay?")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/4N0NYM0US3/2023/Milk_Road/Python_ZWSP_Browser.py | ctfs/4N0NYM0US3/2023/Milk_Road/Python_ZWSP_Browser.py | # Importing required libraries
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWebEngineCore import *
from PyQt5.QtPrintSupport import *
import os
import sys
import webbrowser
# Creating main window class
class MainWindow(QMainWindow):
# Constructor
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
# Creating a QWebEngineView
self.browser = QWebEngineView()
# Setting default browser url as google
self.browser.setUrl(QUrl("http://google.com"))
# Adding action when url gets changed
self.browser.urlChanged.connect(self.update_urlbar)
# Adding action when loading is finished
self.browser.loadFinished.connect(self.update_title)
# Set this browser as central widget or main window
self.setCentralWidget(self.browser)
# Creating a status bar object
self.status = QStatusBar()
# Adding status bar to the main window
self.setStatusBar(self.status)
# Creating QToolBar for navigation
navtb = QToolBar("Navigation")
# Adding this tool bar to the main window
self.addToolBar(navtb)
# Adding actions to the tool bar
# Creating an action for back
back_btn = QAction("Back", self)
back_btn.setStatusTip("Back to previous page")
back_btn.triggered.connect(self.browser.back)
navtb.addAction(back_btn)
next_btn = QAction("Forward", self)
next_btn.setStatusTip("Forward to next page")
next_btn.triggered.connect(self.browser.forward)
navtb.addAction(next_btn)
reload_btn = QAction("Reload", self)
reload_btn.setStatusTip("Reload page")
reload_btn.triggered.connect(self.browser.reload)
navtb.addAction(reload_btn)
home_btn = QAction("Home", self)
home_btn.setStatusTip("Go home")
home_btn.triggered.connect(self.navigate_home)
navtb.addAction(home_btn)
navtb.addSeparator()
self.urlbar = QLineEdit()
self.urlbar.returnPressed.connect(self.navigate_to_url)
navtb.addWidget(self.urlbar)
stop_btn = QAction("Stop", self)
stop_btn.setStatusTip("Stop loading current page")
stop_btn.triggered.connect(self.browser.stop)
navtb.addAction(stop_btn)
# Connect the loadProgress signal to check for content process termination
self.browser.loadProgress.connect(self.check_content_process_termination)
self.browser.loadFinished.connect(self.inject_javascript)
self.content_process_terminated = False # Track whether content process termination has been handled
self.show()
def update_title(self):
title = self.browser.page().title()
self.setWindowTitle("% s - ZWSP Browser" % title)
def navigate_home(self):
self.browser.setUrl(QUrl("http://www.google.com"))
def navigate_to_url(self):
q = QUrl(self.urlbar.text())
if q.scheme() == "":
q.setScheme("http")
self.browser.setUrl(q)
def update_urlbar(self, q):
self.urlbar.setText(q.toString())
self.urlbar.setCursorPosition(0)
def inject_javascript(self):
script = """
let bodyText = document.body.innerText;
let zeroWidthCharacters = ['\u200B', '\u200C', '\u200D', '\uFEFF'];
let foundSequences = [];
for (let char of zeroWidthCharacters) {
if (bodyText.includes(char)) {
let sequence = "";
for (let i = 0; i < bodyText.length; i++) {
if (zeroWidthCharacters.includes(bodyText[i])) {
sequence += bodyText[i];
} else {
if (sequence) {
foundSequences.push(sequence);
sequence = "";
}
}
}
break;
}
}
foundSequences;
"""
self.browser.page().runJavaScript(script, self.handle_result)
def handle_result(self, result):
if result:
for sequence in result:
self.decode_zero_width_chars(sequence)
else:
print("No zero-width characters detected.")
def decode_zero_width_chars(self, sequence):
binary_mapping = {'\u200B': '0', '\u200C': '1'}
binary_sequence = ''.join([binary_mapping[char] for char in sequence if char in binary_mapping])
# Split the binary sequence into 8-bit segments
binary_segments = [binary_sequence[i:i+8] for i in range(0, len(binary_sequence), 8)]
# Convert each 8-bit segment to its ASCII character representation
decoded_message = ''.join([chr(int(segment, 2)) for segment in binary_segments])
# Get the original HTML file name without extension
original_filename = os.path.splitext(self.browser.url().fileName())[0]
# Append "decoded_" to the original filename
decoded_filename = "d3c0d3d_" + original_filename + ".html"
# Save the decoded message to a new HTML file
with open(decoded_filename, "w") as file:
file.write(decoded_message)
# Open the new HTML file in the Python web browser
local_url = QUrl.fromLocalFile(os.path.abspath(decoded_filename))
self.browser.load(local_url)
def check_content_process_termination(self, progress):
# Check if progress reaches 100% but loadFinished signal is not emitted
if progress == 100 and not self.content_process_terminated:
# Reload the page if the content process terminates
self.browser.reload()
# Optional: Show a message or perform any additional action when content process terminates
print("Content process terminated.")
self.content_process_terminated = True
# Creating a PyQt5 application
app = QApplication(sys.argv)
# Setting name to the application
app.setApplicationName("ZWSP Browser")
# Creating a main window object
window = MainWindow()
# Start the event loop
sys.exit(app.exec_())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/De1CTF/2019/ABJudge/bin/server.py | ctfs/De1CTF/2019/ABJudge/bin/server.py | #! /bin/python
from flask import Flask,render_template,request
import uuid
import os
import lorun
import multiprocessing
app = Flask(__name__)
RESULT_STR = [
'Accepted',
'Presentation Error',
'Time Limit Exceeded',
'Memory Limit Exceeded',
'Wrong Answer',
'Runtime Error',
'Output Limit Exceeded',
'Compile Error',
'System Error'
]
def compile_binary(random_prefix):
os.system('gcc %s.c -o %s_prog'%(random_prefix,random_prefix))
@app.route("/judge",methods=['POST'])
def judge():
try:
random_prefix = uuid.uuid1().hex
random_src = random_prefix + '.c'
random_prog = random_prefix + '_prog'
random_output = random_prefix + '.out'
if 'code' not in request.form:
return 'code not exists!'
#write into file
with open(random_src,'w') as f:
f.write(request.form['code'])
#compile
process = multiprocessing.Process(target=compile_binary,args=(random_prefix,))
process.start()
process.join(1)
if process.is_alive():
process.terminate()
return 'compile error!'
if not os.path.exists(random_prefix+'_prog'):
os.remove(random_src)
return 'compile error!'
fin = open('a+b.in','r')
ftemp = open(random_output, 'w')
runcfg = {
'args':['./'+random_prog],
'fd_in':fin.fileno(),
'fd_out':ftemp.fileno(),
'timelimit':1000,
'memorylimit':200000,
'trace':True,
'calls':[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 21, 25, 56, 63, 78, 79, 87, 89, 97, 102, 158, 186, 202, 218, 219, 231, 234, 273],
'files':{
"/etc/ld.so.cache":524288,
"/lib/x86_64-linux-gnu/libc.so.6":524288,
"/lib/x86_64-linux-gnu/libm.so.6":524288,
"/usr/lib/x86_64-linux-gnu/libstdc++.so.6":524288,
"/lib/x86_64-linux-gnu/libgcc_s.so.1":524288,
"/lib/x86_64-linux-gnu/libpthread.so.0":524288,
"/etc/localtime":524288
}
}
rst = lorun.run(runcfg)
fin.close()
ftemp.close()
os.remove(random_prog)
os.remove(random_src)
if rst['result'] == 0:
ftemp = open(random_output,'r')
fout = open('a+b.out','r')
crst = lorun.check(fout.fileno() , ftemp.fileno())
fout.seek(0)
ftemp.seek(0)
standard_output = fout.read()
test_output = ftemp.read()
fout.close()
ftemp.close()
if crst != 0:
msg = RESULT_STR[crst] +'<br/>'
msg += 'standard output:<br/>'
msg += standard_output +'<br/>'
msg += 'your output:<br/>'
msg += test_output
os.remove(random_output)
return msg
os.remove(random_output)
return RESULT_STR[rst['result']]
except Exception as e:
if os.path.exists(random_prog):
os.remove(random_prog)
if os.path.exists(random_src):
os.remove(random_src)
return 'ERROR! '+str(e)
return 'ERROR!'
@app.route("/")
def hello():
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0',port=11111)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Block/2021/crypto/collatzeral_damage/collatzeral-damage.py | ctfs/Block/2021/crypto/collatzeral_damage/collatzeral-damage.py | # idk just pick some random numbers for that 's box' thing, there might be a couple repeats...
stupid_box = [99, 171, 124, 123, 89, 76, 120, 89, 26, 91, 136, 26, 37, 190, 27, 59, 91, 123, 155, 91, 11, 19, 153, 11, 225, 27, 139, 155, 27, 155, 19, 147]
def ben_seq(starter):
sequence = []
current_step = starter
max_steps = 14
steps = 0
while current_step > 1:
sequence.append(current_step)
current_step = ben_step(current_step)
steps += 1
return sequence[1:]
def ben_step(inp):
if inp % 2 == 0:
return inp / 2
return (inp * 3) + 1
def find_longest(start, stop):
largest_seq = []
for i in range(start, stop):
curr_seq = ben_seq(i)
if len(curr_seq) > len(largest_seq):
largest_seq = curr_seq
def bad_hash(flag_str):
final_hash = [0] * 32
final_touched_set = []
for i, c in enumerate(flag_str):
final_hash[i % len(final_hash)] = ord(c) ^ final_hash[i % len(final_hash)]
for i in range(32):
seq = ben_seq(final_hash[i])
indexes = [step % len(final_hash) for step in seq]
for j in indexes:
if j != i:
final_hash[j] = (final_hash[i] ^ stupid_box[j]) & final_hash[j]
return final_hash
with open('flag.txt', 'r') as f:
flag = f.read()
print "".join([chr(b).encode('hex') for b in bad_hash(flag)]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Block/2024/crypto/Glitch_in_the_Crypt_Exploiting_Faulty_RSA_Decryption/server.py | ctfs/Block/2024/crypto/Glitch_in_the_Crypt_Exploiting_Faulty_RSA_Decryption/server.py | import os
import random
from Crypto.Util.number import inverse
# RSA public parameters
# Corrected modulus n = p * q
p = None # Hidden
q = None # Hidden
n = 30392456691103520456566703629789883376981975074658985351907533566054217142999128759248328829870869523368987496991637114688552687369186479700671810414151842146871044878391976165906497019158806633675101
e = 65537
# Encrypted flag
flag = os.environ.get("FLAG", "flag{not_the_real_flag}")
flag_int = int.from_bytes(flag.encode(), 'big')
flag_bytes = flag.encode()
flag_length = len(flag_bytes)
ciphertext = pow(flag_int, e, n)
# Ensure n is correct
assert p * q == n
phi = (p - 1) * (q - 1)
d = inverse(e, phi)
dP = d % (p - 1)
dQ = d % (q - 1)
qInv = inverse(q, p)
def decrypt(c_hex):
try:
c = int(c_hex, 16)
except ValueError:
return None, False, "Invalid ciphertext format. Please provide hexadecimal digits."
if c >= n:
return None, False, "Ciphertext must be less than modulus n."
if c == ciphertext:
return None, False, "Can't use the flag!"
# Simulate fault occurrence
faulty = random.randint(1, 10) == 1 # Fault occurs 1 in 10 times
# Decrypt using CRT
m1 = pow(c, dP, p)
m2 = pow(c, dQ, q)
if faulty:
# Introduce fault in m1
m1 = random.randrange(1, p)
# Combine using CRT
h = (qInv * (m1 - m2)) % p
m = (m2 + h * q) % n
return m, faulty, None
def main():
print("Welcome to the RSA Decryption Oracle!")
print("You can decrypt your own ciphertexts.")
print("Retrieve the encrypted flag to get the secret message.")
print("Type 'flag' to get the encrypted flag.")
print("Type 'exit' to quit.")
while True:
print("\nSend your ciphertext in hex format:")
c_hex = input().strip()
if not c_hex:
break
if c_hex.lower() == 'exit':
print("Goodbye!")
break
elif c_hex.lower() == 'flag':
print(f"Encrypted flag (hex): {hex(ciphertext)}")
print(f"Flag length (bytes): {flag_length}")
continue
m, faulty, error = decrypt(c_hex)
if error:
print(error)
else:
print(f"Decrypted message (hex): {hex(m)}")
if faulty:
print("Note: Fault occurred during decryption.")
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/Block/2024/crypto/Wheres_My_Key/server.py | ctfs/Block/2024/crypto/Wheres_My_Key/server.py | import os
import socketserver
import json
import x25519
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
HOST_PORT = int(os.environ.get("HOST_PORT", "8000"))
FLAG = os.environ.get("FLAG", "flag{this-is-not-the-real-flag}")
X25519_KEY_SIZE = 32
class Handler(socketserver.BaseRequestHandler):
timeout = 5.0
def handle(self):
request = json.loads(self.request.recv(1024))
client_pub = bytes.fromhex(request.get("client_pub", ""))
if len(client_pub) != X25519_KEY_SIZE:
return
server_priv = os.urandom(X25519_KEY_SIZE)
server_pub = x25519.scalar_base_mult(server_priv)
secret = x25519.scalar_mult(server_priv, client_pub)
response = {"server_pub": server_pub.hex()}
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(secret), modes.CTR(iv))
encryptor = cipher.encryptor()
ct = encryptor.update(FLAG.encode()) + encryptor.finalize()
data = {"iv": iv.hex(), "ct": ct.hex()}
# This is how you combine dictionaries... right?
response = response and data
self.request.sendall(json.dumps(response).encode())
class Server(socketserver.ThreadingTCPServer):
request_queue_size = 100
def main(host="0.0.0.0", port=HOST_PORT):
print(f"Running server on {host}:{port}")
server = Server((host, port), Handler)
server.serve_forever()
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/Block/2023/crypto/enCRCroach/server.py | ctfs/Block/2023/crypto/enCRCroach/server.py | import hashlib
import os
import secrets
import fastcrc
import werkzeug.security
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from flask import Flask, Response, request, send_from_directory
app = Flask(__name__)
SERVER_KEY = bytes.fromhex(os.environ.get("SERVER_KEY", ""))
IV_LEN = 16
# USER_LEN = can potentially vary
NONCE_LEN = 42
MAC_LEN = 8
KEY_LEN = 32
USER_DB = {
# Someone keeps hacking us and reading out the admin's /flag.txt.
# Disabling this account to see if that helps.
# "admin": "7a2f445babffa758471e3341a1fadce9abeff194aded071e4fd48b25add856a7",
# Other accounts. File a ticket similar to QDB-244321 to add or modify passwords.
"azure": "9631758175d2f048db1964727ad2efef4233099b97f383e4f1e121c900f3e722",
"cthon": "980809b1482352ae59be5d3ede484c0835b46985309a04ac1bad70b22a167670",
}
def response(text, status=200):
return Response(text, status=status, mimetype="text/plain")
@app.route("/", methods=["GET", ])
def root():
return response("""Endpoints:
- /auth?user=<user>: Auth a user with an optional password. Returns an auth token.
- /read/<path>?token=<token>: Read out a file from a user's directory. Token required.
""")
@app.route("/auth", methods=["GET", ])
def auth():
"""Return a token once the user is successfully authenticated.
"""
user = request.args.get("user")
password = request.args.get("password", "")
if not user or user not in USER_DB:
return response("Bad or missing 'user'", 400)
password_hash = USER_DB[user]
given = hashlib.pbkdf2_hmac("SHA256", password.encode(), user.encode(), 1000).hex()
if password_hash != given:
return response("Bad 'password'", 400)
# User is authenticated! Return a super strong token.
return response(encrypt_token(user, SERVER_KEY).hex())
@app.route("/read", defaults={"path": None})
@app.route("/read/<path>", methods=["GET", ])
def read(path: str):
"""Read a static file under the user's directory.
Lists contents if no path is provided.
Decrypts the token to auth the request and get the user's name.
"""
try:
user = decrypt_token(bytes.fromhex(request.args.get("token", "")), SERVER_KEY)
except ValueError:
user = None
if not user:
return response("Bad or missing token", 400)
user_dir = werkzeug.security.safe_join("users", user)
if path is None:
listing = "\n".join(sorted(os.listdir(os.path.join(app.root_path, user_dir))))
return response(listing)
return send_from_directory(user_dir, path)
def encrypt_token(user: str, key: bytes) -> bytes:
"""Encrypt the user string using "authenticated encryption".
JWTs and JWEs scare me. Too many CVEs! I think I can do better...
Here's the token format we use to encrypt and authenticate a user's name.
This is sent to/from the server in ascii-hex:
len : 16 variable 42 8
data: IV || USER || NONCE || MAC
'------------------------' Encrypted
"""
assert len(key) == KEY_LEN
user_bytes = user.encode("utf-8")
iv = secrets.token_bytes(IV_LEN)
nonce = secrets.token_bytes(NONCE_LEN)
cipher = Cipher(algorithms.AES(key), modes.CTR(iv)).encryptor()
mac = gen_mac(iv + user_bytes + nonce)
ciphertext = cipher.update(user_bytes + nonce + mac) + cipher.finalize()
return iv + ciphertext
def decrypt_token(token: bytes, key: bytes) -> [None, str]:
assert len(key) == KEY_LEN
iv, ciphertext = splitup(token, IV_LEN)
if not iv or not ciphertext:
return None
cipher = Cipher(algorithms.AES(key), modes.CTR(iv)).decryptor()
plaintext = cipher.update(ciphertext) + cipher.finalize()
user_bytes, nonce, mac = splitup(plaintext, -(NONCE_LEN + MAC_LEN), -MAC_LEN)
if not user_bytes or len(nonce) != NONCE_LEN or len(mac) != MAC_LEN:
return None
computed = gen_mac(iv + user_bytes + nonce)
if computed != mac:
return None
return user_bytes.decode("utf-8")
def gen_mac(data: bytes) -> bytes:
# A 64-bit CRC should be pretty good. Faster than a hash, and can't be brute forced.
crc = fastcrc.crc64.go_iso(data)
return int.to_bytes(crc, length=MAC_LEN, byteorder="big")
def splitup(data: bytes, *indices):
last_index = 0
for index in indices:
yield data[last_index:index]
last_index = index
yield data[last_index:]
if __name__ == "__main__":
app.run(host="0.0.0.0", port=os.environ.get("FLASK_SERVER_PORT"), debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/pwn/faster-python/challenge/main.py | ctfs/GDGAlgiers/2022/pwn/faster-python/challenge/main.py | #!/usr/bin/env python3
import cext as module
from binascii import unhexlify
MAXSIZE = 0x50
class CBytes:
def __init__(self, size):
b = module.input(size)
self.b = b
def __len__(self):
return module.len(self.b)
def print(self):
return module.print(self.b)
def getsize(maxsize=MAXSIZE):
size = int(input("Enter size: "))
assert(size < maxsize)
return size
def menu():
print("1. Input")
print("2. Length")
print("3. Print")
print("0. Exit")
if __name__ == "__main__":
size = getsize()
cb = CBytes(size)
choice = -1
while choice != 0:
menu()
choice = int(input("Choice: "))
if choice == 1:
size = getsize()
cb = CBytes(size)
elif choice == 2:
l = len(cb)
print(f"Length: {l}")
elif choice == 3:
cb.print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/pwn/encryptor/challenge/run_server.py | ctfs/GDGAlgiers/2022/pwn/encryptor/challenge/run_server.py | import socketserver
import os
import sys
import encryptor
BUFFER_SIZE = 1024
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
allow_reuse_address = True
def handle(self):
self.request.send(
b"choose an option:\n1) Try our fast AES implementation\n2) Try our fast RC4 implementation\n"
)
option = self.request.recv(BUFFER_SIZE).decode().strip()
if option == "1":
self.request.send(b"NOT IMPLEMENTED YET ?\n")
elif option == "2":
self.request.send(b"Key:\n")
key = self.request.recv(BUFFER_SIZE)
self.request.send(b"Data:\n")
data = self.request.recv(BUFFER_SIZE)
response = encryptor.rc4(key, data)
self.request.send(b"Output:\n")
self.request.sendall(response)
else:
self.request.send(b"Invalid option\n")
class ThreadedTCPServer(socketserver.ForkingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 1337
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
print("Server loop running in process:", os.getpid(), file=sys.stderr)
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/GDGAlgiers/2022/jail/PY_explorer/chall.py | ctfs/GDGAlgiers/2022/jail/PY_explorer/chall.py | #!/usr/local/bin/python3
def customDir(obj, expr):
result = dir(obj)
print("\n".join(f"{i}] {sub}" for i, sub in enumerate(result)))
ind = input("index of next object -> ")
if checkInt(ind) and -len(result) <= int(ind) < len(result):
try :
obj, expr = getattr(obj, result[int(ind)]), expr + f".{result[int(ind)]}"
except AttributeError:
print("That attribute doesn't exist")
else:
print("Supply a correct index")
if isinstance(obj, dict):
print(obj)
key = input("Enter a key -> ")
if key in obj.keys():
return obj[key], expr + f"['{key}']"
else:
print("Wrong key")
return obj, expr
def subclasses(obj, expr):
try:
result = obj.__subclasses__()
print("\n".join(f"{i}] {sub}" for i, sub in enumerate(result)))
ind = input("index of next object -> ")
if checkInt(ind) and -len(result) <= int(ind) < len(result):
return result[int(ind)], expr + f".__subclasses__()[{int(ind)}]"
else:
print("Supply a correct index")
except:
print("Can't run subclasses on the current object")
return obj, expr
def checkInt(string):
try:
int(string)
return True
except ValueError:
return False
def welcome():
print("""
Welcome to PY Explorer. I'll give you a tour around my code and let you change what you don't like.
How to use :
1- Choose any object you want.
1- After finishing and choosing, I will run this : obj1 = obj2
"""
)
def explore():
obj = object
expr = "object"
finished = False
while not finished:
print(
"""0- exit
1- explore dir
2- check subclasses
3- show current object
4- clear
5- Done
"""
)
choice = input("--> ")
match choice:
case "0":
exit()
case "1":
obj, expr = customDir(obj, expr)
case "2":
obj, expr = subclasses(obj, expr)
case "3":
print(obj)
case "4":
obj = object
expr = "object"
case "5":
finished = True
return expr
welcome()
left_expr = explore()
right_expr = explore()
# Time for you to make changes
try:
exec(f"{left_expr} = {right_expr}")
except:
print("Impossible to change")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/jail/Type_it/chal.py | ctfs/GDGAlgiers/2022/jail/Type_it/chal.py | #!/usr/bin/env python3
FLAG = "CyberErudites{fake_flag}"
BLACKLIST = '"%&\',-/_:;@\\`{|}~*<=>[] \t\n\r'
def check(s):
return all(ord(x) < 0x7f for x in s) and all(x not in s for x in BLACKLIST)
def safe_eval(s, func):
if not check(s):
print("Input is bad")
else:
try:
print(eval(f"{func.__name__}({s})", {"__builtins__": {func.__name__: func}, "flag": FLAG}))
except:
print("Error")
if __name__ == "__main__":
safe_eval(input("Input : "), type)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/jail/Type_it2/jail.py | ctfs/GDGAlgiers/2022/jail/Type_it2/jail.py | #!/usr/bin/env python3
with open("./flag.txt") as f:
FLAG = f.read().strip()
BLACKLIST = '"%&\',-/_:;@\\`{|}~*<=>[] \t\n\r\x0b\x0c'
OPEN_LIST = '(['
CLOSE_LIST = ')]'
class BadInput(Exception):
pass
def check_balanced(s):
stack = []
for i in s:
if i in OPEN_LIST:
stack.append(i)
elif i in CLOSE_LIST:
pos = CLOSE_LIST.index(i)
if ((len(stack) > 0) and
(OPEN_LIST[pos] == stack[len(stack)-1])):
stack.pop()
else:
return False
return len(stack) == 0
def check(s):
return all(ord(x) < 0x7f for x in s) and all(x not in s for x in BLACKLIST) and check_balanced(s)
def safe_eval(s, func):
if not check(s):
print("Input is bad")
else:
try:
print(eval(f"{func.__name__}({s})", {"__builtins__": {func.__name__: func}, "flag": FLAG}))
except:
print("Error")
if __name__ == "__main__":
while True :
inp = input("Input : ")
if inp == "EXIT":
exit()
safe_eval(inp, type)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/jail/kevin-higgs-the-revenge/challenge/challenge.py | ctfs/GDGAlgiers/2022/jail/kevin-higgs-the-revenge/challenge/challenge.py | #!/usr/bin/env python3
import pickle
import pickletools
import io
import sys
BLACKLIST_OPCODES = {
"BUILD",
"SETITEM",
"SETITEMS",
"DICT",
"EMPTY_DICT",
"INST",
"OBJ",
"NEWOBJ",
"EXT1",
"EXT2",
"EXT4",
"EMPTY_SET",
"ADDITEMS",
"FROZENSET",
"NEWOBJ_EX",
"FRAME",
"BYTEARRAY8",
"NEXT_BUFFER",
"READONLY_BUFFER",
}
module = type(__builtins__)
empty = module("empty")
sys.modules["empty"] = empty
class MyUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if module == "empty" and name.count(".") <= 1 and "setattr" not in name and "setitem" not in name:
return super().find_class(module, name)
else:
raise pickle.UnpicklingError("No :(")
def check(data):
return (
all(
opcode.name not in BLACKLIST_OPCODES
for opcode, _, _ in pickletools.genops(data)
)
and len(data) <= 400
)
if __name__ == "__main__":
data = bytes.fromhex(input("Enter your hex-encoded pickle data: "))
if check(data):
result = MyUnpickler(io.BytesIO(data)).load()
print(f"Result: {result}")
else:
print("Check failed :(")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/franklin-last-words/main.py | ctfs/GDGAlgiers/2022/crypto/franklin-last-words/main.py | from Crypto.Util.number import bytes_to_long, getStrongPrime
from math import gcd
from flag import FLAG
from Crypto.Random import get_random_bytes
def encrypt_message(m):
return pow(m,e,N)
def advanced_encrypt(a,m):
return encrypt_message(pow(a,3,N)+(m << 24))
e = 3
p = getStrongPrime(512)
q = getStrongPrime(512)
# generate secure keys
result = 0
while (result !=1):
p = getStrongPrime(512)
q = getStrongPrime(512)
result = gcd(e,(p-1)*(q-1))
N = p * q
print("N = " + str(N))
print("e = " + str(e))
rand = bytes_to_long(get_random_bytes(64))
ct = []
ct.append(encrypt_message(rand << 24))
for car in FLAG:
ct.append(advanced_encrypt(car,rand))
print("ct = "+str(ct))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/franklin-last-words/message.py | ctfs/GDGAlgiers/2022/crypto/franklin-last-words/message.py | N = 128704452311502431858930198880251272310127835853066867118127724648453996065794849896361864026440048456920428841973494939542251652347755395656512696329757941393301819624888067640984628166587498928291226622894829126692225620665358415985778838076183290137030890396001916620456369124216429276076622486278042629001
e = 3
ct = [21340757543584301785921441484183053451553315439245254915339588451884106542258661009436759738472587801036386643847752005362980150928908869053740830266273664899424683013780904331345502086236995074501779725358484854206059302399319323859279240268722523450455802058257892548941510959997370995292748578655762731064, 53066819955389743890197631647873076075338086201977617516688228878534943391813622173359672220491899999289257725082621279332126787067021987817619363964027754585057494857755310178293620211144789491527192983726079040683600073569676641124270473179040250808117008272524876858340200385005503388452491343904776677382, 7842029648140254898731712025732394370883533642138819492816448948307815782380138847628158108013809453236401089035015649397623608296202122635822677717636589547775619483739816443584071749358123933593122063285229582290924379314987624399741427190797914523635723048501174115183499642950146958355891757875557441498, 81695021584105358045051566003505716258539304380158236410692031154675976958477102448120001354028763788338277726836564439223825775055987134804476545219389719030154358688010609211929573454049639296115583549679374560630884139585632673018270295206596781845043810461183562700653267241738473715845857687319113614456, 86586501887041201286527802721761642260725877818992995519871353147763446402104956574783967901914351377837180089585862713765704485010827129195281513365094091181910563864296721772761074690566705659717173959009277068631076288853911923094528971015851696547954102181618472963745794032190874682537561541341010731317, 4407010096401177719382587860973089547269774584169025945612873836837456069669989617488086581303974564705691737258603082424491662678151761823140849931562969625660637062703801758223280715291175509480824528541363322136476980382432430887691493142016500898713242165899187042640529277802536975777824806009438943965, 20524927494678402175950259591111162749212820045240667997136299019445709195168242983746096181865554404588029237712065575377811975608978219126831818907269960069985776657364619267644968568292446797472239793194732664070169465897817709246314196916593546896176278896250403566147976472899677805168690321734513565299, 4407010096401177719382587860973089547269774584169025945612873836837456069669989617488086581303974564705691737258603082424491662678151761823140849931562969625660637062703801758223280715291175509480824528541363322136476980382432430887691493142016500898713242165899187042640529277802536975777824806009438943965, 51139318697490622650693660298147944378988372035109840705368428672127413619272423551816883049235344493649752002429044518033993427344083454465185748371604373504028204966800166389631164678888210143920677529018088140621435737669118638794028597406100569365879488348484226040476359974085585581378223149467179501946, 61799162491846407044403618488152290977719649337271367195813541845489917481067315542645819191562014741305490739984114955413967671171269164971415239796230389202065094904892080733323413509954520339080338852975324810347271929340532300585500631891040710031375781370408675545957886220089645926354912765277207193798, 107206043735279333846992454448839140370827883940390260597595481248800707737249317944514632453873180357326528319466071505831942392623928121738100851252667510107695812737386157242288048018487583295361010891262525476641689707830363622742934590525129489305921929428048618530386530992073266265026078031189655320106, 85307591403552508243723419381075892490553211323303653139542717671522446932474210804647996573033586101417717988233360452582706073794403902188813545550074952753888569571363969851352079224368979656333248386459649432144248164681972775841136644513642798070299209002137286717588527668402619441954609514753661947313, 86586501887041201286527802721761642260725877818992995519871353147763446402104956574783967901914351377837180089585862713765704485010827129195281513365094091181910563864296721772761074690566705659717173959009277068631076288853911923094528971015851696547954102181618472963745794032190874682537561541341010731317, 41397924411890772454375265845933795072222843402754920501088753051420044021616883093528477351669664383575552141733184262754285200808444804620877416618853152278116553671610496732425895917227824642073742631842238665475944337858457051856626631418115315171059531227054863964810769428751856584563528521378904763004, 10605243757384588410949346291843691695059260029262285885688340336498786144062875360655352621500803735554571187372176718434140069866861892334998832161282034966596765115799113734407139063630983608233399160254561926930070785190320545453208884166339176430224475632173509946846905362279714116952844713431984171423, 65849650090975782672006215530044304732838792899298125801656552932222950757929203789661590769174992774295751413212216292841524763630804121853440450854889497695508837735482849044800782262622201081754096333157119856307403189214765778617730569259936442310922376487593547587612071369577598550538470953180060327484, 4407010096401177719382587860973089547269774584169025945612873836837456069669989617488086581303974564705691737258603082424491662678151761823140849931562969625660637062703801758223280715291175509480824528541363322136476980382432430887691493142016500898713242165899187042640529277802536975777824806009438943965, 25192663003159777174615451629938213843222366842683940183362551204469496974891644208321342646667233572676576472164648007266602388592839440014310951184481049521012297732473729920930726303235436945383858287317594336428793167109440236357984389807244311551143246546400865347076405661274883099848046482994822149839, 81111299336050275750472008224957667125146586306759086248084295752602324720839543288370663615750857287552903922536031859099788116379487391773903754451992919367596305768339444201446994649849712459520992343839084870637197983082887171667909318521242800685401171176726353172069040622627821647795603423551447271897, 172967095404256540830825090627890385022225889601723954575733125793475006259282286018366839965172738142366017838292656817573153121633640374942242813153661050037135885057976712584829626048750871049237074200959050511068507540075123164896445819553176441313661889437609142291778433892651893386678048468180013621, 54209820127153720986474084238052778697132905502967498816654290121880250372787906574546961463213093657385992644387672873438452821695140015330496830316777538022586647303682910176500454712473480999658744024410467615800495847992591570851886050019970720291086916154447046480846281731972943090264324948456440665661, 28885040548649433818312707049098386302426564056859377602258643789733090344285966189272164940417109799449123029221353559595585853944793603746038212728785628090812468725975339605126975370377243473883045109400760722557049145239156309228858278704148782700632988895826738069560545828526225627800055745581440022577, 81111299336050275750472008224957667125146586306759086248084295752602324720839543288370663615750857287552903922536031859099788116379487391773903754451992919367596305768339444201446994649849712459520992343839084870637197983082887171667909318521242800685401171176726353172069040622627821647795603423551447271897, 15712112799522387502102713193722467424402631384092196807057434496598674428309494459811523180782790044819285433524468899851335245998768088831658170418466392438399410802792501309056236805241160176754059850691703432150262405441430237695612809894131939658419704673281367391393311992247965290741727023994779433141, 90557913992970124339018122417017168647892092654619957439310943241692998853469781201535236911728649858936776518532983596071103348064396527739989572674507974009483171965078556587909741335279567452647179397815757421899178406412750565529499623891538068993828045760955318494257424529204657968028613157183995612711, 85675609516128041505642974246105781207878835838608550975500845934782884530583531039538004477522284615403428772115964969520508967026139845649101029319923434926707385504059806901530960679704218584706660751338176542291587725130564020356976235189119834080273889731614886626208044719903723301580316649222174716532, 15712112799522387502102713193722467424402631384092196807057434496598674428309494459811523180782790044819285433524468899851335245998768088831658170418466392438399410802792501309056236805241160176754059850691703432150262405441430237695612809894131939658419704673281367391393311992247965290741727023994779433141, 81111299336050275750472008224957667125146586306759086248084295752602324720839543288370663615750857287552903922536031859099788116379487391773903754451992919367596305768339444201446994649849712459520992343839084870637197983082887171667909318521242800685401171176726353172069040622627821647795603423551447271897, 85675609516128041505642974246105781207878835838608550975500845934782884530583531039538004477522284615403428772115964969520508967026139845649101029319923434926707385504059806901530960679704218584706660751338176542291587725130564020356976235189119834080273889731614886626208044719903723301580316649222174716532, 85675609516128041505642974246105781207878835838608550975500845934782884530583531039538004477522284615403428772115964969520508967026139845649101029319923434926707385504059806901530960679704218584706660751338176542291587725130564020356976235189119834080273889731614886626208044719903723301580316649222174716532, 61799162491846407044403618488152290977719649337271367195813541845489917481067315542645819191562014741305490739984114955413967671171269164971415239796230389202065094904892080733323413509954520339080338852975324810347271929340532300585500631891040710031375781370408675545957886220089645926354912765277207193798, 15712112799522387502102713193722467424402631384092196807057434496598674428309494459811523180782790044819285433524468899851335245998768088831658170418466392438399410802792501309056236805241160176754059850691703432150262405441430237695612809894131939658419704673281367391393311992247965290741727023994779433141, 38962700196345764443430076328468823048654528820043766024585560519262075591273928991068126566288543007226770928003946070052439096668643477740474190703788526219925328431721859530740114691295801384955561916420881286450144549992327909272769286620245430583032691331672843446292771750462163437595822776667096333763, 81111299336050275750472008224957667125146586306759086248084295752602324720839543288370663615750857287552903922536031859099788116379487391773903754451992919367596305768339444201446994649849712459520992343839084870637197983082887171667909318521242800685401171176726353172069040622627821647795603423551447271897, 81604909815994086673421693572426298878862835900596359748090824964404410968235612905849185964777674389932839535035599455168277871014038156501897270840412741045214049490644167087296649367556864887777074100267203854799140784786464099851736527907291367077573005882823454864594785834874833652994406695607530576301, 85307591403552508243723419381075892490553211323303653139542717671522446932474210804647996573033586101417717988233360452582706073794403902188813545550074952753888569571363969851352079224368979656333248386459649432144248164681972775841136644513642798070299209002137286717588527668402619441954609514753661947313, 52156001220188104895473522650224336584905726666754737059523290472567230003322526600513423004029753974157905270382920020591958052240353991252839261876495000572160369521817108757646640716294419293319582726159643898164423211489747574918997667612756540268118158962997647124621728161184263876514787554342131369200, 85675609516128041505642974246105781207878835838608550975500845934782884530583531039538004477522284615403428772115964969520508967026139845649101029319923434926707385504059806901530960679704218584706660751338176542291587725130564020356976235189119834080273889731614886626208044719903723301580316649222174716532, 8626201435710132500083028176804629797027088958282385045951979777069641530512143047104352887040944488529150298079174517417971856366246040580278209977476709229172088355435726582119603207919684569044830141050650718261952439402562787510913838563646318999328281769878916484145022935183249932414990371457340982530, 15712112799522387502102713193722467424402631384092196807057434496598674428309494459811523180782790044819285433524468899851335245998768088831658170418466392438399410802792501309056236805241160176754059850691703432150262405441430237695612809894131939658419704673281367391393311992247965290741727023994779433141, 121226218034082229384971342687398416100893638888085513248813472413262145283395477535912994933231543339828879244145432486720289587030092361101582541189271478597197509543997536280636089567590609161877061652162188271757425292313858133390807992771802944817639363538653163784369687974560442354969526917376491860952, 85675609516128041505642974246105781207878835838608550975500845934782884530583531039538004477522284615403428772115964969520508967026139845649101029319923434926707385504059806901530960679704218584706660751338176542291587725130564020356976235189119834080273889731614886626208044719903723301580316649222174716532, 25192663003159777174615451629938213843222366842683940183362551204469496974891644208321342646667233572676576472164648007266602388592839440014310951184481049521012297732473729920930726303235436945383858287317594336428793167109440236357984389807244311551143246546400865347076405661274883099848046482994822149839, 49537543950196981196008705073490431322869824547419754434164989869148910207602945400222339540873326843877995376121122967451939219149806674439960220589193189585760172923124276530124072984487005587747672999647203434177959209139239195212611226079544263186906487384149209242751551401702465174463378551587903464013, 81604909815994086673421693572426298878862835900596359748090824964404410968235612905849185964777674389932839535035599455168277871014038156501897270840412741045214049490644167087296649367556864887777074100267203854799140784786464099851736527907291367077573005882823454864594785834874833652994406695607530576301, 82605108086464943169862550306200946889734302370750892864214984485030047777068048016807926063544535451667188130157336614116049572675082898787939202381661956285707961358162934993215182977800779844581722076853699116970869839871673603035667037900906095736260590599998045628715894324887335765024740238758306886601, 15712112799522387502102713193722467424402631384092196807057434496598674428309494459811523180782790044819285433524468899851335245998768088831658170418466392438399410802792501309056236805241160176754059850691703432150262405441430237695612809894131939658419704673281367391393311992247965290741727023994779433141, 87183215347967191590542176417724958857058607082507361242348562809358164198308247679047180368020902280813201721298429403561075113836349947551334588733174809438143792381327054583566337165561000865476978009557708693850414825902676261268716823948760442922777052374371288490023049947720611595532141510532644435250, 49537543950196981196008705073490431322869824547419754434164989869148910207602945400222339540873326843877995376121122967451939219149806674439960220589193189585760172923124276530124072984487005587747672999647203434177959209139239195212611226079544263186906487384149209242751551401702465174463378551587903464013, 25192663003159777174615451629938213843222366842683940183362551204469496974891644208321342646667233572676576472164648007266602388592839440014310951184481049521012297732473729920930726303235436945383858287317594336428793167109440236357984389807244311551143246546400865347076405661274883099848046482994822149839, 66766715720902966595178914295223547348495022878823462889622775721913448987561303310541276071530863698182890278728480864181198078543766251390078585132912767108062691265660663002406799106089377580272724589978697222635560956414236639690889939243054319449595599517712915493280854882719256210734111619403134480752, 23942811148204157202654637859911277560708533796069053111751942163750895868053622268645847217089096022452975956692323271828103232820789988209286647453449929108598776835367103056318289898885824280500932307262080931914632255743345269865080087850167325191747197921286245735954464811042826275305804860020107464497]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/eXORcist/server.py | ctfs/GDGAlgiers/2022/crypto/eXORcist/server.py | #!/usr/bin/env python3
# Crypto challenge of eXORciste
import os
from flag import FLAG
import random
def xor(message, key):
return ''.join([chr(m^k) for m,k in zip(message, key)] )
def generate_key(length):
random_seed = os.urandom(16)
key = random_seed * (length //16) + random_seed[:(length % 16)]
return key
def main():
print("Hello Stranger, send me your secret and I will make sure to roll it up")
while True:
message = input('>> ').encode()
if len(message)<20:
print('That is not a secret man!')
exit()
key = generate_key(len(message))
offset = random.randint(0, len(message))
cipher = xor(message[:offset]+FLAG+message[offset:], key)
print("> "+ cipher.encode().hex())
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/Nitro/nitro_server.py | ctfs/GDGAlgiers/2022/crypto/Nitro/nitro_server.py | #!/usr/bin/sage
from sage.all import *
from nitro import Nitro
with open("flag.txt","r") as f:
flag = f.readline()
assert len(flag)==32
def str2bin(s):
return ''.join(bin(ord(i))[2:].zfill(8) for i in s)
def main():
print("********** NITRO ORCALE **********")
print(" Welcome to the nitro oracle ")
print("After getting inspired by some encryption services, i tried to built my own server")
print("My idea is based on using polynomials to make an affine encryption")
print("Keep in mind that i can only encrypt a specific byte each time")
print("You can send me the position of the byte and i send the encrypted byte with the used public key ")
N, p, q, d = 8, 2, 29, 2
assert gcd(N, q) == 1 and gcd(p, q) == 1 and q > (6 * d + 1) * p
cipher = Nitro(N, p, q, d)
print("------------------------------")
print("| MENU |")
print("| a) encrypt the ith byte |")
print("| b) exit |")
print("------------------------------")
while True:
menu= input("choose an option \n")
try:
if menu == "a":
i = int(input("enter the byte index: "))
assert i<32
m = list(str2bin(flag[i]))
e,h = cipher.encrypt(m)
print(e)
print(h)
elif menu == "b":
print(" Good Bye !! ")
exit()
else:
print("Error: invalid menu option.")
raise Exception
except Exception as ex:
print("\nSomething went wrong......try again?\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/GDGAlgiers/2022/crypto/Nitro/nitro.py | ctfs/GDGAlgiers/2022/crypto/Nitro/nitro.py | from sage.all import *
class Nitro:
f_x = None
g_x = None
Fp_x = None
Fq_x = None
hx = None
R = None
Rq = None
Rp = None
def __init__(self, N, p, q, d):
self.N = N
self.p = p
self.q = q
self.d = d
def random_poly(self, N, d1, d2):
coef_list = [1] * d1 + [-1] * d2 + [0] * (N - d1 - d2)
shuffle(coef_list)
return coef_list
def keygen(self):
RR= ZZ['x']
Cyc = RR([-1]+[0]*(self.N - 1)+[1])#x^N-1
R = RR.quotient(Cyc)
Rq = RR.change_ring(Integers(self.q)).quotient(Cyc)
Rp = RR.change_ring(Integers(self.p)).quotient(Cyc)
while True:
try:
f_x = R(self.random_poly(self.N, self.d + 1, self.d))
g_x = R(self.random_poly(self.N, self.d, self.d))
Fp_x = Rp(lift(1 / Rp(f_x)))
Fq_x = Rq(lift(1 / Rq(f_x)))
break
except:
continue
assert Fp_x * f_x == 1 and Fq_x * f_x == 1
h_x = Rq(Fq_x * g_x)
self.f_x, self.g_x, self.Fp_x, self.Fq_x, self.h_x = f_x, g_x, Fp_x, Fq_x, h_x
self.R, self.Rq, self.Rp = R, Rq, Rp
def encrypt(self, m: list):
self.keygen()
r_x = self.Rq(self.random_poly(self.N, self.d, self.d))
m_x = self.Rp(m)
m_x = m_x.lift()
m_x = self.Rq(m_x)
e_x = self.Rq(self.p * self.h_x * r_x + m_x)
return e_x.list(), self.h_x.list()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/The_Messager/main.py | ctfs/GDGAlgiers/2022/crypto/The_Messager/main.py | from Crypto.Util.number import bytes_to_long, getStrongPrime
from math import gcd
from flag import FLAG
from Crypto.Random import get_random_bytes
def encrypt(m):
return pow(m,e,N)
e = 65537
p = getStrongPrime(512)
q = getStrongPrime(512)
# generate secure keys
result = 0
while (result !=1):
p = getStrongPrime(512)
q = getStrongPrime(512)
result = gcd(e,(p-1)*(q-1))
N = p * q
print("N = " + str(N))
print("e = " + str(e))
ct= []
for car in FLAG:
ct.append(encrypt(car))
print("ct = "+str(ct))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/The_Messager/values.py | ctfs/GDGAlgiers/2022/crypto/The_Messager/values.py | N = 98104793775314212094769435239703971612667878931942709323496314311667226421821897454047455384364608911477616865967419199078405667657976292973268348872702988831334377069809925141829484522654208638838107410232921531587371072553811548927714437673444716295120279177952417246053452081185183736591850104338774924467
e = 65537
ct = [59557955474959576660206624043525133310846273212302498426617436803509748162425548197634342588486918147482616522004973199040835582029750639280438996041147608325208945908930143369193578357304254186197457724664951265550125834141764148045395673244799362717438148450445733115690641779639700095307768869847300438253, 97607048581416029062926571417018505731500447987666749788250474454907085372131489769519910926920534443601110489923573005850842619961100534688807840056091034028521978858538829709536737164423073421200827014744373227200312703793013121930135671636129353327159074972851000295417487475393785861237498669100252159044, 38004372795906696894757331871131648031530224436062728311269995645679921465860485882640133168345664604826972306265890129274273712784742292386264877901342467450073854945336549802761040220581301944731832263904413955868554541032965928145245552702237020307108692009940580999397066524173367199993649856004328057742, 65610249332297040857458625252345288063146612523070884751329130451311432450616240978313398905634305852803956572836207006589154213390653363753096142240060011676100524742759979837715526660586946517351104362359503433372228973219040992417231448232501045568342643952828283657002239493968651030160444042592742821704, 57848645190759408064035590555936830924698250834888791007777378610157328101724090892906866832981118503713608571999546148360291005814228191335933740646809173112980033932040429630915379773311975468263990487774811641250195145854945296593410828226719945265428980056477809378473409876224348392301132414375600482145, 6957313057923125085560089171257023203473760713428969376506313775674935905331220908781606247947286464352829783509336646534352069713158426789070512876613819994334721302255774326364472262201418256437848642715536135555310854711754230871987373456743599734380487729023490786912371292789582759182344068210906709437, 57848645190759408064035590555936830924698250834888791007777378610157328101724090892906866832981118503713608571999546148360291005814228191335933740646809173112980033932040429630915379773311975468263990487774811641250195145854945296593410828226719945265428980056477809378473409876224348392301132414375600482145, 86981930105976551495164122424877602808538689622013953327755531942761413178486859339237027300813089402393881575838614995306165507320948680052157051372144094227162770147906143007868913058816635061023693892012271047424221921010665613320265092140949310454855198535840356505430209488382744252937000305623126274981, 43194337616183740840373877930430444558035875544167920088841334164283815069627893036640896202300068282555350508087275606412990826390607317994753773146664539097200868658564184107702069263897799338743023683516244270261267952472432302747143119856402273690172005970575042730179269556627141544683832526442746625620, 89482250871395306943439551053432603987153291395935283447383084666749345242834202340239224042753136323487333541103857486797076006246959981023094994254952247687662257200424989390425345067264043016898808878163242281530099650957903235755890413530217078161462479854268304411400292604355251188571405664115761805870, 59004132970655915407575540335458518744987427174122718756739997109742149797845390775225011383646848770090445181183356371877490986486052859127596478431641719020940954381912300430916516066505882895123361236544957045616712772904947107588375750976961327129547131842010432603580698190614513899046948008736633277887, 65610249332297040857458625252345288063146612523070884751329130451311432450616240978313398905634305852803956572836207006589154213390653363753096142240060011676100524742759979837715526660586946517351104362359503433372228973219040992417231448232501045568342643952828283657002239493968651030160444042592742821704, 73377674922608380792803895136384842155055004173277601125036794781251796549911376743357472487307931722382949404880532165110084706407648325781788607799982049524795055595575324896792591758211839428101947701097528854735395576260170767689630906369602490800021309425922005052538837709336081758167900811397583576739, 50246935183161062737224021785712390498811706353563533293793406173952476246411914152992510272946905607232359663000424907635082990523308645940091607928710163897185184275818989292007936664967310249145204832393938408152331297363783015691523686048839555893686886192431916484292887680955850479433207956919920980064, 377882002174596153633276317568260474480928041358619489242738289560653531457881685988123729759728398216906613180303020396765921617858739036990839132640493889512282856960243668908984038038274169896587114479452005978400240634587204977995890324791053672603289344503438286200648410619790530586970955956772435042, 31134732989375505037651060289329792781984995823556031810352299052142048218014958723151872872140421479582382388981945259211205136917455283441679885609709888815114018977855858911995190105030672217522283042495357373399924237475937492960193606028515776599009887097973954414118241371225063611270348251125921180340, 72690263681427459894339244851545230551932557853596141944208804704898771381243044062352425263427346699237648647721690205722305781128706721973072337946356094361854040257668379183092400367089217864116313001797258804030819988222013219237591758957935061520554807668681793101966647829883883792681252967395348250369, 17744214418862750750628595942426777264085281746564350519351849125357909215702141365067173481976504453865545366813247817156700890437386862883573235607568538748560094957997922830502895325437384905119971159369510788500584456908054079993975068164190152959257433704790351996739318214909314542073393673056420479367, 18553547918531492525239807645125303478049892952906401020913179894611759090899357301111688599085906237531770450565645348606127118877509515132064269267599315894398813793340020058999199487530199598039746850264982678456194354496912591985203212017625226230934422430413074553259597940121550019135636760921971467071, 31134732989375505037651060289329792781984995823556031810352299052142048218014958723151872872140421479582382388981945259211205136917455283441679885609709888815114018977855858911995190105030672217522283042495357373399924237475937492960193606028515776599009887097973954414118241371225063611270348251125921180340, 17744214418862750750628595942426777264085281746564350519351849125357909215702141365067173481976504453865545366813247817156700890437386862883573235607568538748560094957997922830502895325437384905119971159369510788500584456908054079993975068164190152959257433704790351996739318214909314542073393673056420479367, 31134732989375505037651060289329792781984995823556031810352299052142048218014958723151872872140421479582382388981945259211205136917455283441679885609709888815114018977855858911995190105030672217522283042495357373399924237475937492960193606028515776599009887097973954414118241371225063611270348251125921180340, 18553547918531492525239807645125303478049892952906401020913179894611759090899357301111688599085906237531770450565645348606127118877509515132064269267599315894398813793340020058999199487530199598039746850264982678456194354496912591985203212017625226230934422430413074553259597940121550019135636760921971467071, 94592207010722594308702619712179051703015050811781849638810744886301723011902610038136023428453707529824573444299955767387581154312796003660757222332693665526933340779371005490242254804245399130460876402292770538238672286913809389323944071825548623579074964966226902547501885902030045992552185132357338216440, 36349340997000118908053493561315437938277590145384734609841524763386955434588819101635297713664002468053429638826064093345896953953449915414940959569953780727663610306471532452540857781920326685246554174850712980942667758470762597496188891574758605216953945495105383110418651125871273957067290054861036717109, 56210287450605424717417620523865659142157407620414448399648624632567967086205875139379575727948289246358623540117721822231037683482562524254668687894696365965999727701212749159615373959926735368456771664557736034129056367814341992536541173310380931245560285859891264447301379493093435295322654206376045277703, 31137485314938566096207186288083056760255642263153067726021876308871046719167454514180413623907116257372167080309608595960679079179247706746005277083592871187596130824520297498677444990016876449170985904320873602829901631197750645386404135868444109969649851935288095403721504921444527957579663711468083625270, 90248414078396660011917775155662850080661993198359150098322537025758577439311872260081046328532609428758863888812071165416794917407114226529001007502707704188657982525354413358811663757299626779660625106387266208620708995229602210117320708232000890787640905284183393699176732059049566492321187882565736881592]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/the_matrix/the_matrix.py | ctfs/GDGAlgiers/2022/crypto/the_matrix/the_matrix.py | import json
from os import urandom
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from sage.all import *
from Crypto.Util.number import getPrime
from random import randint
p = getPrime(64)
def read_matrix(file_name):
data = open(file_name, 'r').read().strip()
rows = [list(eval(row)) for row in data.splitlines()]
return Matrix(GF(p), rows)
def encrypt(plaintext,key):
iv = urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext,16))
return iv,ciphertext
G = read_matrix('matrix.txt')
priv = randint(1,p-1)
pub = G**priv
key = SHA256.new(data=str(priv).encode()).digest()[:2**8]
flag = b'CyberErudites{???????????????????????????????}'
iv,encrypted_flag = encrypt(flag,key)
with open('public_key.txt', 'wb') as f:
for i in range(N):
f.write((str(list(pub[i])).encode())+b'\n')
json.dump({
"iv": iv.hex(),
"ciphertext": encrypted_flag.hex(),
"p":str(p)
}, open('encrypted_flag.txt', 'w'))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/Eddy/challenge.py | ctfs/GDGAlgiers/2022/crypto/Eddy/challenge.py | from pure25519.basic import (bytes_to_clamped_scalar,scalar_to_bytes,
bytes_to_scalar,
bytes_to_element, Base)
import hashlib, binascii
import os
def H(m):
return hashlib.sha512(m).digest()
def publickey(seed):
# turn first half of SHA512(seed) into scalar, then into point
assert len(seed) == 32
a = bytes_to_clamped_scalar(H(seed)[:32])
A = Base.scalarmult(a)
return A.to_bytes()
def Hint(m):
h = H(m)
return int(binascii.hexlify(h[::-1]), 16)
def signature(m, sk, pk):
assert len(sk) == 32 # seed
assert len(pk) == 32
h = H(sk[:32])
a_bytes, inter = h[:32], h[32:]
a = bytes_to_clamped_scalar(a_bytes)
r = Hint(inter + m)
R = Base.scalarmult(r)
R_bytes = R.to_bytes()
S = r + Hint(R_bytes + pk + m) * a
e = Hint(R_bytes + pk + m)
return R_bytes, S, e
def checkvalid(s, m, pk):
if len(s) != 64: raise Exception("signature length is wrong")
if len(pk) != 32: raise Exception("public-key length is wrong")
R = bytes_to_element(s[:32])
A = bytes_to_element(pk)
S = bytes_to_scalar(s[32:])
h = Hint(s[:32] + pk + m)
v1 = Base.scalarmult(S)
v2 = R.add(A.scalarmult(h))
return v1 == v2
def create_signing_key():
seed = os.urandom(32)
return seed
def create_verifying_key(signing_key):
return publickey(signing_key)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/crypto/Eddy/server.py | ctfs/GDGAlgiers/2022/crypto/Eddy/server.py | #!/usr/bin/python3
import sys
from challenge import *
from Crypto.Util.number import *
with open("flag.txt","r") as f:
flag = f.read()
flag = flag.encode()
sk = create_signing_key()
pk = create_verifying_key(sk)
R_flag,S_flag,e_flag = signature(flag,sk,pk)
def start():
print("Welcom to my singing server !")
print("-" * 10 + "Menu" + "-" * 10)
print("1- Sign a message with a random private key ")
print("2- Sign a message with your private key ")
print("3- Verify the flag")
print("4- Quit")
print("-" * 24)
try:
while True:
c = input("> ")
if c == '1':
msg =input("Enter your message : ").encode()
pk = create_verifying_key(sk)
R,S,e = signature(msg,sk,pk)
out = {"R":R,"S": S,"e":e}
print(out)
elif c == '2':
msg = input("Enter your message : ").encode()
privk = int(input("Enter your private key : "))
privk = long_to_bytes(privk)
pk = create_verifying_key(privk)
R, S, e = signature(msg, sk, pk)
out = {"R": R, "S": S, "e": e}
print(out)
elif c == '3':
pk = int(input("Enter your public key : "))
pk = long_to_bytes(pk)
if checkvalid(R_flag+scalar_to_bytes(S_flag),flag,pk):
print("You are an admin, Here's your flag ", flag)
else:
print("Sorry , you can't get your flag !")
sys.exit()
elif c == '4':
print("Goodbye :)")
sys.exit()
except Exception:
print("System error.")
sys.exit()
start() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/web/Pipe_your_way/app.py | ctfs/GDGAlgiers/2022/web/Pipe_your_way/app.py | from pickle import FALSE
from flask import Flask, request,render_template
from jinja2 import Template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('./index.html')
@app.route( '/follow_the_light', methods=['GET'])
def F0LL0WM3():
the_light = request.args.get("input", None)
if the_light is None:
return "It's just a white screen keep trying....."
else:
for _ in the_light:
if any(x in the_light for x in {'.','_','|join', '[', ']', 'mro', 'base','import','builtins','attr','request','application','getitem','render_template'}):
return "NOICE TRY"
else:
return Template("Your input: " + the_light).render()
if __name__ == "__main__":
app.run(host='0.0.0.0', port=3000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/web/Validator/challenge/app/app.py | ctfs/GDGAlgiers/2022/web/Validator/challenge/app/app.py | import os
from flask import Flask, request, redirect, render_template, session, send_from_directory
from dotenv import load_dotenv
from schema import Schema, And, SchemaError
import json
load_dotenv()
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY")
app.config["DEBUG"] = os.getenv("FLASK_ENV") == "development"
FLAG_DIRECTORY = "."
FLAG_FILENAME = "flag.txt"
# MyDict class
class MyDict(dict):
def __getattr__(self, *args, **kwargs):
return self.get(*args, **kwargs)
def __setattr__(self, *args, **kwargs):
return self.__setitem__(*args, **kwargs)
# Utility functions
def wrap_error(e: Exception):
return f"{e.__class__.__name__}: {e}"
# Routes
@app.route("/")
def index():
session["isAdmin"] = False
return render_template("index.html")
@app.route("/validate", methods=["POST", "GET"])
def validate():
if request.method == "GET":
return redirect("/")
res = MyDict()
json_body = request.json
if type(json_body) != dict:
res.message = "JSON body must be a dictionary"
res.isError = True
return res
schema = json_body.get("schema")
if type(schema) != dict:
res.message = "Schema must be a dictionary"
res.isError = True
return res
data = json_body.get("data")
if type(data) != str:
res.message = "Data must be a string"
res.isError = True
return res
try:
data = json.loads(data)
except json.JSONDecodeError as e:
res.message = wrap_error(e)
res.isError = True
return res
valid_msg = json_body.get("validMsg", "Valid data")
if type(valid_msg) != str:
res.message = "Valid message must be a string"
res.isError = True
return res
invalid_msg = json_body.get("invalidMsg", "Invalid data")
if type(invalid_msg) != str:
res.message = "Invalid message must be a string"
res.isError = True
return res
types = {
"str": str,
"int": int,
"float": float,
"bool": bool,
}
if any(type(fname) != str for fname in schema):
res.message = "Invalid field name"
res.isError = True
return res
if any(ftype not in types for _, ftype in schema.items()):
res.message = "Invalid field type"
res.isError = True
return res
sdict = { fname: And(types[ftype]) for fname, ftype in schema.items() }
s = Schema(sdict, error=invalid_msg)
try:
s.validate(MyDict(data))
res.message = valid_msg
res.isError = False
return res
except SchemaError as e:
res.message = wrap_error(e)
res.isError = True
return res
@app.route("/flag")
def flag():
if session.get("isAdmin", False):
return send_from_directory(FLAG_DIRECTORY, FLAG_FILENAME)
return redirect("/")
# Error handling
@app.errorhandler(404)
def not_found(e):
return render_template("404.html"), 404
@app.errorhandler(500)
def server_error(e):
return render_template("500.html"), 500
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GDGAlgiers/2022/web/Validator/challenge/app/wsgi.py | ctfs/GDGAlgiers/2022/web/Validator/challenge/app/wsgi.py | from app import app
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/CYBERGON/2023/rev/Super_Secure_Encryption/encrypt.py | ctfs/CYBERGON/2023/rev/Super_Secure_Encryption/encrypt.py | import sys
from algorithm import encrypt
def encrypt_file(input_file: str, output_file: str):
with open(input_file, 'rb') as infile:
data = infile.read()
encrypted_data = encrypt(data)
with open(output_file, 'wb') as outfile:
outfile.write(encrypted_data)
print(f"File {input_file} has been encrypted and saved to {output_file}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python encrypt_file.py <input_file> <output_file>")
else:
input_file = sys.argv[1]
output_file = sys.argv[2]
encrypt_file(input_file, output_file)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CYBERGON/2023/crypto/EZ_RSA/Crypto3.py | ctfs/CYBERGON/2023/crypto/EZ_RSA/Crypto3.py | from Crypto.Util.number import getStrongPrime, bytes_to_long
import re
from random import randint
flag = open("flag.txt").read()
m = bytes_to_long(flag.encode())
p = getStrongPrime(512)
q = getStrongPrime(512)
n = p*q
e = 0x10001
c = pow(m,e,n)
num = randint(100,999)
p_encode = []
q_encode = []
p_list = re.findall('.',str(p))
q_list = re.findall('.',str(q))
for value in range(len(p_list)):
p_encode.append(str(int(p_list[value]) ^ num))
q_encode.append(str(int(q_list[value]) ^ num))
print(c)
print(n)
print(p_encode)
print(q_encode)
| 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.