code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def _html(self, message): """This just generates an HTML document that includes `message` in the body. Override, or re-write this do do more interesting stuff. """ content = f"<html><body><h1>Tickets</h1>{message}</body></html>" return content.encode("utf8") # NOTE: must return a bytes object!
This just generates an HTML document that includes `message` in the body. Override, or re-write this do do more interesting stuff.
_html
python
sajjadium/ctf-archives
ctfs/CCCamp/2023/web/Awesome_Notepad/note-admin/watcher.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/web/Awesome_Notepad/note-admin/watcher.py
MIT
def generate_hash(timestamp=None): """Generate hash for post preview.""" if timestamp: seed(timestamp) else: seed(int(datetime.now().timestamp())) return randbytes(32).hex()
Generate hash for post preview.
generate_hash
python
sajjadium/ctf-archives
ctfs/HeroCTF/2023/web/Blogodogo_12/src/utils.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/HeroCTF/2023/web/Blogodogo_12/src/utils.py
MIT
def iter_chunks(xs, n=1448): """Yield successive n-sized chunks from xs""" for i in range(0, len(xs), n): yield xs[i : i + n]
Yield successive n-sized chunks from xs
iter_chunks
python
sajjadium/ctf-archives
ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/notes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/notes.py
MIT
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nft_web.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
Run administrative tasks.
main
python
sajjadium/ctf-archives
ctfs/Codegate/2022/Quals/crypto/nft/nft_web/manage.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Codegate/2022/Quals/crypto/nft/nft_web/manage.py
MIT
def pack(self): """Pack the packet into bytes""" if len(self.payload) > 255: raise ValueError("Payload too large (max 255 bytes)") header = struct.pack('!BBB4sB', self.version, int(self.packet_type), self.flags, self.rsv, self.payload_length ) return header + self.payload
Pack the packet into bytes
pack
python
sajjadium/ctf-archives
ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py
MIT
def unpack(cls, data): """Unpack bytes into a packet""" if len(data) < 8: raise ValueError("Packet too short (minimum 8 bytes)") version, packet_type, flags, rsv, payload_length = struct.unpack('!BBB4sB', data[:8]) if len(data) < 8 + payload_length: raise ValueError(f"Packet payload incomplete. Expected {payload_length} bytes") payload = data[8:8+payload_length] try: packet_type = PacketType(packet_type) except ValueError: raise ValueError(f"Invalid packet type: {packet_type}") return cls(version, packet_type, flags, rsv,payload_length, payload)
Unpack bytes into a packet
unpack
python
sajjadium/ctf-archives
ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py
MIT
def __str__(self): """String representation for debugging""" flags_str = [] if self.flags & Flags.DEV: flags_str.append("DEV") if self.flags & Flags.SYN: flags_str.append("SYN") if self.flags & Flags.ACK: flags_str.append("ACK") if self.flags & Flags.ERROR: flags_str.append("ERROR") if self.flags & Flags.FIN: flags_str.append("FIN") return (f"GhostingPacket(version={self.version}, " f"type={self.packet_type.name}, " f"flags=[{' | '.join(flags_str)}], " f"rsv={self.rsv}, " f"payload_length={self.payload_length}, " f"payload={self.payload})")
String representation for debugging
__str__
python
sajjadium/ctf-archives
ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py
MIT
def add(): username = request.form["username"] password = request.form["password"] sql = f"INSERT INTO `user`(password, username) VALUES ('{password}', '{username}')" try: db.execute_sql(sql) except Exception as e: return f"Err: {sql} <br>" + str(e) return "Your password is leaked :)<br>" + \ """<blockquote class="imgur-embed-pub" lang="en" data-id="WY6z44D" ><a href="//imgur.com/WY6z44D">Please take care of your privacy</a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script> """
<blockquote class="imgur-embed-pub" lang="en" data-id="WY6z44D" ><a href="//imgur.com/WY6z44D">Please take care of your privacy</a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>
add
python
sajjadium/ctf-archives
ctfs/WeCTF/2021/Phish/main.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WeCTF/2021/Phish/main.py
MIT
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cache.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
Run administrative tasks.
main
python
sajjadium/ctf-archives
ctfs/WeCTF/2021/Cache/manage.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WeCTF/2021/Cache/manage.py
MIT
def new_challenge(): """Create new questions for a passage""" p = '\n'.join([lorem.paragraph() for _ in range(random.randint(5, 15))]) qs, ans, res = [], [], [] for _ in range(10): q = lorem.sentence().replace(".", "?") op = [lorem.sentence() for _ in range(4)] qs.append({'question': q, 'options': op}) ans.append(random.randrange(0, 4)) res.append(False) return {'passage': p, 'questions': qs, 'answers': ans, 'results': res}
Create new questions for a passage
new_challenge
python
sajjadium/ctf-archives
ctfs/CakeCTF/2023/web/TOWFL/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2023/web/TOWFL/service/app.py
MIT
def db(): """Get connection to DB""" if getattr(flask.g, '_redis', None) is None: flask.g._redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) return flask.g._redis
Get connection to DB
db
python
sajjadium/ctf-archives
ctfs/CakeCTF/2023/web/TOWFL/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2023/web/TOWFL/service/app.py
MIT
def login_ok(): """Check if the current user is logged in""" return 'user' in flask.session
Check if the current user is logged in
login_ok
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def conn_user(): """Create a connection to user database""" return redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)
Create a connection to user database
conn_user
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def conn_report(): """Create a connection to report database""" return redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=1)
Create a connection to report database
conn_report
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def success(message): """Return a success message""" return flask.jsonify({'status': 'success', 'message': message})
Return a success message
success
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def error(message): """Return an error message""" return flask.jsonify({'status': 'error', 'message': message})
Return an error message
error
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def passhash(password): """Get a safe hash value of password""" return hashlib.sha256(SALT + password.encode()).hexdigest()
Get a safe hash value of password
passhash
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def user_register(): """Register a new user""" # Check username and password username = flask.request.form.get('username', '') password = flask.request.form.get('password', '') if re.match("^[-a-zA-Z0-9_]{5,20}$", username) is None: return error("Username must follow regex '^[-a-zA-Z0-9_]{5,20}$'") if re.match("^.{8,128}$", password) is None: return error("Password must follow regex '^.{8,128}$'") # Register a new user conn = conn_user() if conn.exists(username): return error("This username has been already taken.") else: conn.hset(username, mapping={ 'password': passhash(password), 'bio': "<p>Hello! I'm new to this website.</p>" }) flask.session['user'] = username return success("Successfully registered a new user.")
Register a new user
user_register
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def user_login(): """Login user""" if login_ok(): return success("You have already been logged in.") username = flask.request.form.get('username', '') password = flask.request.form.get('password', '') # Check password conn = conn_user() if conn.hget(username, 'password').decode() == passhash(password): flask.session['user'] = username return success("Successfully logged in.") else: return error("Invalid password or user does not exist.")
Login user
user_login
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def user_logout(): """Logout user""" if login_ok(): flask.session.clear() return success("Successfully logged out.") else: return error("You are not logged in.")
Logout user
user_logout
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def user_update(): """Update user info""" if not login_ok(): return error("You are not logged in.") username = flask.session['user'] bio = flask.request.form.get('bio', '') if len(bio) > 2000: return error("Bio is too long.") # Update bio conn = conn_user() conn.hset(username, 'bio', bio) return success("Successfully updated your profile.")
Update user info
user_update
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
def report(): """Report spam Support staff will check the reported contents as soon as possible. """ if RECAPTCHA_KEY: recaptcha = flask.request.form.get('recaptcha', '') params = { 'secret': RECAPTCHA_KEY, 'response': recaptcha } r = requests.get( "https://www.google.com/recaptcha/api/siteverify", params=params ) if json.loads(r.text)['success'] == False: abort(400) username = flask.request.form.get('username', '') conn = conn_user() if not conn.exists(username): return error("This user does not exist.") conn = conn_report() conn.rpush('report', username) return success("""Thank you for your report.<br>Our support team will check the post as soon as possible.""")
Report spam Support staff will check the reported contents as soon as possible.
report
python
sajjadium/ctf-archives
ctfs/CakeCTF/2022/web/openbio/service/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py
MIT
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
0- exit 1- explore dir 2- check subclasses 3- show current object 4- clear 5- Done
explore
python
sajjadium/ctf-archives
ctfs/GDGAlgiers/2022/jail/PY_explorer/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GDGAlgiers/2022/jail/PY_explorer/chall.py
MIT
def get_answer_info(word_id=None): con, cur = get_sql() if word_id: word = cur.execute( """SELECT word FROM answerList WHERE id = (?)""", (word_id,) ).fetchone()[0] else: word_id, word = cur.execute( """SELECT id, word FROM answerList ORDER BY RANDOM() LIMIT 1""" ).fetchone() return word_id, word
SELECT word FROM answerList WHERE id = (?)""", (word_id,) ).fetchone()[0] else: word_id, word = cur.execute( """SELECT id, word FROM answerList ORDER BY RANDOM() LIMIT 1
get_answer_info
python
sajjadium/ctf-archives
ctfs/BYUCTF/2022/web/Wordle/utils.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BYUCTF/2022/web/Wordle/utils.py
MIT
def start_game(): """ Starts a new game """ word_id = None con, cur = get_sql() key = str(uuid.uuid4()) word_id, word = get_answer_info(word_id) cur.execute("""INSERT INTO game (word, key) VALUES (?, ?)""", (word, key)) con.commit() con.close() return api_response({"id": cur.lastrowid, "key": key, "wordID": word_id})
Starts a new game
start_game
python
sajjadium/ctf-archives
ctfs/BYUCTF/2022/web/Wordle/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BYUCTF/2022/web/Wordle/app.py
MIT
def sign_file(path): """ path: a file path to be signed returns signature - merkel_root1, merkel_root2, merkel_root3, merkel_branches1, merkel_branches2, merkel_branches3, low_degree_stark_proof """ with open(path, "rb") as f: data = f.read() data_blake_hash = blake(data) file_hash = rescue([x for x in data_blake_hash]) proof = rescue_sign([ord(x) for x in PASSWORD], PASSWORD_HASH, file_hash) proof_yaml = yaml.dump(proof, Dumper=yaml.SafeDumper) return proof_yaml
path: a file path to be signed returns signature - merkel_root1, merkel_root2, merkel_root3, merkel_branches1, merkel_branches2, merkel_branches3, low_degree_stark_proof
sign_file
python
sajjadium/ctf-archives
ctfs/Intent/2021/crypto/SANSA/sign_file.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Intent/2021/crypto/SANSA/sign_file.py
MIT
def pow_mod(vector: np.ndarray, exponent: int, p: int) -> np.ndarray: """ Returns a numpy array which, in index i, will be equal to (vector[i] ** exponent % p), where '**' is the power operator. """ return np.vectorize(lambda x: pow(x, exponent, p))(vector)
Returns a numpy array which, in index i, will be equal to (vector[i] ** exponent % p), where '**' is the power operator.
pow_mod
python
sajjadium/ctf-archives
ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py
MIT
def rescue_hash( inputs, mds_matrix=MDS_MATRIX, round_constants=ROUND_CONSTANTS, word_size=WORD_SIZE, p=PRIME, num_rounds=NUM_ROUNDS): """ Returns the result of the Rescue hash on the given input. The state size is word_size * 3. inputs is a list/np.array of size (word_size * 2) round_constants consists of (2 * num_rounds + 1) vectors, each of the same size as state size. mds_matrix is an MDS (Maximum Distance Separable) matrix of size (state size)x(state size). """ mds_matrix = np.array(mds_matrix, dtype=object) % p round_constants = np.array(round_constants, dtype=object)[:, :, np.newaxis] % p inputs = np.array(inputs, dtype=object).reshape(2 * word_size, 1) % p zeros = np.zeros((word_size, 1), dtype=object) state = np.concatenate((inputs, zeros)) #print("state:", [x[0] for x in state]) state = (state + round_constants[0]) % p for i in range(1, 2 * num_rounds, 2): # First half of round i/2. #print("before first half", [x[0] for x in state]) state = pow_mod(state, (2 * p - 1) // 3, p) state = mds_matrix.dot(state) % p state = (state + round_constants[i]) % p # Second half of round i/2. #print("before second half", [x[0] for x in state]) state = pow_mod(state, 3, p) state = mds_matrix.dot(state) % p state = (state + round_constants[i + 1]) % p return (state[:word_size].flatten() % p).tolist()
Returns the result of the Rescue hash on the given input. The state size is word_size * 3. inputs is a list/np.array of size (word_size * 2) round_constants consists of (2 * num_rounds + 1) vectors, each of the same size as state size. mds_matrix is an MDS (Maximum Distance Separable) matrix of size (state size)x(state size).
rescue_hash
python
sajjadium/ctf-archives
ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py
MIT
def point_add(P: Point, Q: Point, D: Point) -> Point: """ Algorithm 1 (xADD) """ V0 = (P.x + P.z) % p V1 = (Q.x - Q.z) % p V1 = (V1 * V0) % p V0 = (P.x - P.z) % p V2 = (Q.x + Q.z) % p V2 = (V2 * V0) % p V3 = (V1 + V2) % p V3 = (V3 * V3) % p V4 = (V1 - V2) % p V4 = (V4 * V4) % p x = (D.z * V3) % p z = (D.x * V4) % p return Point(x, z)
Algorithm 1 (xADD)
point_add
python
sajjadium/ctf-archives
ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
MIT
def point_double(P: Point) -> Point: """ Algorithm 2 (xDBL) """ V1 = (P.x + P.z) % p V1 = (V1 * V1) % p V2 = (P.x - P.z) % p V2 = (V2 * V2) % p x = (V1 * V2) % p V1 = (V1 - V2) % p V3 = (((C.a + 2) // 4) * V1) % p V3 = (V3 + V2) % p z = (V1 * V3) % p return Point(x, z)
Algorithm 2 (xDBL)
point_double
python
sajjadium/ctf-archives
ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
MIT
def scalar_multiplication(P: Point, k: int) -> Point: """ Algorithm 4 (LADDER) """ if k == 0: return Point(0, 0) R0, R1 = P, point_double(P) for i in range(size(k) - 2, -1, -1): if k & (1 << i) == 0: R0, R1 = point_double(R0), point_add(R0, R1, P) else: R0, R1 = point_add(R0, R1, P), point_double(R1) return R0
Algorithm 4 (LADDER)
scalar_multiplication
python
sajjadium/ctf-archives
ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
MIT
def encode(s): """Base64 encode the string using our custom alphabet""" return base64.b64encode(s.encode()).decode().replace('=', '').translate(translation_table)
Base64 encode the string using our custom alphabet
encode
python
sajjadium/ctf-archives
ctfs/BuckeyeCTF/2024/misc/fixpoint/fixpoint.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2024/misc/fixpoint/fixpoint.py
MIT
def bytes2matrix(text): """ Converts a 16-byte array into a 4x4 matrix. """ return [list(text[i:i+4]) for i in range(0, len(text), 4)]
Converts a 16-byte array into a 4x4 matrix.
bytes2matrix
python
sajjadium/ctf-archives
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
MIT
def matrix2bytes(matrix): """ Converts a 4x4 matrix into a 16-byte array. """ return bytes(sum(matrix, []))
Converts a 4x4 matrix into a 16-byte array.
matrix2bytes
python
sajjadium/ctf-archives
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
MIT
def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i ^ j for i, j in zip(a, b))
Returns a new byte array with the elements xor'ed.
xor_bytes
python
sajjadium/ctf-archives
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
MIT
def pad(plaintext): """ Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes. Note that if the plaintext size is a multiple of 16, a whole block will be added. """ padding_len = 16 - (len(plaintext) % 16) padding = bytes([padding_len] * padding_len) return plaintext + padding
Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes. Note that if the plaintext size is a multiple of 16, a whole block will be added.
pad
python
sajjadium/ctf-archives
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
MIT
def __init__(self, master_key): """ Initializes the object with a given key. """ assert len(master_key) in AES.rounds_by_key_size self.n_rounds = AES.rounds_by_key_size[len(master_key)] self._key_matrices = self._expand_key(master_key)
Initializes the object with a given key.
__init__
python
sajjadium/ctf-archives
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
MIT
def _expand_key(self, master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Initialize round keys with raw key material. key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (self.n_rounds + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: # Run word through S-box in the fourth iteration when using a # 256-bit key. word = [s_box[b] for b in word] # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i: 4*(i+1)] for i in range(len(key_columns) // 4)]
Expands and returns a list of key matrices for the given master_key.
_expand_key
python
sajjadium/ctf-archives
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
MIT
def encrypt_block(self, plaintext): """ Encrypts a single block of 16 byte long plaintext. """ assert len(plaintext) == 16 plain_state = bytes2matrix(plaintext) add_round_key(plain_state, self._key_matrices[0]) for i in range(1, self.n_rounds): sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, self._key_matrices[i]) sub_bytes(plain_state) shift_rows(plain_state) add_round_key(plain_state, self._key_matrices[-1]) return matrix2bytes(plain_state)
Encrypts a single block of 16 byte long plaintext.
encrypt_block
python
sajjadium/ctf-archives
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
MIT
def verify(secret, id, hash): '''new_id = "" for i in range(max(len(secret), len(id))): new_id += chr(ord(secret[i % len(secret)]) ^ ord(id[i % len(id)]))''' id_arr = [i for i in id] for i in range(16): id_arr[i] = ord(secret[i]) ^ id[i] id = bytes(id_arr) print(id) new_hash = sha248(id) print(new_hash) print(hash) if new_hash in hash: return True return False
new_id = "" for i in range(max(len(secret), len(id))): new_id += chr(ord(secret[i % len(secret)]) ^ ord(id[i % len(id)]))
verify
python
sajjadium/ctf-archives
ctfs/LIT/2023/crypto/leaderboard-service/flask_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LIT/2023/crypto/leaderboard-service/flask_app.py
MIT
def inv_val(self, val): """ Get the inverse of a given field element using the curves prime field. """ return pow(val, self.mod - 2, self.mod)
Get the inverse of a given field element using the curves prime field.
inv_val
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
MIT
def sqrt(self, a): """ Take the square root in the field using Tonelli–Shanks algorithm. Based on https://gist.github.com/nakov/60d62bdf4067ea72b7832ce9f71ae079 :return: sqrt(a) if it exists, 0 otherwise """ p = self.mod if self.legendre_symbol(a) != 1: return 0 elif a == 0: return 0 elif p == 2: return p elif p % 4 == 3: # lagrange method return pow(a, (p + 1) // 4, p) # Partition p-1 to s * 2^e for an odd s (i.e. # reduce all the powers of 2 from p-1) s = p - 1 e = 0 while s % 2 == 0: s //= 2 e += 1 # Find some 'n' with a legendre symbol n|p = -1. # Shouldn't take long. n = 2 while self.legendre_symbol(n) != -1: n += 1 # Here be dragons! # Read the paper "Square roots from 1; 24, 51, # 10 to Dan Shanks" by Ezra Brown for more # information # # x is a guess of the square root that gets better # with each iteration. # b is the "fudge factor" - by how much we're off # with the guess. The invariant x^2 = ab (mod p) # is maintained throughout the loop. # g is used for successive powers of n to update # both a and b # r is the exponent - decreases with each update # x = pow(a, (s + 1) // 2, p) b = pow(a, s, p) g = pow(n, s, p) r = e while True: t = b m = 0 for m in range(r): if t == 1: break t = pow(t, 2, p) if m == 0: return x gs = pow(g, 2 ** (r - m - 1), p) g = (gs * gs) % p x = (x * gs) % p b = (b * g) % p r = m
Take the square root in the field using Tonelli–Shanks algorithm. Based on https://gist.github.com/nakov/60d62bdf4067ea72b7832ce9f71ae079 :return: sqrt(a) if it exists, 0 otherwise
sqrt
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
MIT
def invert(self, point): """ Invert a point. """ return AffinePoint(self, point.x, (-1 * point.y) % self.mod)
Invert a point.
invert
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
MIT
def mul(self, point, scalar): """ Do scalar multiplication Q = dP using double and add. """ return self.double_and_add(point, scalar)
Do scalar multiplication Q = dP using double and add.
mul
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
MIT
def double_and_add(self, point, scalar): """ Do scalar multiplication Q = dP using double and add. As here: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Double-and-add """ if scalar < 1: raise ValueError("Scalar must be >= 1") result = None tmp = point.copy() while scalar: if scalar & 1: if result is None: result = tmp else: result = self.add(result, tmp) scalar >>= 1 tmp = self.add(tmp, tmp) return result
Do scalar multiplication Q = dP using double and add. As here: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Double-and-add
double_and_add
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
MIT
def plot(self, dotsize=3, fontsize=5, lines=None): """ Plot the curve as scatter plot. This obviously only works for tiny fields. :param lines: A list of lines you want to draw additionally to the points. Every line is a dict with keys: from, to, color(optional), width(optional) :return: pyplot object """ if plt is None: raise ValueError("matplotlib not available.") x = [] y = [] for P in self.enumerate_points(): x.append(P.x) y.append(P.y) plt.rcParams.update({'font.size': fontsize}) plt.scatter(x, y, s=dotsize, marker="o") if lines is not None: for line in lines: plt.plot( (line['from'][0], line['to'][0]), (line['from'][1], line['to'][1]), '-', marker='.', color=line.get('color', 'blue'), linewidth=line.get('width', 1) ) plt.grid() plt.title("{}".format(self)) return plt
Plot the curve as scatter plot. This obviously only works for tiny fields. :param lines: A list of lines you want to draw additionally to the points. Every line is a dict with keys: from, to, color(optional), width(optional) :return: pyplot object
plot
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py
MIT
def enumerate_points(self): """ Yields points of the curve. This only works well on tiny curves. """ for i in range(self.mod): sq = self.calc_y_sq(i) y = self.sqrt(sq) if y: yield AffinePoint(self, i, y) yield AffinePoint(self, i, self.mod - y)
Yields points of the curve. This only works well on tiny curves.
enumerate_points
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py
MIT
def add(self, P, Q): """ Sum of the points P and Q. Rules: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication """ if not (self.is_on_curve(P) and self.is_on_curve(Q)): raise ValueError( "Points not on basic_curves {}: {}, {}: {}".format(P, self.is_on_curve(P), Q, self.is_on_curve(Q))) # Cases with POIF if P == self.poif: result = Q elif Q == self.poif: result = P elif Q == self.invert(P): result = self.poif else: # without POIF if P == Q: slope = (3 * P.x ** 2 + self.a) * self.inv_val(2 * P.y) else: slope = (Q.y - P.y) * self.inv_val(Q.x - P.x) x = (slope ** 2 - P.x - Q.x) % self.mod y = (slope * (P.x - x) - P.y) % self.mod result = AffinePoint(self, x, y) return result
Sum of the points P and Q. Rules: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication
add
python
sajjadium/ctf-archives
ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py
MIT
def __py_new(name, data=b'', **kwargs): """new(name, data=b'', **kwargs) - Return a new hashing object using the named algorithm; optionally initialized with data (which must be a bytes-like object). """ return __get_builtin_constructor(name)(data, **kwargs)
new(name, data=b'', **kwargs) - Return a new hashing object using the named algorithm; optionally initialized with data (which must be a bytes-like object).
__py_new
python
sajjadium/ctf-archives
ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py
MIT
def __hash_new(name, data=b'', **kwargs): """new(name, data=b'') - Return a new hashing object using the named algorithm; optionally initialized with data (which must be a bytes-like object). """ if name in __block_openssl_constructor: # Prefer our builtin blake2 implementation. return __get_builtin_constructor(name)(data, **kwargs) try: return _hashlib.new(name, data, **kwargs) except ValueError: # If the _hashlib module (OpenSSL) doesn't support the named # hash, try using our builtin implementations. # This allows for SHA224/256 and SHA384/512 support even though # the OpenSSL library prior to 0.9.8 doesn't provide them. return __get_builtin_constructor(name)(data)
new(name, data=b'') - Return a new hashing object using the named algorithm; optionally initialized with data (which must be a bytes-like object).
__hash_new
python
sajjadium/ctf-archives
ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py
MIT
def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None): """Password based key derivation function 2 (PKCS #5 v2.0) This Python implementations based on the hmac module about as fast as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster for long passwords. """ if not isinstance(hash_name, str): raise TypeError(hash_name) if not isinstance(password, (bytes, bytearray)): password = bytes(memoryview(password)) if not isinstance(salt, (bytes, bytearray)): salt = bytes(memoryview(salt)) # Fast inline HMAC implementation inner = new(hash_name) outer = new(hash_name) blocksize = getattr(inner, 'block_size', 64) if len(password) > blocksize: password = new(hash_name, password).digest() password = password + b'\x00' * (blocksize - len(password)) inner.update(password.translate(_trans_36)) outer.update(password.translate(_trans_5C)) def prf(msg, inner=inner, outer=outer): # PBKDF2_HMAC uses the password as key. We can re-use the same # digest objects and just update copies to skip initialization. icpy = inner.copy() ocpy = outer.copy() icpy.update(msg) ocpy.update(icpy.digest()) return ocpy.digest() if iterations < 1: raise ValueError(iterations) if dklen is None: dklen = outer.digest_size if dklen < 1: raise ValueError(dklen) dkey = b'' loop = 1 from_bytes = int.from_bytes while len(dkey) < dklen: prev = prf(salt + loop.to_bytes(4, 'big')) # endianness doesn't matter here as long to / from use the same rkey = int.from_bytes(prev, 'big') for i in range(iterations - 1): prev = prf(prev) # rkey = rkey ^ prev rkey ^= from_bytes(prev, 'big') loop += 1 dkey += rkey.to_bytes(inner.digest_size, 'big') return dkey[:dklen]
Password based key derivation function 2 (PKCS #5 v2.0) This Python implementations based on the hmac module about as fast as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster for long passwords.
pbkdf2_hmac
python
sajjadium/ctf-archives
ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py
MIT
def optimize_pushes_pops(self): """This finds runs of push(es) followed by pop(s) and combines them into simpler, faster mov instructions. For example: pushq 8(%rbp) pushq $100 popq %rdx popq %rax Will be turned into: movq $100, %rdx movq 8(%rbp), %rax """ state = 'default' optimized = [] pushes = 0 pops = 0 # This nested function combines a sequence of pushes and pops def combine(): mid = len(optimized) - pops num = min(pushes, pops) moves = [] for i in range(num): pop_arg = optimized[mid + i][1][0] push_arg = optimized[mid - i - 1][1][0] if push_arg != pop_arg: moves.append(('movq', [push_arg, pop_arg])) optimized[mid - num:mid + num] = moves # This loop actually finds the sequences for opcode, args in self.batch: if state == 'default': if opcode == 'pushq': state = 'push' pushes += 1 else: pushes = 0 pops = 0 optimized.append((opcode, args)) elif state == 'push': if opcode == 'pushq': pushes += 1 elif opcode == 'popq': state = 'pop' pops += 1 else: state = 'default' pushes = 0 pops = 0 optimized.append((opcode, args)) elif state == 'pop': if opcode == 'popq': pops += 1 elif opcode == 'pushq': combine() state = 'push' pushes = 1 pops = 0 else: combine() state = 'default' pushes = 0 pops = 0 optimized.append((opcode, args)) else: assert False, 'bad state: {}'.format(state) if state == 'pop': combine() self.batch = optimized
This finds runs of push(es) followed by pop(s) and combines them into simpler, faster mov instructions. For example: pushq 8(%rbp) pushq $100 popq %rdx popq %rax Will be turned into: movq $100, %rdx movq 8(%rbp), %rax
optimize_pushes_pops
python
sajjadium/ctf-archives
ctfs/SECCON/2021/rev/pyast64/pyast64.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SECCON/2021/rev/pyast64/pyast64.py
MIT
def builtin_array(self, args): """FIXED: Nov 20th, 2021 The original design of `array` was vulnerable to out-of-bounds access and type confusion. The fixed version of the array has its length to prevent out-of-bounds access. i.e. x=array(1) 0 4 8 16 +--------+--------+--------+ | length | type | x[0] | +--------+--------+--------+ The `type` field is used to check if the variable is actually an array. This value is not guessable. """ assert len(args) == 1, 'array(len) expected 1 arg, not {}'.format(len(args)) self.visit(args[0]) # Array length must be within [0, 0xffff] self.asm.instr('popq', '%rax') self.asm.instr('cmpq', '$0xffff', '%rax') self.asm.instr('ja', 'trap') # Allocate array on stack, add size to _array_size self.asm.instr('movq', '%rax', '%rcx') self.asm.instr('addq', '$1', '%rax') self.asm.instr('shlq', '$3', '%rax') offset = self.local_offset('_array_size') self.asm.instr('addq', '%rax', '{}(%rbp)'.format(offset)) self.asm.instr('subq', '%rax', '%rsp') self.asm.instr('movq', '%rsp', '%rax') self.asm.instr('movq', '%rax', '%rbx') # Store the array length self.asm.instr('mov', '%ecx', '(%rax)') self.asm.instr('movq', '%fs:0x2c', '%rdx') self.asm.instr('mov', '%edx', '4(%rax)') # Fill the buffer with 0x00 self.asm.instr('lea', '8(%rax)', '%rdi') self.asm.instr('xor', '%eax', '%eax') self.asm.instr('rep', 'stosq') # Push address self.asm.instr('pushq', '%rbx')
FIXED: Nov 20th, 2021 The original design of `array` was vulnerable to out-of-bounds access and type confusion. The fixed version of the array has its length to prevent out-of-bounds access. i.e. x=array(1) 0 4 8 16 +--------+--------+--------+ | length | type | x[0] | +--------+--------+--------+ The `type` field is used to check if the variable is actually an array. This value is not guessable.
builtin_array
python
sajjadium/ctf-archives
ctfs/SECCON/2021/rev/pyast64/pyast64.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SECCON/2021/rev/pyast64/pyast64.py
MIT
def optimize_pushes_pops(self): """This finds runs of push(es) followed by pop(s) and combines them into simpler, faster mov instructions. For example: pushq 8(%rbp) pushq $100 popq %rdx popq %rax Will be turned into: movq $100, %rdx movq 8(%rbp), %rax """ state = 'default' optimized = [] pushes = 0 pops = 0 # This nested function combines a sequence of pushes and pops def combine(): mid = len(optimized) - pops num = min(pushes, pops) moves = [] for i in range(num): pop_arg = optimized[mid + i][1][0] push_arg = optimized[mid - i - 1][1][0] if push_arg != pop_arg: moves.append(('movq', [push_arg, pop_arg])) optimized[mid - num:mid + num] = moves # This loop actually finds the sequences for opcode, args in self.batch: if state == 'default': if opcode == 'pushq': state = 'push' pushes += 1 else: pushes = 0 pops = 0 optimized.append((opcode, args)) elif state == 'push': if opcode == 'pushq': pushes += 1 elif opcode == 'popq': state = 'pop' pops += 1 else: state = 'default' pushes = 0 pops = 0 optimized.append((opcode, args)) elif state == 'pop': if opcode == 'popq': pops += 1 elif opcode == 'pushq': combine() state = 'push' pushes = 1 pops = 0 else: combine() state = 'default' pushes = 0 pops = 0 optimized.append((opcode, args)) else: assert False, 'bad state: {}'.format(state) if state == 'pop': combine() self.batch = optimized
This finds runs of push(es) followed by pop(s) and combines them into simpler, faster mov instructions. For example: pushq 8(%rbp) pushq $100 popq %rdx popq %rax Will be turned into: movq $100, %rdx movq 8(%rbp), %rax
optimize_pushes_pops
python
sajjadium/ctf-archives
ctfs/SECCON/2021/pwn/pyast64/pyast64.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SECCON/2021/pwn/pyast64/pyast64.py
MIT
def builtin_array(self, args): """FIXED: Nov 20th, 2021 The original design of `array` was vulnerable to out-of-bounds access and type confusion. The fixed version of the array has its length to prevent out-of-bounds access. i.e. x=array(1) 0 4 8 16 +--------+--------+--------+ | length | type | x[0] | +--------+--------+--------+ The `type` field is used to check if the variable is actually an array. This value is not guessable. """ assert len(args) == 1, 'array(len) expected 1 arg, not {}'.format(len(args)) self.visit(args[0]) # Array length must be within [0, 0xffff] self.asm.instr('popq', '%rax') self.asm.instr('cmpq', '$0xffff', '%rax') self.asm.instr('ja', 'trap') # Allocate array on stack, add size to _array_size self.asm.instr('movq', '%rax', '%rcx') self.asm.instr('addq', '$1', '%rax') self.asm.instr('shlq', '$3', '%rax') offset = self.local_offset('_array_size') self.asm.instr('addq', '%rax', '{}(%rbp)'.format(offset)) self.asm.instr('subq', '%rax', '%rsp') self.asm.instr('movq', '%rsp', '%rax') self.asm.instr('movq', '%rax', '%rbx') # Store the array length self.asm.instr('mov', '%ecx', '(%rax)') self.asm.instr('movq', '%fs:0x2c', '%rdx') self.asm.instr('mov', '%edx', '4(%rax)') # Fill the buffer with 0x00 self.asm.instr('lea', '8(%rax)', '%rdi') self.asm.instr('xor', '%eax', '%eax') self.asm.instr('rep', 'stosq') # Push address self.asm.instr('pushq', '%rbx')
FIXED: Nov 20th, 2021 The original design of `array` was vulnerable to out-of-bounds access and type confusion. The fixed version of the array has its length to prevent out-of-bounds access. i.e. x=array(1) 0 4 8 16 +--------+--------+--------+ | length | type | x[0] | +--------+--------+--------+ The `type` field is used to check if the variable is actually an array. This value is not guessable.
builtin_array
python
sajjadium/ctf-archives
ctfs/SECCON/2021/pwn/pyast64/pyast64.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SECCON/2021/pwn/pyast64/pyast64.py
MIT
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'secureblog.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
Run administrative tasks.
main
python
sajjadium/ctf-archives
ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/manage.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/manage.py
MIT
def get(self, request: Request, format=None): """ Just return all articles """ articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data)
Just return all articles
get
python
sajjadium/ctf-archives
ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py
MIT
def post(self, request: Request, format=None): """ Query articles """ articles = Article.objects.filter(**request.data) serializer = ArticleSerializer(articles, many=True) return Response(serializer.data)
Query articles
post
python
sajjadium/ctf-archives
ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py
MIT
def e_add(pub, a, b): """Add one encrypted integer to another""" return a * b % pub.n_sq
Add one encrypted integer to another
e_add
python
sajjadium/ctf-archives
ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py
MIT
def e_add_const(pub, a, n): """Add constant n to an encrypted integer""" return a * pow(pub.g, n, pub.n_sq) % pub.n_sq
Add constant n to an encrypted integer
e_add_const
python
sajjadium/ctf-archives
ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py
MIT
def e_mul_const(pub, a, n): """Multiplies an ancrypted integer by a constant""" return pow(a, n, pub.n_sq)
Multiplies an ancrypted integer by a constant
e_mul_const
python
sajjadium/ctf-archives
ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py
MIT
def page_not_found(error): """Custom 404 page.""" return render_template('404.html'), 404
Custom 404 page.
page_not_found
python
sajjadium/ctf-archives
ctfs/LA/2023/web/85_reasons_why/app/views.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2023/web/85_reasons_why/app/views.py
MIT
def r_value(x, y, μ, int_size_bits=1024): """Generates the Fiat-Shamir verifier challenges Hash(xi,yi,μi)""" int_size = int_size_bits // 8 s = (x.to_bytes(int_size, "big", signed=False) + y.to_bytes(int_size, "big", signed=False) + μ.to_bytes(int_size, "big", signed=False)) b = hashlib.sha256(s).digest() return int.from_bytes(b[:16], "big")
Generates the Fiat-Shamir verifier challenges Hash(xi,yi,μi)
r_value
python
sajjadium/ctf-archives
ctfs/LA/2025/crypto/p_vs_np/VDF.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py
MIT
def generate_proof(xi, t, δ, yi, N, i, π=[]): """ Generate the proof, list of μi values """ # Halving protocol from Pietrzak p16. # μi = xi^(2^(T/2^i)) # ri = Hash((xi,T/2^(i−1),yi),μi) # xi+1 = xi^ri . μi # yi+1 = μi^ri . yi t = t//2 # or t = int(τ / pow(2, i)) μi = pow(xi, pow(2, t), N) ri = r_value(xi, yi, μi) % N xi = (pow(xi, ri, N) * μi) % N yi = (pow(μi, ri, N) * yi) % N π.append(μi) print("Values: T:{}, x{}:{}, y{}:{}, u{}:{}, r{}: {}".format(t, i, xi, i, yi, i, μi, i, ri)) # Verify we can build a proof for the leaf if t == pow(2, δ): xi_delta = pow(xi, pow(2, pow(2, δ)), N) if xi_delta == yi: print("Match Last (x{})^2^2^{} {} = y{}: {}".format(i, δ, xi_delta, i, yi)) return π else: print("Proof incomplete.") return return generate_proof(xi, t, δ, yi, N, i+1, π)
Generate the proof, list of μi values
generate_proof
python
sajjadium/ctf-archives
ctfs/LA/2025/crypto/p_vs_np/VDF.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py
MIT
def repeated_squarings(N, x, τ): """ Repeatedly square x. """ return pow(x, pow(2, τ), N)
Repeatedly square x.
repeated_squarings
python
sajjadium/ctf-archives
ctfs/LA/2025/crypto/p_vs_np/VDF.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py
MIT
def verify_proof(xi, yi, π, τ, δ, N): """ Verify proof """ # Verify algo from Pietrzak p16. # ri := hash((xi,T/^2i−1,yi), μi) # xi+1 := xi^ri . μi # yi+1 := μi^ri . yi while(len(π) != 0): μi = π.pop() ri = r_value(xi, yi, μi) % N xi = (pow(xi, ri, N) * μi) % N yi = (pow(μi, ri, N) * yi) % N # yt+1 ?= (xt+1)^2 if yi == pow(xi,pow(2, pow(2, δ)),N): return True else: return False
Verify proof
verify_proof
python
sajjadium/ctf-archives
ctfs/LA/2025/crypto/p_vs_np/VDF.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py
MIT
def db_init(): con = sqlite3.connect('database/data.db') # Create users database query(con, ''' CREATE TABLE IF NOT EXISTS users ( id integer PRIMARY KEY, username text NOT NULL, password text NOT NULL ); ''') query(con, f''' INSERT INTO users ( username, password ) VALUES ( 'admin', '{os.environ.get("ADMIN_PASSWD")}' ); ''') # Create posts database query(con, ''' CREATE TABLE IF NOT EXISTS posts ( id integer PRIMARY KEY, user_id integer NOT NULL, title text, content text NOT NULL, hidden boolean NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) ); ''') query(con, f''' INSERT INTO posts ( user_id, title, content, hidden ) VALUES ( 1, 'Here is a ducky flag!', '{os.environ.get("FLAG")}', 1 ); ''') con.commit()
) query(con, f
db_init
python
sajjadium/ctf-archives
ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/database/database.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/database/database.py
MIT
def db_init(): con = sqlite3.connect('database/data.db') # Create users database query(con, ''' CREATE TABLE IF NOT EXISTS users ( id integer PRIMARY KEY, username text NOT NULL, password text NOT NULL ); ''') query(con, f''' INSERT INTO users ( username, password ) VALUES ( 'admin', '{os.environ.get("ADMIN_PASSWD")}' ); ''') # Create posts database query(con, ''' CREATE TABLE IF NOT EXISTS posts ( id integer PRIMARY KEY, user_id integer NOT NULL, title text, content text NOT NULL, hidden boolean NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) ); ''') query(con, f''' INSERT INTO posts ( user_id, title, content, hidden ) VALUES ( 1, 'Here is a ducky flag!', '{os.environ.get("FLAG")}', 1 ); ''') con.commit()
) query(con, f
db_init
python
sajjadium/ctf-archives
ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/database/database.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/database/database.py
MIT
def db_init(): con = sqlite3.connect('database/data.db') # Create users database query(con, ''' CREATE TABLE IF NOT EXISTS users ( id integer PRIMARY KEY, username text NOT NULL, password text NOT NULL ); ''') query(con, f''' INSERT INTO users ( username, password ) VALUES ( 'admin', '{os.environ.get("ADMIN_PASSWD")}' ); ''') # Create posts database query(con, ''' CREATE TABLE IF NOT EXISTS posts ( id integer PRIMARY KEY, user_id integer NOT NULL, title text, content text NOT NULL, hidden boolean NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) ); ''') query(con, f''' INSERT INTO posts ( user_id, title, content, hidden ) VALUES ( 1, 'Here is a ducky flag!', '{os.environ.get("FLAG")}', 1 ); ''') con.commit()
) query(con, f
db_init
python
sajjadium/ctf-archives
ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/database/database.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/database/database.py
MIT
def db_init(): con = sqlite3.connect('database/data.db') # Create users database query(con, ''' CREATE TABLE IF NOT EXISTS users ( id integer PRIMARY KEY, username text NOT NULL, password text NOT NULL ); ''') query(con, f''' INSERT INTO users ( username, password ) VALUES ( 'admin', '{os.environ.get("ADMIN_PASSWD")}' ); ''') # Create posts database query(con, ''' CREATE TABLE IF NOT EXISTS posts ( id integer PRIMARY KEY, user_id integer NOT NULL, title text, content text NOT NULL, hidden boolean NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) ); ''') query(con, f''' INSERT INTO posts ( user_id, title, content, hidden ) VALUES ( 1, 'Here is a ducky flag!', '{os.environ.get("FLAG")}', 0 ); ''') con.commit()
) query(con, f
db_init
python
sajjadium/ctf-archives
ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/database/database.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/database/database.py
MIT
def garble_label(key0, key1, key2): """ key0, key1 = two input labels key2 = output label """ gl = encrypt(key2, key0, key1) validation = encrypt(0, key0, key1) return (gl, validation)
key0, key1 = two input labels key2 = output label
garble_label
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def evaluate_gate(garbled_table, key0, key1): """ Return the output label unlocked by the two input labels, or raise a ValueError if no entry correctly decoded """ for g in garbled_table: gl, v = g label = decrypt(gl, key0, key1) validation = decrypt(v, key0, key1) if validation == 0: return label raise ValueError("None of the gates correctly decoded; invalid input labels")
Return the output label unlocked by the two input labels, or raise a ValueError if no entry correctly decoded
evaluate_gate
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def evaluate_circuit(circuit, g_tables, inputs): """ Evaluate yao circuit with given inputs. Keyword arguments: circuit -- dict containing circuit spec g_tables -- garbled tables of yao circuit inputs -- dict mapping wires to labels Returns: evaluation -- a dict mapping output wires to the result labels """ gates = circuit["gates"] # dict containing circuit gates wire_outputs = circuit["outputs"] # list of output wires wire_inputs = {} # dict containing Alice and Bob inputs evaluation = {} # dict containing result of evaluation wire_inputs.update(inputs) # Iterate over all gates for gate in sorted(gates, key=lambda g: g["id"]): gate_id, gate_in = gate["id"], gate["in"] key0 = wire_inputs[gate_in[0]] key1 = wire_inputs[gate_in[1]] garbled_table = g_tables[gate_id] msg = evaluate_gate(garbled_table, key0, key1) wire_inputs[gate_id] = msg # After all gates have been evaluated, we populate the dict of results for out in wire_outputs: evaluation[out] = wire_inputs[out] return evaluation
Evaluate yao circuit with given inputs. Keyword arguments: circuit -- dict containing circuit spec g_tables -- garbled tables of yao circuit inputs -- dict mapping wires to labels Returns: evaluation -- a dict mapping output wires to the result labels
evaluate_circuit
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def _gen_garbled_AND_gate(self, labels0, labels1, labels2): """ labels0, labels1 = two input labels labels2 = output label """ key0_0, key0_1 = labels0 key1_0, key1_1 = labels1 key2_0, key2_1 = labels2 G = [] G.append(garble_label(key0_0, key1_0, key2_0)) G.append(garble_label(key0_0, key1_1, key2_0)) G.append(garble_label(key0_1, key1_0, key2_0)) G.append(garble_label(key0_1, key1_1, key2_1)) # randomly shuffle the table so you don't know what the labels correspond to shuffle(G) return G
labels0, labels1 = two input labels labels2 = output label
_gen_garbled_AND_gate
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def get_garbled_table(self): """Return the garbled table of the gate.""" return self.garbled_table
Return the garbled table of the gate.
get_garbled_table
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def _gen_keys(self): """Create pair of keys for each wire.""" for wire in self.wires: self.keys[wire] = ( generate_random_label(), generate_random_label() )
Create pair of keys for each wire.
_gen_keys
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def _gen_garbled_tables(self): """Create the garbled table of each gate.""" for gate in self.gates: garbled_gate = GarbledGate(gate, self.keys) self.garbled_tables[gate["id"]] = garbled_gate.get_garbled_table()
Create the garbled table of each gate.
_gen_garbled_tables
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def get_garbled_tables(self): """Return dict mapping each gate to its garbled table.""" return self.garbled_tables
Return dict mapping each gate to its garbled table.
get_garbled_tables
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def get_keys(self): """Return dict mapping each wire to its pair of keys.""" return self.keys
Return dict mapping each wire to its pair of keys.
get_keys
python
sajjadium/ctf-archives
ctfs/DiceCTF/2021/crypto/garbled/yao.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py
MIT
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.clamp(x, min=clip_val) * C)
PARAMS ------ C: compression factor
dynamic_range_compression_torch
python
jaywalnut310/vits
mel_processing.py
https://github.com/jaywalnut310/vits/blob/master/mel_processing.py
MIT
def dynamic_range_decompression_torch(x, C=1): """ PARAMS ------ C: compression factor used to compress """ return torch.exp(x) / C
PARAMS ------ C: compression factor used to compress
dynamic_range_decompression_torch
python
jaywalnut310/vits
mel_processing.py
https://github.com/jaywalnut310/vits/blob/master/mel_processing.py
MIT
def main(): """Assume Single Node Multi GPUs Training Only""" assert torch.cuda.is_available(), "CPU training is not allowed." n_gpus = torch.cuda.device_count() os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '80000' hps = utils.get_hparams() mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
Assume Single Node Multi GPUs Training Only
main
python
jaywalnut310/vits
train_ms.py
https://github.com/jaywalnut310/vits/blob/master/train_ms.py
MIT
def kl_loss(z_p, logs_q, m_p, logs_p, z_mask): """ z_p, logs_q: [b, h, t_t] m_p, logs_p: [b, h, t_t] """ z_p = z_p.float() logs_q = logs_q.float() m_p = m_p.float() logs_p = logs_p.float() z_mask = z_mask.float() kl = logs_p - logs_q - 0.5 kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p) kl = torch.sum(kl * z_mask) l = kl / torch.sum(z_mask) return l
z_p, logs_q: [b, h, t_t] m_p, logs_p: [b, h, t_t]
kl_loss
python
jaywalnut310/vits
losses.py
https://github.com/jaywalnut310/vits/blob/master/losses.py
MIT
def main(): """Assume Single Node Multi GPUs Training Only""" assert torch.cuda.is_available(), "CPU training is not allowed." n_gpus = torch.cuda.device_count() os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '80000' hps = utils.get_hparams() mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
Assume Single Node Multi GPUs Training Only
main
python
jaywalnut310/vits
train.py
https://github.com/jaywalnut310/vits/blob/master/train.py
MIT
def _filter(self): """ Filter text & store spec lengths """ # Store spectrogram lengths for Bucketing # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2) # spec_length = wav_length // hop_length audiopaths_and_text_new = [] lengths = [] for audiopath, text in self.audiopaths_and_text: if self.min_text_len <= len(text) and len(text) <= self.max_text_len: audiopaths_and_text_new.append([audiopath, text]) lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length)) self.audiopaths_and_text = audiopaths_and_text_new self.lengths = lengths
Filter text & store spec lengths
_filter
python
jaywalnut310/vits
data_utils.py
https://github.com/jaywalnut310/vits/blob/master/data_utils.py
MIT
def __call__(self, batch): """Collate's training batch from normalized text and aduio PARAMS ------ batch: [text_normalized, spec_normalized, wav_normalized] """ # Right zero-pad all one-hot text sequences to max input length _, ids_sorted_decreasing = torch.sort( torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True) max_text_len = max([len(x[0]) for x in batch]) max_spec_len = max([x[1].size(1) for x in batch]) max_wav_len = max([x[2].size(1) for x in batch]) text_lengths = torch.LongTensor(len(batch)) spec_lengths = torch.LongTensor(len(batch)) wav_lengths = torch.LongTensor(len(batch)) text_padded = torch.LongTensor(len(batch), max_text_len) spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len) wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) text_padded.zero_() spec_padded.zero_() wav_padded.zero_() for i in range(len(ids_sorted_decreasing)): row = batch[ids_sorted_decreasing[i]] text = row[0] text_padded[i, :text.size(0)] = text text_lengths[i] = text.size(0) spec = row[1] spec_padded[i, :, :spec.size(1)] = spec spec_lengths[i] = spec.size(1) wav = row[2] wav_padded[i, :, :wav.size(1)] = wav wav_lengths[i] = wav.size(1) if self.return_ids: return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths
Collate's training batch from normalized text and aduio PARAMS ------ batch: [text_normalized, spec_normalized, wav_normalized]
__call__
python
jaywalnut310/vits
data_utils.py
https://github.com/jaywalnut310/vits/blob/master/data_utils.py
MIT
def _filter(self): """ Filter text & store spec lengths """ # Store spectrogram lengths for Bucketing # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2) # spec_length = wav_length // hop_length audiopaths_sid_text_new = [] lengths = [] for audiopath, sid, text in self.audiopaths_sid_text: if self.min_text_len <= len(text) and len(text) <= self.max_text_len: audiopaths_sid_text_new.append([audiopath, sid, text]) lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length)) self.audiopaths_sid_text = audiopaths_sid_text_new self.lengths = lengths
Filter text & store spec lengths
_filter
python
jaywalnut310/vits
data_utils.py
https://github.com/jaywalnut310/vits/blob/master/data_utils.py
MIT
def __call__(self, batch): """Collate's training batch from normalized text, audio and speaker identities PARAMS ------ batch: [text_normalized, spec_normalized, wav_normalized, sid] """ # Right zero-pad all one-hot text sequences to max input length _, ids_sorted_decreasing = torch.sort( torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True) max_text_len = max([len(x[0]) for x in batch]) max_spec_len = max([x[1].size(1) for x in batch]) max_wav_len = max([x[2].size(1) for x in batch]) text_lengths = torch.LongTensor(len(batch)) spec_lengths = torch.LongTensor(len(batch)) wav_lengths = torch.LongTensor(len(batch)) sid = torch.LongTensor(len(batch)) text_padded = torch.LongTensor(len(batch), max_text_len) spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len) wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) text_padded.zero_() spec_padded.zero_() wav_padded.zero_() for i in range(len(ids_sorted_decreasing)): row = batch[ids_sorted_decreasing[i]] text = row[0] text_padded[i, :text.size(0)] = text text_lengths[i] = text.size(0) spec = row[1] spec_padded[i, :, :spec.size(1)] = spec spec_lengths[i] = spec.size(1) wav = row[2] wav_padded[i, :, :wav.size(1)] = wav wav_lengths[i] = wav.size(1) sid[i] = row[3] if self.return_ids: return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid
Collate's training batch from normalized text, audio and speaker identities PARAMS ------ batch: [text_normalized, spec_normalized, wav_normalized, sid]
__call__
python
jaywalnut310/vits
data_utils.py
https://github.com/jaywalnut310/vits/blob/master/data_utils.py
MIT
def forward(self, x, x_mask, h, h_mask): """ x: decoder input h: encoder output """ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype) encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask for i in range(self.n_layers): y = self.self_attn_layers[i](x, x, self_attn_mask) y = self.drop(y) x = self.norm_layers_0[i](x + y) y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) y = self.drop(y) x = self.norm_layers_1[i](x + y) y = self.ffn_layers[i](x, x_mask) y = self.drop(y) x = self.norm_layers_2[i](x + y) x = x * x_mask return x
x: decoder input h: encoder output
forward
python
jaywalnut310/vits
attentions.py
https://github.com/jaywalnut310/vits/blob/master/attentions.py
MIT
def _matmul_with_relative_values(self, x, y): """ x: [b, h, l, m] y: [h or 1, m, d] ret: [b, h, l, d] """ ret = torch.matmul(x, y.unsqueeze(0)) return ret
x: [b, h, l, m] y: [h or 1, m, d] ret: [b, h, l, d]
_matmul_with_relative_values
python
jaywalnut310/vits
attentions.py
https://github.com/jaywalnut310/vits/blob/master/attentions.py
MIT
def _matmul_with_relative_keys(self, x, y): """ x: [b, h, l, d] y: [h or 1, m, d] ret: [b, h, l, m] """ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) return ret
x: [b, h, l, d] y: [h or 1, m, d] ret: [b, h, l, m]
_matmul_with_relative_keys
python
jaywalnut310/vits
attentions.py
https://github.com/jaywalnut310/vits/blob/master/attentions.py
MIT
def _relative_position_to_absolute_position(self, x): """ x: [b, h, l, 2*l-1] ret: [b, h, l, l] """ batch, heads, length, _ = x.size() # Concat columns of pad to shift from relative to absolute indexing. x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]])) # Concat extra elements so to add up to shape (len+1, 2*len-1). x_flat = x.view([batch, heads, length * 2 * length]) x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]])) # Reshape and slice out the padded elements. x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:] return x_final
x: [b, h, l, 2*l-1] ret: [b, h, l, l]
_relative_position_to_absolute_position
python
jaywalnut310/vits
attentions.py
https://github.com/jaywalnut310/vits/blob/master/attentions.py
MIT
def _absolute_position_to_relative_position(self, x): """ x: [b, h, l, l] ret: [b, h, l, 2*l-1] """ batch, heads, length, _ = x.size() # padd along column x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]])) x_flat = x.view([batch, heads, length**2 + length*(length -1)]) # add 0's in the beginning that will skew the elements after reshape x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:] return x_final
x: [b, h, l, l] ret: [b, h, l, 2*l-1]
_absolute_position_to_relative_position
python
jaywalnut310/vits
attentions.py
https://github.com/jaywalnut310/vits/blob/master/attentions.py
MIT
def _attention_bias_proximal(self, length): """Bias for self-attention to encourage attention to close positions. Args: length: an integer scalar. Returns: a Tensor with shape [1, 1, length, length] """ r = torch.arange(length, dtype=torch.float32) diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
Bias for self-attention to encourage attention to close positions. Args: length: an integer scalar. Returns: a Tensor with shape [1, 1, length, length]
_attention_bias_proximal
python
jaywalnut310/vits
attentions.py
https://github.com/jaywalnut310/vits/blob/master/attentions.py
MIT
def kl_divergence(m_p, logs_p, m_q, logs_q): """KL(P||Q)""" kl = (logs_q - logs_p) - 0.5 kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) return kl
KL(P||Q)
kl_divergence
python
jaywalnut310/vits
commons.py
https://github.com/jaywalnut310/vits/blob/master/commons.py
MIT
def rand_gumbel(shape): """Sample from the Gumbel distribution, protect from overflows.""" uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 return -torch.log(-torch.log(uniform_samples))
Sample from the Gumbel distribution, protect from overflows.
rand_gumbel
python
jaywalnut310/vits
commons.py
https://github.com/jaywalnut310/vits/blob/master/commons.py
MIT
def generate_path(duration, mask): """ duration: [b, 1, t_x] mask: [b, 1, t_y, t_x] """ device = duration.device b, _, t_y, t_x = mask.shape cum_duration = torch.cumsum(duration, -1) cum_duration_flat = cum_duration.view(b * t_x) path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) path = path.view(b, t_x, t_y) path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] path = path.unsqueeze(1).transpose(2,3) * mask return path
duration: [b, 1, t_x] mask: [b, 1, t_y, t_x]
generate_path
python
jaywalnut310/vits
commons.py
https://github.com/jaywalnut310/vits/blob/master/commons.py
MIT
def maximum_path(neg_cent, mask): """ Cython optimized version. neg_cent: [b, t_t, t_s] mask: [b, t_t, t_s] """ device = neg_cent.device dtype = neg_cent.dtype neg_cent = neg_cent.data.cpu().numpy().astype(np.float32) path = np.zeros(neg_cent.shape, dtype=np.int32) t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(np.int32) t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(np.int32) maximum_path_c(path, neg_cent, t_t_max, t_s_max) return torch.from_numpy(path).to(device=device, dtype=dtype)
Cython optimized version. neg_cent: [b, t_t, t_s] mask: [b, t_t, t_s]
maximum_path
python
jaywalnut310/vits
monotonic_align/__init__.py
https://github.com/jaywalnut310/vits/blob/master/monotonic_align/__init__.py
MIT
def basic_cleaners(text): '''Basic pipeline that lowercases and collapses whitespace without transliteration.''' text = lowercase(text) text = collapse_whitespace(text) return text
Basic pipeline that lowercases and collapses whitespace without transliteration.
basic_cleaners
python
jaywalnut310/vits
text/cleaners.py
https://github.com/jaywalnut310/vits/blob/master/text/cleaners.py
MIT
def transliteration_cleaners(text): '''Pipeline for non-English text that transliterates to ASCII.''' text = convert_to_ascii(text) text = lowercase(text) text = collapse_whitespace(text) return text
Pipeline for non-English text that transliterates to ASCII.
transliteration_cleaners
python
jaywalnut310/vits
text/cleaners.py
https://github.com/jaywalnut310/vits/blob/master/text/cleaners.py
MIT