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/AmateursCTF/2023/algo/gcd-query-v1/main.py
ctfs/AmateursCTF/2023/algo/gcd-query-v1/main.py
#!/usr/local/bin/python from flag import flag from math import gcd from Crypto.Util.number import getRandomInteger for i in range(10): x = getRandomInteger(2048) for i in range(1412): try: n, m = map(int, input("n m: ").split()) assert m > 0 print(gcd(x + n, m)) except: print("bad input. you *die*") exit(0) if int(input("x: ")) != x: print("get better lol") exit(0) print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/algo/gcd-query-v2/main.py
ctfs/AmateursCTF/2023/algo/gcd-query-v2/main.py
#!/usr/local/bin/python from flag import flag from math import gcd from Crypto.Util.number import getRandomInteger x = getRandomInteger(128) for i in range(16): try: n, m = map(int, input("n m: ").split()) assert m > 0 print(gcd(x + n, m)) except: print("bad input. you *die*") exit(0) if int(input("x: ")) == x: print(flag) else: print("get better lol")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/OwO_time_pad/main.py
ctfs/AmateursCTF/2023/crypto/OwO_time_pad/main.py
import os import random from Crypto.Util.strxor import strxor from math import gcd with open('secret.txt', 'rb') as f: plaintext = f.read() keylength = len(plaintext) while gcd(keylength, len(plaintext)) > 1: keylength = random.randint(10, 100) key = os.urandom(keylength) key = key * len(plaintext) plaintext = plaintext * keylength ciphertext = strxor(plaintext, key) with open('out.txt', 'w') as g: g.write(ciphertext.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/Poly_Fractions/main.py
ctfs/AmateursCTF/2023/crypto/Poly_Fractions/main.py
#!/usr/local/bin/python import random import math from flag import flag, text a = 1 b = random.randint(-10, 10) b2 = random.randint(-10, 10) numcoefficients = [a, b] denomcoefficients = [a, b2] query = 0 for i in flag: sign = random.randint(0, 1) if sign == 0: sign -= 1 numcoefficients.append(sign * int(i)) for i in text: sign = random.randint(0, 1) if sign == 0: sign -= 1 denomcoefficients.append(sign * int(i)) numcoefficients.reverse() denomcoefficients.reverse() while True: try: query += 1 if query > 500: print("exceeded query limit!") exit(0) numcoefficients[-2] = random.randint(-10, 10) denomcoefficients[-2] = random.randint(-10, 10) x = int(input("x: ")) if -99 <= x <= 99: x1 = 1 numerator = 0 for i in numcoefficients: numerator += i * x1 x1 *= x x2 = 1 denominator = 0 for i in denomcoefficients: denominator += i * x2 x2 *= x gcd = math.gcd(numerator, denominator) print(str(numerator//gcd) + "/" + str(denominator//gcd)) else: print("input must be at most 2 digits") except: print("invalid input") exit(0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/Lottery/main.py
ctfs/AmateursCTF/2023/crypto/Lottery/main.py
#!/usr/local/bin/python from Crypto.Util.number import * from Crypto.Cipher import AES from math import ceil import os import random from flag import flag xyz = len(flag) fullkey = "" for i in range(128): key = "" for j in range(128): key += str(random.randint(0, 1)) for j in range(10): key = bin(int(key, 2))[:2:-1] + str(random.randint(0, 1)) key = bin(int(key, 2))[:2:-1] key = int(key) key = pow(key, random.randint(0, 256), random.randint(1, 256)) for i in range(256): key = key * i * random.randint(0, 2) + key * random.randint( 1, 3) + key // (i + 1) * random.randint(2, 4) + key * key key = key % 256 key = key * \ random.randint(1, random.randint( 1, random.randint(1, random.randint(1, 1e4)))) key = bin(key)[2:][::-1] fullkey += key[0] key = long_to_bytes(int(fullkey, 2)) # secure padding key = b"\x00" * (16 - len(key)) + key flag = b"\x00" * (16 - len(flag) % 16) + flag iv = os.urandom(16) aescbc = AES.new(key, AES.MODE_CBC, iv=iv) encrypted_flag = aescbc.encrypt(flag).hex() luck = 0 def draw(): y = 1 while random.randint(1, 10000) != 1: y += 1 return y while True: args = input("Enter Arguments: ") if args == "flag": if luck >= 3: print(encrypted_flag) break else: print("Not lucky enough.") elif args == "": print("Bruh please input something plz!!") break elif args == "draw": if random.randint(1, 10000) == 1: luck += 1 if luck == 1: print("Success! 2 more draws until you can see the flag!") elif luck == 2: print("Success! 1 more draw until you can see the flag!") elif luck == 3: print("Success! Now go get that flag!") for i in range(random.randint(1, 8)): print(random.randint(0, 1), end="") print() else: print("Your lucky number is:", bytes_to_long( os.urandom(getRandomInteger(3)))) else: print("Better luck next time!") break elif args[:3] == "win": if args[3:] == "": print("if you were to draw, you would've drawn", draw(), "times") break else: # good luck! if bytes_to_long(os.urandom(getRandomInteger(10))) == 69420**3: try: print("good job. you won.") print(eval(args[3:])) except: print( args[3:], "gave an error, too bad so sad. Try again next century. Maybe try printing the flag next time. ;) Just saying.") else: print("Didn't win hard enough, sorry.") elif args == "rsa": print(pow(bytes_to_long(flag), 3, getPrime(128)*getPrime(128))) print(pow(xyz, 3, getPrime(128)*getPrime(128))) # random way of getting you to minimize query count. elif ord(args[0]) % (getRandomInteger(7) + 1) == 3: print("Too many RNG calls!") else: try: assert str(int(args)) == args, "get better" if 0 < int(args) <= 128: print(random.randrange(1, 2**int(args))) elif int(args) > 128: print(random.randrange(1, len(str(args)))) else: print("Invalid input") except: try: # limit loop length because it would be bad if it were uncapped. args = int(args[1:]) % 10**5 for i in range(args): random.randrange(1, 2) except: print("Invalid input.") print("Exiting...")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/You_get_extra_information_2/main.py
ctfs/AmateursCTF/2023/crypto/You_get_extra_information_2/main.py
from Crypto.Util.number import * from flag import flag p = getPrime(512) q = getPrime(512) n = p*q e = 0x10001 extra_information = (n**2)*(p**3 + 5*(p+1)**2) + 5*n*q + q**2 ptxt = bytes_to_long(flag) c = pow(ptxt, e, n) with open('output.txt', 'w') as f: f.write(f"n: {n}\nc: {c}\ne: {e}\nextra_information: {extra_information}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/You_get_extra_information_1/main.py
ctfs/AmateursCTF/2023/crypto/You_get_extra_information_1/main.py
from Crypto.Util.number import * from flag import flag p = getPrime(512) q = getPrime(512) n = p*q p = p + q e = 0x10001 extra_information = p + q ptxt = bytes_to_long(flag) c = pow(ptxt, e, n) with open('output.txt', 'w') as f: f.write(f"n: {n}\nc: {c}\ne: {e}\nextra_information: {extra_information}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/Minimalaestic/main.py
ctfs/AmateursCTF/2023/crypto/Minimalaestic/main.py
# based on https://github.com/boppreh/aes/blob/master/aes.py from flag import flag, key import copy KEY_SIZE = 2 ROUNDS = 100 def sub_bytes(s): for i in range(2): s[i][0] = sbox[s[i][0]] def final_sub(s): for i in range(2): s[i][1] = sbox[s[i][1]] sbox = [0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16] def shift_rows(s): s[0][0], s[1][0] = s[1][0], s[0][0] def final_shift(s): s[0][1], s[1][1] = s[1][1], s[0][1] def mix_column(column): column[0] = column[0] ^ column[1] def mix_columns(state): for i in range(2): column = [] for j in range(2): column.append(state[i][j]) mix_column(column) for j in range(2): state[i][j] = column[j] def add_round_key(s, k): for i in range(2): for j in range(2): s[i][j] ^= k[k[k[k[i*2+j]%4]%4]%4] def final_add(s, k): for i in range(2): s[i][1] ^= k[k[k[k[i*2+1]%4]%4]%4] def schedule_key(k): for i in range(4): for j in range(2*ROUNDS): k[i] = pow(pow(sbox[sbox[sbox[((((k[i] << 4) ^ k[i]) << 4) ^ k[i]) % 256]]], pow(k[i], k[i]), 256), pow(sbox[k[i]], sbox[k[i]]), 256) def final_schedule(k): for i in range(4): k[i] = sbox[k[i]] def bytes2matrix(text): return [list(text[i:i+2]) for i in range(0, len(text), 2)] def matrix2bytes(matrix): return bytes(sum(matrix, [])) def pad(plaintext): padding_len = 4 - (len(plaintext) % 4) padding = bytes([padding_len] * padding_len) return plaintext + padding def unpad(plaintext): padding_len = plaintext[-1] assert padding_len > 0 message, padding = plaintext[:-padding_len], plaintext[-padding_len:] assert all(p == padding_len for p in padding) return message def split_blocks(message, block_size=4, require_padding=True): assert len(message) % block_size == 0 or not require_padding return [message[i:i+4] for i in range(0, len(message), block_size)] def encrypt(p, k): ciphertext = b"" for i in split_blocks(pad(p)): key = k.copy() i = bytes2matrix(i) add_round_key(i, key) for j in range(ROUNDS): schedule_key(key) sub_bytes(i) shift_rows(i) mix_columns(i) add_round_key(i, key) final_schedule(key) final_sub(i) final_shift(i) final_add(i, key) ciphertext += matrix2bytes(i) return ciphertext print(encrypt(flag, key).hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/Weak_Primes/main.py
ctfs/AmateursCTF/2023/crypto/Weak_Primes/main.py
from Crypto.Util.number import * from flag import flag def phi(p, q): if p == q: return (p-1)*p else: return (p-1)*(q-1) def getModPrime(modulus): p = 2**2047 + getPrime(128) p += (modulus - p) % modulus p += 1 iters = 0 while not isPrime(p): p += modulus return p flag = bytes_to_long(flag) p = getPrime(2048) q = getModPrime(3) n = p*q e = 65537 d = inverse(e, phi(p, q)) c = pow(flag, e, n) with open('output.txt', 'w') as f: f.write(f"{c} {e} {n}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/The_Vault_2/main.py
ctfs/AmateursCTF/2023/crypto/The_Vault_2/main.py
#!/usr/local/bin/python from flag import flag import sys sys.set_int_max_str_digits(13337) a = input("a: ") b = input("b: ") c = input("c: ") x = input("x: ") y = input("y: ") z = input("z: ") try: a, b, c, x, y, z = list(map(int, [a,b,c,x,y,z])) except: print("Invalid input") exit(0) for i in [a,b,c,x,y,z]: if i <= 10**3000: print("Key not long enough!") exit(0) if a**3 + 12*a**2*c + 48*a*c**2 - b**3 - 18*b**2*c - 108*b*c**2 - 241*c**3 + 3*c**2*x + 12*c**2*y - 48*c**2*z + 3*c*x**2 + 6*c*y**2 - 6*c*z**2 + x**3 + y**3 == 141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141214121412141212488758637498921042944525720568307237104333151014412406868046361656574051443283617353264223083104499701186373847555640986580222462632242450835599012566450500789609955582975746413742616575264413182756310632740215995652579485462835795143115072271196916126598100786252571645439848026242507568551496713555552916037700884530961979760783611520343060653277575777670596653687356833792412579573914468717879366050100745712200481983786309714440258562305904620082422854656240877909714441782540532559885547709235182876694751754537256714169623381476910930042427153614717793035200843605106177687921664274225546602585991018510757319460079698323945401347460386676651609999998731411576878666727667828716674786890916043435562187425283353370111061372111110408019382318920351762734096344232363934850178057445641990965565990725333827824325950058299386434788354241837948312232909177919072995399107014016457441983593506826700668732655559772029479968840585243337024148183128751476307377033210451345983136054676613780111514609962599719331085094992291594744968164483282588171606093863173073039599421841875029884963698301543640207543425642344623015138811721225038162776573317135633195444156610378450917547304967763922184335823400189098127917214297211228676686339948274477454186682305336576681219279691964088095217164795720624628330348810647922401805621551993946419759239939953516266568821636656092766746359740244827643306131103594048126437239496437905899851452177471053012539850118120614097434385504936403727596454855640758700762698797799076987562336417284674410160033185987596961374256107177133469220353886364625402806646561541539272962594957553264094621049454285238451029660043517038100883478390766065860984676088618716893427638345706762328133100275291611716877245561409812753224168496984801008896325035107161198400514779490576604849115527386869873337437234103213530368394062517426771232394255140398534571516108343670906474947812467798373039989348565179463538392079936543225061877607003233504409036916620319367463006744831801738956677004110145448975256215835184982504935765782022144249342480614175071811835543337500507477744150572871386700006542164047767200116554744636264531500700077803067418968180498983184917493185812385940110387266754139950310654766125029688956775635519413767930709870252013546043399816166444767910074718447586172569383825702744500731854671960028445616472270617079064700442663891123026562286407303487937788587408036208197310015214900093141463780291967011964336497721989434121509932419084713261876194758960945283218053198123856736918083433211745469165870566940675835398544403226487513082335746109766749377864046042910722219427313116257665427700822183627656096906977901238978568155040201411044741794198280929106347610392595695128408426325730293715959631813267528375872554233286071035738984840779094588303024093441166337141126923508022300127053414736436085617040907120453814265394563105422607299205832572575616935106790825432361591867521437955425444691390064058193496589901356914616623722908304974006198697928753291209980971961952230876116196600032921823402395138528260710350045401380276935832803533852648974271680396684173492565565435901006448545699751271056244728024328317022854208645802627227052487220798428537247202338922100018724089837669373980011617908044949577955685780155778740139731793711174199544426905808203526395837254855745446935294816875117275820133116837060769978100618769102201079185361231220113943073496262480003215839034087411846876197784842430892575985905565291519816409651923502881310908479671429833859100598350105649657415171877851198997391329546893116533538292182925187961701932020756162132826321472507285375576848902514165435150670192276408429260315132693209979525609123552448427120772069326303118565295699991054985839861648837807372901798394335929583588708534788199741194904651470591887013174546166716494052327310197169753122012868602048501652021373616713307845799876064959641062982547844511802418531889434603463580510389465579979840439720852706420226081733543816259504971077173924658321734750825896168004315709817176481666426574158167885866119913324478331334700882594805493569915087612224938607816853649957604491143933377934786051223773859621387609484841086821036179750684336511664542704064503696782594696045798403178279213663914699384231907644063074098119993590512021784201856440144081080076287706011743828533996824064375067588307553081428140719302377089313214958750661142161567315535563225919738142007736747019716134001614954586772808066460125906094518206571433495658383842303641829468849286922236860363512378150687507019542390689443723694776044633453357733913681890918599770796106466916461979785938583458625694460840559646635950147698609409476923651652695685169715681757552690393636514530111481694531092582878267890976687707081045311685147280283152339583085973373914500796502582920474175794943596195643949365997257232242726696545753812991806251162076738435340580428919552280802716144140340658490094675738966705188772634321382480553839006001374938946766005807948876814587760219117394129686737146641203962346146995996685154762149188459787337121460090385753218802744044656567094214830603508028807952183525664525286537719917536003201610548317551272218442560787254938341839299360813784912352933562434029887064000656772589241274473596251945499850448119743573496213388055382280060600774970493926743695553627904928069400091007601093360869600349402958975723228468064221301653538051874281261336975829074774897467645694546547372495134204929476175241891790887443042678693174917928649569897805106540094657796922667608644951445404487481035710955712743180281348881608104776335978704373415871180666671966442515933684099801439251466626343723708605138930145321224618497610824636631694187750961608567795577666492694126539211827204448166778013191075160886938726303351138606888140981601495002110368980507242276967637362037854043404408580320673787074895029212199203185196539822894936260874472605281595743349280895275432817958674858624133864229341440351333592495709323759069472035504195121890770451326113618485103602320375756075769358267013820120229905046183443675436653241867530241645452143636330911263870734122477724805627591530905010502820063024039384122077085200252300966704220577605309262326322691494112682896053644173375642822732590021777570685877998397222849112107199757604556729346856745339256687415931706534227821680973909758952578754998199421068940957470225199966382868240575050915159972920117915187200196172160693983620552281911967682854020917099313512609413366575780993005754431243535560530200704511232056527495685426943763108198038542913801325722404476375662233591258291165990549943613569804756850557814105573135073705084587006441304956836120245048825058615702976597149626337358752933705649923989429024102429500169378589179237693486758415302190992845894290734580148868637849379707577875731311830127746929876633579608231033726629354774745082823848610498257895258482347042148320618353643797635501471606224158797903933149824493164469678556445927068984426210442115542142705986825215979195738144332469386295963862771968827498046388325475726298974903173754201162046766163790396232533226729433479817592747961860039937245360946426362140110796904732790384506968550383705380164825280527729711095107419522542727950904328902368933760294783249509835202788807103690001315836689083381240103863335190421478448323457674468246942663761228053623933849625560059387667020177076908768459203260788891081489466336690022422796626850639696238674361980506612060347201328798339847183157394858123985123060313407871189834386248711072144229976368534769990624213657699264813712769765629787091292085814399368091688123973385624514465481795741781603450405689748497487333084517209423269399827829862332126436166128489420008723950462724437264893411463062813599091703993991457032975900150121315033378777333806282964851152430807747368676704003820957274749051424985132857816524654010475586971532811157027452906166134625420139370554424342405562296946632174280169415978640163698845139194157374844108409212169392008776300863231577354: print("Access Granted!") print(flag) exit(0) else: print("Bad Key.") exit(0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/Non-Quadratic_Residues/main.py
ctfs/AmateursCTF/2023/crypto/Non-Quadratic_Residues/main.py
from Crypto.Util.number import * from flag import flag def getModPrime(modulus): p = getPrime(1024) p += (modulus - p) % modulus p += 1 iters = 0 while not isPrime(p): p += modulus return p difficulty = 210 flag = bytes_to_long(flag) # no cheeses here! b = getModPrime(difficulty**10) c = inverse(flag, b) n = pow(c, difficulty, b) with open('output.txt', 'w') as f: f.write(f"{n} {b}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/crypto/lce_cream_generator/main.py
ctfs/AmateursCTF/2023/crypto/lce_cream_generator/main.py
#!/usr/local/bin/python from Crypto.Util.number import * from os import urandom from flag import flag class lcg: def __init__(self, p): while (a:=bytes_to_long(urandom(16))) > p: pass while (b:=bytes_to_long(urandom(16))) > p: pass self.a, self.b, self.p = a, b, p seed = 1337 def gen_next(self): self.seed = (self.a*self.seed + self.b) % self.p return self.seed class order: def __init__(self, p): self.p = p self.inner_lcg = lcg(p) for i in range(1337): self.inner_lcg.gen_next() self.flavors = [self.inner_lcg.gen_next() for i in range(1338)] self.flavor_map = {i:self.flavors[i] for i in [1,2,3,4,5,6]} self.private = {i:self.flavors[i] for i in [1,2,3,4,5,6,1337]} bowls = [0, 0, 0] used = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0} recipe = [] def make_bowl(self): global flavor_indices self.bowls = [0, 0, 0] self.recipe = [] new = {} available = [] for i, n in self.used.items(): if n == 0: new[i] = 0 available += [i] self.used = new print("\nREMAINING FLAVORS: ") for i in available: print(f"Flavor {i} - {flavor_indices[i]}") while True: command = input("\nAdd, combine, or finish? ") if command.lower() == "add": try: add = input("\nGive a flavor and a bowl: ").rsplit(" ", 1) self.add(*add) except Exception as e: print() print(e) elif command.lower() == "combine": try: combination = input("\nGive two bowls and an operation: ").split() assert len(combination) == 3, "Invalid Input Length" self.combine_bowl(*combination) except Exception as e: print() print(e) elif command.lower() == "finish bowl": self.finish_bowl() elif command.lower() == "finish": self.finish() break elif command.lower() == "exit": exit(1) else: print("\nPlease give a valid input.") def mod(self): self.bowls = [i % self.p for i in self.bowls] def add(self, flavor, bowl): assert "0" < bowl < "4", "Invalid Bowl" bowl = int(bowl) - 1 global flavor_names if flavor not in ["1", "2", "3", "4", "5", "6"]: try: if self.used[flavor_names[flavor]] < 5: self.bowls[bowl] += self.flavor_map[flavor_names[flavor]] self.used[flavor_names[flavor]] += 1 self.recipe += [[flavor_names[flavor], bowl]] else: print(f"\nCannot order {flavor} due to stock issues.") except: print("\nInvalid Flavor") else: try: flavor = int(flavor) if self.used[flavor] < 5: self.bowls[bowl] += self.flavor_map[flavor] self.used[flavor] += 1 self.recipe += [[flavor, bowl]] else: print(f"\nCannot order {flavor} due to stock issues.") except: print("\nInvalid Flavor") def combine_bowl(self, a, b, op): assert op in ['add', 'sub', 'mult', 'div'], "Invalid Operation. Please choose either 'add', 'sub', 'mult', or 'div'." assert "0" < a < "4" and "0" < b < "4" and a != b, "Invalid Bowl" a = int(a) - 1 b = int(b) - 1 if op == 'add': self.bowls[a] += self.bowls[b] elif op == 'sub': self.bowls[a] -= self.bowls[b] elif op == 'mult': self.bowls[a] *= self.bowls[b] elif op == 'div': assert self.bowls[b] != 0, "Empty Bowl for Division" self.bowls[a] *= pow(self.bowls[b], -1, self.p) else: print("\nwtf") exit(1) self.recipe += [[op, a, b]] self.bowls[b] = 0 self.mod() def finish_bowl(self): unique = 0 for i, n in self.used.items(): if n and n != 1337: unique += 1 if unique < min(3, len(self.used)): print("\nAdd more flavor!") return False recipe = str(self.recipe).replace(' ', '') signature = sum(self.bowls) % self.p self.bowls = [0, 0, 0] self.recipe = [] for i in self.used: if self.used[i]: self.used[i] = 1337 print(f"\nUser #: {self.p}") print(f"\nRecipe: \n{recipe}") print(f"\n\nSignature: \n{signature}") return True def finish(self): if sum(self.bowls): if not self.finish_bowl(): print("\nOk the bowls will be dumped.") print("\nOrder done!") return True def verify(self, recipe, signature): bowls = [0, 0, 0] for i in recipe: try: if len(i) == 2: bowls[i[1]] += self.private[i[0]] elif len(i) == 3: if i[0] == 'add': bowls[i[1]] += bowls[i[2]] elif i[0] == 'sub': bowls[i[1]] -= bowls[i[2]] elif i[0] == 'mult': bowls[i[1]] *= bowls[i[2]] elif i[0] == 'div': bowls[i[1]] *= pow(bowls[i[2]], -1, self.p) bowls[i[2]] = 0 bowls = [i % self.p for i in bowls] except: exit("\nInvalid Recipe") try: assert sum(bowls) % self.p == signature, "\nInvalid Signature" print("\nYou have successfully redeemed your lce cream!") if signature == self.private[1337]: print(flag) except Exception as e: print(e) flavor_names = {"revanilla":1, "cryptolatte":2, "pwnstachio":3, "strawebrry":4, "miscnt":5, "cookie dalgo":6, "flaudge chocolate":1337} flavor_indices = {i:n for n, i in flavor_names.items()} intro = \ """ ---------------------------------------------------- WELCOME TO THE LCE CREAM SHOP! ---------------------------------------------------- HERE AT THE LCE CREAM SHOP WE HAVE A FEW BELIEFS 1. Don't be boring! Choose at least 3 flavors of lce cream. All of it tastes the same anyways... 2. Don't be repetitive! Well... that and the fact that we have some stock issues. After getting one lce cream with one flavor, you don't get to choose that flavor again. 3. Since I rolled my own signature system that is extremely secure, if you can manage to forge an arbitrary flavor, I'll give it to you! As long as it exists... 4. These aren't really beliefs anymore but we only have 6 flavors (available to the customer), and you're only allowed to order once (stock issues again smh). Choose wisely! 5. To help with the boringness, I will allow you to mix flavors in any way you want. But you can only use up to 5 scoops of each flavor to concoct your lce cream (once again stock issues). 6. I AM ONLY ACCEPTING ONE RECIEPT. If the first fails, too bad. 7. I heard there's a special flavor called "flaudge chocolate", it's like the 1337th flavor or something. 8. Orders can have multiple lce cream mixtures, as long as they follow the rules above. 9. I am accepting reciepts for TAX PURPOSES only. 10. Each scoop costs $5 (stock issues AGAIN). 11. The reciept itself costs $1. 12. Everything is free. Have fun! 13. Zero indexing sucks. Here at LCE CREAM SHOP we use one indexing. Oh yeah here are the options:""" options = \ """ OPTIONS: (1) Generate order (2) View flavors (3) Redeem a reciept (4) Exit Choice: """ print(intro) while True: choice = input(options) if choice == "1": if 'user' in vars(): print("\nYou already ordered.") continue user = order(getPrime(128)) user.make_bowl() print() elif choice == "2": print("\nThe only valid flavors are: ") [print(f"Flavor {i} - {n}") for i, n in flavor_indices.items() if i != 1337] elif choice == "3": if 'user' not in vars(): print("\nNo user.") else: userid = int(input("\nENTER NUMBER: ")) assert userid == user.p, "You seem to have lost your reciept." recipe = input("\nENTER RECIPE: ") assert all([i in "[,]01234567abdilmstuv'" for i in recipe]), "\n\nSir, please don't put junk in my lce cream machine!" recipe = eval(recipe, {"__builtins__": {}}, {"__builtins__": {}}) # screw json or ast.literal_eval signature = input("\nENTER SIGNATURE: ") user.verify(recipe, int(signature)) exit("\nGoodbye.") elif choice == "4": exit("\nGoodbye.") else: print("\nINVALID CHOICE. Please input '1', '2', '3', or '4'")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/web/funny_factorials/app.py
ctfs/AmateursCTF/2023/web/funny_factorials/app.py
from flask import Flask, render_template, request import sys app = Flask(__name__) def factorial(n): if n == 0: return 1 else: try: return n * factorial(n - 1) except RecursionError: return 1 def filter_path(path): # print(path) path = path.replace("../", "") try: return filter_path(path) except RecursionError: # remove root / from path if it exists if path[0] == "/": path = path[1:] print(path) return path @app.route('/') def index(): safe_theme = filter_path(request.args.get("theme", "themes/theme1.css")) f = open(safe_theme, "r") theme = f.read() f.close() return render_template('index.html', css=theme) @app.route('/', methods=['POST']) def calculate_factorial(): safe_theme = filter_path(request.args.get("theme", "themes/theme1.css")) f = open(safe_theme, "r") theme = f.read() f.close() try: num = int(request.form['number']) if num < 0: error = "Invalid input: Please enter a non-negative integer." return render_template('index.html', error=error, css=theme) result = factorial(num) return render_template('index.html', result=result, css=theme) except ValueError: error = "Invalid input: Please enter a non-negative integer." return render_template('index.html', error=error, css=theme) if __name__ == '__main__': sys.setrecursionlimit(100) app.run(host='0.0.0.0')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KnightCTF/2022/crypto/Tony_Stark_Needs_Help_Again/encryptor.py
ctfs/KnightCTF/2022/crypto/Tony_Stark_Needs_Help_Again/encryptor.py
import base64 str1 = input("Enter text to encrypt: ") arr1 = [] l_c = ''.join(chr(c) for c in range (97,123)) u_c = ''.join(chr(c) for c in range (65,91)) l_e = l_c[13:] + l_c[:13] u_e = u_c[13:] + u_c[:13] so = "" for c in str1: if c in l_c: so = so + l_e[l_c.find(c)] elif c in u_c: so = so + u_e[u_c.find(c)] else: so = so + c d1 = { "A" : "~", "B" : "`", "C" : "@", "D" : "#", "E" : "$", "F" : "%", "G" : "^", "H" : "&", "I" : "*", "J" : "(", "K" : ")", "L" : "-", "M" : "_", "N" : "=", "O" : "+", "P" : "{", "Q" : "[", "R" : "]", "S" : ":", "T" : ";", "U" : "\'", "V" : "\"", "W" : ",", "X" : "<", "Y" : ".", "Z" : ">", "a" : "?", "b" : "/", "c" : "5", "d" : "1", "e" : "3", "f" : "2", "g" : "4", "h" : "9", "i" : "0", "j" : "8", "k" : "6", "l" : "7", "m" : "K", "n" : "Q", "o" : "F", "p" : "V", "q" : "X", "r" : "D", "s" : "S", "t" : "A", "u" : "J", "v" : "N", "w" : "M", "x" : "P", "y" : "I", "z" : "T", "~" : "A", "`" : "B", "@" : "C", "#" : "D", "$" : "E", "%" : "F", "^" : "G", "&" : "H", "*" : "I", "(" : "J", ")" : "K", "-" : "L", "_" : "M", "=" : "N", "+" : "O", "{" : "P", "[" : "Q", "]" : "R", ":" : "S", ";" : "T", "\'" : "U", "\"" : "V", "," : "W", "<" : "X", "." : "Y", ">" : "Z", "?" : "a", "/" : "b", "5" : "c", "1" : "d", "3" : "e", "2" : "f", "4" : "g", "9" : "h", "0" : "i", "8" : "j", "6" : "k", "7" : "l", } vas1 = "" for i in so: scr1 = str(d1.get(i)) vas1 += str(scr1) for c in vas1: arr1.append(ord(c)) arr2 = [] for i in arr1: if i % 2 == 0: i += 2 else: i += 1 arr2.append(i) saa2t = "" for c in arr2: saa2t += chr(c) d2 = { "~" : "A", "`" : "B", "@" : "C", "#" : "D", "$" : "E", "%" : "F", "^" : "G", "&" : "H", "*" : "I", "(" : "J", ")" : "K", "-" : "L", "_" : "M", "=" : "N", "+" : "O", "{" : "P", "[" : "Q", "]" : "R", ":" : "S", ";" : "T", "\'" : "U", "\"" : "V", "," : "W", "<" : "X", "." : "Y", ">" : "Z", "?" : "a", "/" : "b", "5" : "c", "1" : "d", "4" : "e", "2" : "f", "3" : "g", "9" : "h", "0" : "i", "8" : "j", "6" : "k", "7" : "l", "K" : "m", "Q" : "n", "F" : "o", "V" : "p", "X" : "q", "D" : "r", "S" : "s", "A" : "t", "J" : "u", "N" : "v", "M" : "w", "P" : "x", "I" : "y", "T" : "z", "A" : "~", "B" : "`", "C" : "*", "D" : "#", "E" : "$", "F" : "%", "G" : "^", "H" : "&", "I" : "@", "J" : "(", "K" : ")", "L" : "-", "M" : "_", "N" : "=", "O" : "+", "P" : "{", "Q" : "[", "R" : "]", "S" : ":", "T" : ";", "U" : "\'", "V" : "\"", "W" : ",", "X" : "<", "Y" : ".", "Z" : ">", "a" : "?", "b" : "/", "c" : "5", "d" : "7", "e" : "3", "f" : "2", "g" : "4", "h" : "9", "i" : "0", "j" : "8", "k" : "6", "l" : "1", } vas2 = "" for i in saa2t: scr2 = str(d2.get(i)) vas2 += str(scr2) sarev = vas2[::-1] msg_b = sarev.encode("ascii") b64_bytes = base64.b64encode(msg_b) b64_string = b64_bytes.decode("ascii") print(b64_string)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KnightCTF/2022/crypto/Tony_Stark_Needs_Help/encryptor.py
ctfs/KnightCTF/2022/crypto/Tony_Stark_Needs_Help/encryptor.py
secret = input("Enter your string to encrypt: ") key = input("Enter the key: ") secarr = [] keyarr = [] x = 0 def keyfunc(key,keyarr,x): for character in key: keyarr.append(ord(character)) for i in keyarr: x += i def secretfucn(secret,secarr,key,x): for character in secret: secarr.append(ord(character)) for i in range(len(secarr)): if 97 <= secarr[i] <= 122: secarr[i] = secarr[i]-6 else: if 65 <= secarr[i] <= 90: secarr[i] = secarr[i]-11 if len(key) % 2 == 0: x = x + 1 else: x = x + 3 if x % 2 == 0: secarr[i] = secarr[i] + 3 else: secarr[i] = secarr[i] + 2 encrypted = "" for val in secarr: encrypted = encrypted + chr(val) print("Encrypted Text: " + encrypted) keyfunc(key,keyarr,x) secretfucn(secret,secarr,key,x)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KnightCTF/2022/crypto/Jumble/enc.py
ctfs/KnightCTF/2022/crypto/Jumble/enc.py
def f(t): c = list(t) for i in range(len(t)): for j in range(i, len(t) - 1): c[j], c[j+1] = c[j+1], c[j] return "".join(c) if __name__ == "__main__": flag = open("flag", "r").read() open("ciphertext", "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/KnightCTF/2022/crypto/Feistival/enc.py
ctfs/KnightCTF/2022/crypto/Feistival/enc.py
m, n = 21, 22 def f(word, key): out = "" for i in range(len(word)): out += chr(ord(word[i]) ^ key) return out flag = open("flag.txt", "r").read() L, R = flag[0:len(flag)//2], flag[len(flag)//2:] x = "".join(chr(ord(f(R, m)[i]) ^ ord(L[i])) for i in range(len(L))) y = f(R, 0) L, R = y, x x = "".join(chr(ord(f(R, n)[i]) ^ ord(L[i])) for i in range(len(L))) y = f(R, 0) ciphertext = x + y ct = open("cipher.txt", "w") ct.write(ciphertext) ct.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/pwn/javascript_for_dummies_part_2/build/release/connect.py
ctfs/Zh3r0/2021/pwn/javascript_for_dummies_part_2/build/release/connect.py
#!/usr/bin/python3 import sys import os import binascii import re import subprocess import signal def handler(x, y): sys.exit(-1) signal.signal(signal.SIGALRM, handler) signal.alarm(30) def gen_filename(): return '/tmp/' + binascii.hexlify(os.urandom(16)).decode('utf-8') EOF = 'zh3r0-CTF' MAX_SIZE = 10000 def main(): print(f'Give me the source code(size < {MAX_SIZE}). EOF word is `{EOF}\'') sys.stdout.flush() size = 0 code = '' while True: s = sys.stdin.readline() size += len(s) if size > MAX_SIZE: print('too long') sys.stdout.flush() return False idx = s.find(EOF) if idx < 0: code += s else: code += s[:idx] break filename = gen_filename() + ".js" with open(filename, 'w') as f: f.write(code) os.close(1) os.close(2) os.system(f'./run.sh {filename}') main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/pwn/javascript_for_dummies_part_1/build/release/connect.py
ctfs/Zh3r0/2021/pwn/javascript_for_dummies_part_1/build/release/connect.py
#!/usr/bin/python3 import sys import os import binascii import re import subprocess import signal def handler(x, y): sys.exit(-1) signal.signal(signal.SIGALRM, handler) signal.alarm(30) def gen_filename(): return '/tmp/' + binascii.hexlify(os.urandom(16)).decode('utf-8') EOF = 'zh3r0-CTF' MAX_SIZE = 10000 def main(): print(f'Give me the source code(size < {MAX_SIZE}). EOF word is `{EOF}\'') sys.stdout.flush() size = 0 code = '' while True: s = sys.stdin.readline() size += len(s) if size > MAX_SIZE: print('too long') sys.stdout.flush() return False idx = s.find(EOF) if idx < 0: code += s else: code += s[:idx] break filename = gen_filename() + ".js" with open(filename, 'w') as f: f.write(code) os.close(1) os.close(2) os.system(f'./run.sh {filename}') main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/crypto/twist_and_shout/challenge.py
ctfs/Zh3r0/2021/crypto/twist_and_shout/challenge.py
from secret import flag import os import random state_len = 624*4 right_pad = random.randint(0,state_len-len(flag)) left_pad = state_len-len(flag)-right_pad state_bytes = os.urandom(left_pad)+flag+os.urandom(right_pad) state = tuple( int.from_bytes(state_bytes[i:i+4],'big') for i in range(0,state_len,4) ) random.setstate((3,state+(624,),None)) outputs = [random.getrandbits(32) for i in range(624)] print(*outputs,sep='\n')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/crypto/chaos/challenge.py
ctfs/Zh3r0/2021/crypto/chaos/challenge.py
from secret import flag def ROTL(value, bits, size=32): return ((value % (1 << (size - bits))) << bits) | (value >> (size - bits)) def ROTR(value, bits, size=32): return ((value % (1 << bits)) << (size - bits)) | (value >> bits) def pad(pt): pt+=b'\x80' L = len(pt) to_pad = 60-(L%64) if L%64 <= 60 else 124-(L%64) padding = bytearray(to_pad) + int.to_bytes(L-1,4,'big') return pt+padding def hash(text:bytes): text = pad(text) text = [int.from_bytes(text[i:i+4],'big') for i in range(0,len(text),4)] M = 0xffff x,y,z,u = 0x0124fdce, 0x89ab57ea, 0xba89370a, 0xfedc45ef A,B,C,D = 0x401ab257, 0xb7cd34e1, 0x76b3a27c, 0xf13c3adf RV1,RV2,RV3,RV4 = 0xe12f23cd, 0xc5ab6789, 0xf1234567, 0x9a8bc7ef for i in range(0,len(text),4): X,Y,Z,U = text[i]^x,text[i+1]^y,text[i+2]^z,text[i+3]^u RV1 ^= (x := (X&0xffff)*(M - (Y>>16)) ^ ROTL(Z,1) ^ ROTR(U,1) ^ A) RV2 ^= (y := (Y&0xffff)*(M - (Z>>16)) ^ ROTL(U,2) ^ ROTR(X,2) ^ B) RV3 ^= (z := (Z&0xffff)*(M - (U>>16)) ^ ROTL(X,3) ^ ROTR(Y,3) ^ C) RV4 ^= (u := (U&0xffff)*(M - (X>>16)) ^ ROTL(Y,4) ^ ROTR(Z,4) ^ D) for i in range(4): RV1 ^= (x := (X&0xffff)*(M - (Y>>16)) ^ ROTL(Z,1) ^ ROTR(U,1) ^ A) RV2 ^= (y := (Y&0xffff)*(M - (Z>>16)) ^ ROTL(U,2) ^ ROTR(X,2) ^ B) RV3 ^= (z := (Z&0xffff)*(M - (U>>16)) ^ ROTL(X,3) ^ ROTR(Y,3) ^ C) RV4 ^= (u := (U&0xffff)*(M - (X>>16)) ^ ROTL(Y,4) ^ ROTR(Z,4) ^ D) return int.to_bytes( (RV1<<96)|(RV2<<64)|(RV3<<32)|RV4 ,16,'big') try: m1 = bytes.fromhex(input("input first string to hash : ")) m2 = bytes.fromhex(input("input second string to hash : ")) if m1!=m2 and hash(m1)==hash(m2): print(flag) else: print('Never gonna give you up') except: print('Never gonna let you down')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/crypto/real_mersenne/challenge.py
ctfs/Zh3r0/2021/crypto/real_mersenne/challenge.py
import random from secret import flag from fractions import Fraction def score(a,b): if abs(a-b)<1/2**10: # capping score to 1024 so you dont get extra lucky return Fraction(2**10) return Fraction(2**53,int(2**53*a)-int(2**53*b)) total_score = 0 for _ in range(2000): try: x = random.random() y = float(input('enter your guess:\n')) round_score = score(x,y) total_score+=float(round_score) print('total score: {:0.2f}, round score: {}'.format( total_score,round_score)) if total_score>10**6: print(flag) exit(0) except: print('Error, exiting') exit(1) else: print('Maybe better luck next time')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/crypto/alice_bob_dave/chall.py
ctfs/Zh3r0/2021/crypto/alice_bob_dave/chall.py
from Crypto.Util.number import * from secret import msg_a,msg_b e=65537 p,q,r=[getStrongPrime(1024,e) for _ in range(3)] pt_a=bytes_to_long(msg_a) pt_b=bytes_to_long(msg_b) n_a=p*q n_b=p*r phin_a=(p-1)*(q-1) phin_b=(p-1)*(r-1) d_a=inverse(e,phin_a) d_b=inverse(e,phin_b) ct_a=pow(pt_a,e,n_a) ct_b=pow(pt_b,e,n_b) print(f"{ct_a=}\n{ct_b=}\n{d_a=}\n{d_b=}\n{e=}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/crypto/import_numpy_as_MT/challenge.py
ctfs/Zh3r0/2021/crypto/import_numpy_as_MT/challenge.py
import os from numpy import random from Crypto.Cipher import AES from Crypto.Util.Padding import pad from secret import flag def rand_32(): return int.from_bytes(os.urandom(4),'big') flag = pad(flag,16) for _ in range(2): # hate to do it twice, but i dont want people bruteforcing it random.seed(rand_32()) iv,key = random.bytes(16), random.bytes(16) cipher = AES.new(key,iv=iv,mode=AES.MODE_CBC) flag = iv+cipher.encrypt(flag) print(flag.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Zh3r0/2021/crypto/1n_jection/challenge.py
ctfs/Zh3r0/2021/crypto/1n_jection/challenge.py
from secret import flag def nk2n(nk): l = len(nk) if l==1: return nk[0] elif l==2: i,j = nk return ((i+j)*(i+j+1))//2 +j return nk2n([nk2n(nk[:l-l//2]), nk2n(nk[l-l//2:])]) print(nk2n(flag)) #2597749519984520018193538914972744028780767067373210633843441892910830749749277631182596420937027368405416666234869030284255514216592219508067528406889067888675964979055810441575553504341722797908073355991646423732420612775191216409926513346494355434293682149298585
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/pwn/wyze_guy/webserver.py
ctfs/K3RN3L/2021/pwn/wyze_guy/webserver.py
import SocketServer import BaseHTTPServer import CGIHTTPServer class ThreadingCGIServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer): pass import sys server = ThreadingCGIServer(('', 4444), CGIHTTPServer.CGIHTTPRequestHandler) # try: while 1: sys.stdout.flush() server.handle_request() except KeyboardInterrupt: print "Finished"
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py
ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py
#!/usr/bin/env python3 # # Polymero # # Imports import os class BeeHive: """ Surrounding their beehive, the bees can feast on six flower fields with six flowers each. """ def __init__(self, key): """ Initialise the bee colony. """ self.fields = self.plant_flowers(key) self.nectar = None self.collect() def plant_flowers(self, key): """ Plant flowers around the beehive. """ try: if type(key) != bytes: key = bytes.fromhex(key) return [FlowerField(key[i:i+6]) for i in range(0,36,6)] except: raise ValueError('Invalid Key!') def collect(self): """ Collect nectar from the closest flowers. """ A,B,C,D,E,F = [i.flowers for i in self.fields] self.nectar = [A[2]^^B[4],B[3]^^C[5],C[4]^^D[0],D[5]^^E[1],E[0]^^F[2],F[1]^^A[3]] def cross_breed(self): """ Cross-breed the outermost bordering flowers. """ def swap_petals(F1, F2, i1, i2): """ Swap the petals of two flowers. """ F1.flowers[i1], F2.flowers[i2] = F2.flowers[i2], F1.flowers[i1] A,B,C,D,E,F = self.fields swap_petals(A,B,1,5) swap_petals(B,C,2,0) swap_petals(C,D,3,1) swap_petals(D,E,4,2) swap_petals(E,F,5,3) swap_petals(F,A,0,4) def pollinate(self): """ Have the bees pollinate their flower fields (in order). """ bees = [i for i in self.nectar] A,B,C,D,E,F = self.fields for i in range(6): bees = [[A,B,C,D,E,F][i].flowers[k] ^^ bees[k] for k in range(6)] self.fields[i].flowers = bees def stream(self, n=1): """ Produce the honey... I mean keystream! """ buf = [] # Go through n rounds for i in range(n): # Go through 6 sub-rounds for field in self.fields: field.rotate() self.cross_breed() self.collect() self.pollinate() # Collect nectar self.collect() buf += self.nectar return buf def encrypt(self, msg): """ Beecrypt your message! """ beeline = self.stream(n = (len(msg) + 5) // 6) cip = bytes([beeline[i] ^^ msg[i] for i in range(len(msg))]) return cip class FlowerField: """ A nice field perfectly suited for a total of six flowers. """ def __init__(self, flowers): """ Initialise the flower field. """ self.flowers = [i for i in flowers] def rotate(self): """ Crop-rotation is important! """ self.flowers = [self.flowers[-1]] + self.flowers[:-1] some_text = b'Bees make honey, but they also made the Bee Movie... flag{_REDACTED_}' flag = BeeHive(os.urandom(36).hex()).encrypt(some_text).hex() print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Vietas_Poly/template.py
ctfs/K3RN3L/2021/crypto/Vietas_Poly/template.py
from pwn import * context.log_level = 'debug' #will print all input and output for debugging purposes conn = remote("server",port) #enter the address and the port here as strings. For example nc 0.0.0.0 5000 turns into remote('0.0.0.0', 5000) def get_input(): #function to get one line from the netcat input = conn.recvline().strip().decode() return input def parse(polynomial): ''' TODO: Parse polynomial For example, parse("x^3 + 2x^2 - x + 1") should return [1,2,-1,1] ''' for _ in range(4): get_input() #ignore challenge flavortext for i in range(100): type = get_input() coeffs = parse(get_input()) print(coeffs) ans = -1 if 'sum of the roots' in type: ans = -1 #TODO: Find answer elif 'sum of the reciprocals of the roots' in type: ans = -1 #TODO: Find answer elif 'sum of the squares of the roots' in type: ans = -1 #TODO: Find answer conn.sendline(str(ans)) #send answer to server get_input() conn.interactive() #should print flag if you got everything right
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Objection/objection.py
ctfs/K3RN3L/2021/crypto/Objection/objection.py
#!/usr/bin/env python3 # # Polymero # # Imports import hashlib, secrets, json from Crypto.PublicKey import DSA # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() class CCC: """ Certified Certificate Certifier. (It's just DSA...) """ def __init__(self, p, q, g): """ Initialise class object. """ self.p = p self.q = q self.g = g self.sk = secrets.randbelow(self.q) self.pk = pow(self.g, self.sk, self.p) def inv(self, x, p): """ Return modular multiplicative inverse over prime field. """ return pow(x, p-2, p) def H_int(self, m): """ Return integer hash of byte message. """ return int.from_bytes(hashlib.sha256(m).digest(),'big') def bake(self, m, r, s): """ Return JSON object of signed message. """ return json.dumps({ 'm' : m.hex() , 'r' : r , 's' : s }) def sign(self, m): """ Sign a message. """ h = self.H_int(m) k = secrets.randbelow(self.q) r = pow(self.g, k, self.p) % self.q s = ( self.inv(k, self.q) * (h + self.sk * r) ) % self.q assert self.verify_recv(m, r, s, self.pk) return self.bake(m, r, s) def verify_recv(self, m, r, s, pk): """ Verify a message received from pk holder. """ if r < 2 or r > self.q-2 or s < 2 or s > self.q-1: return False h = self.H_int(m) u = self.inv(s, self.q) v = (h * u) % self.q w = (r * u) % self.q return r == ((pow(self.g,v,self.p) * pow(pk,w,self.p)) % self.p) % self.q #------------------------------------------------------------------------------------------------------------ # SERVER CODE #------------------------------------------------------------------------------------------------------------ HDR = r"""| | ___ ____ ____ ___ __ ______ ____ ___ ____ __ | / \ | \ | | / _] / ]| || | / \ | \ | | | | || o ) |__ | / [_ / / | | | | | || _ || | | | O || | __| || _] / / |_| |_| | | | O || | ||__| | | || O |/ | || [_ / \_ | | | | | || | | __ | | || |\ ` || |\ | | | | | | || | || | | \___/ |_____| \____||_____| \____| |__| |____| \___/ |__|__||__| |""" MENU = r"""| | Domain Controller options: | [G]enerate new domain parameters | [P]rovide domain parameters | | Network options: | [S]end signed message to Harry |""" print(HDR) # Set up domain domain = DSA.generate(1024) P,Q = domain.p, domain.q G_default = domain.g # Set up static clients Auth1 = None Auth2 = None Harry = None # Set win conditions WIN1 = False WIN2 = False print('| Current domain parameters:') print('| P =',P) print('| Q =',Q) print('| G (default) =',G_default) print('|') while True: if WIN1 and WIN2: print('|\n| Objection!!!\n| You have done it! Harry will hopefully never hoard again... {}'.format(FLAG)) break print(MENU) try: choice = input('| >> ').lower() if choice == 'g': domain = DSA.generate(1024) P, Q = domain.p, domain.q G_default = domain.g print('|\n| Current domain parameters:') print('| P =',P) print('| Q =',Q) print('| G (default) =',G_default) print('|') elif choice == 'p': # Reset win conditions WIN1 = False WIN2 = False print('|\n| [1] Authenticator Alice') print('| [2] Certifier Carlo') print('| [3] Harry the Flag Hoarder') target = input('|\n| >> Target: ') try: G_user = int(input('| >> G_user (empty for default): ')) except: G_user = G_default if G_user < 2 or G_user > P-2: print('|\n| USER INPUT ERROR -- A valid generator is within the range {2 ... Q-2}.') continue if pow(G_user,Q,P) != 1: print('|\n| USER INPUT ERROR -- A valid generator has order Q.') continue if target == '1': Auth1 = CCC(P,Q,G_user) print("|\n| Authenticator Alice's public key: {}".format(Auth1.pk)) elif target == '2': Auth2 = CCC(P,Q,G_user) print("|\n| Certifier Carlo's public key: {}".format(Auth2.pk)) elif target == '3': Harry = CCC(P,Q,G_user) print("|\n| Harry's public key: {}".format(Harry.pk)) else: print('|\n| USER INPUT ERROR -- Unknown target.') elif choice == 's': try: signed_msg = input('|\n| JSON object (m,r,s,pk): ') jsonobject = json.loads(signed_msg) if Harry.verify_recv(jsonobject['m'],jsonobject['r'],jsonobject['s'],jsonobject['pk']): if jsonobject['m'] == b'I, Authenticator Alice, do not concur with the hoarding of flags.'.hex() and jsonobject['pk'] == Auth1.pk: WIN1 = True elif jsonobject['m'] == b'I, Certifier Carlo, do not concur with the hoarding of flags.'.hex() and jsonobject['pk'] == Auth2.pk: WIN2 = True print('|\n| Your message was delivered succesfully.') else: print('|\n| VERIFICATION ERROR -- Message was rejected.') except: print('|\n| USER INPUT ERROR -- Invalid input.') else: print('|\n| USER INPUT ERROR -- Unknown option.') except KeyboardInterrupt: print('\n|\n| ~ OVERRULED!\n|') break except: print('|\n| RUN ERROR -- An unknown error has occured.')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Pascal_RSA/main.py
ctfs/K3RN3L/2021/crypto/Pascal_RSA/main.py
triangle =[[1]] flag = open('flag.txt','rb').read() from Crypto.Util.number import getPrime,bytes_to_long from math import gcd p = getPrime(20) while len(triangle[-1]) <= p: r = [1] for i in range(len(triangle[-1]) - 1): r.append(triangle[-1][i] + triangle[-1][i+1]) r.append(1) triangle.append(r) code = '' for x in triangle[-1]: code+=str(x%2) d = int(code,2) while True: P = getPrime(512) Q = getPrime(512) if gcd(d, (P-1)*(Q-1)) == 1: N = P*Q e = pow(d,-1,(P-1)*(Q-1)) break enc = pow(bytes_to_long(flag), e, N) file = open('challenge.txt','w') file.write(f'p = {p}\nenc = {enc}\nN = {N}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Cozzmic_Dizzcovery/pandorascomb.py
ctfs/K3RN3L/2021/crypto/Cozzmic_Dizzcovery/pandorascomb.py
#!/usr/bin/env python3 # Imports import os # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() HDR = r"""| | | 15 26 | \ 17 18 19 20 / | 14 16 \ | | | | / 21 25 | \ | \| | | |/ | / | \ | |_____| |_____| | / | 13 \| / \ / \ |/ 24 | \ |_____/ \_____/ \_____| / | \ / \ / \ / \ / | \/ \_____/ \_____/ \/ | 12 \ / \ / \ / 23 | \ \_____/ \_____/ \_____/ / | \ / \ / \ / \ / | \/ \_____/ \_____/ \/ | 11 /\ / \ / \ /\ 22 | \/ \_____/ \_____/ \_____/ \/ | /\ / \ / \ / \ /\ | 10 \/ \_____/ \_____/ \/ 31 | /\ / \ / \ /\ | / \_____/ \_____/ \_____/ \ | / / \ / \ / \ \ | 9 / \_____/ \_____/ \ 30 | /\ / \ / \ /\ | / \_____/ \_____/ \_____/ \ | / | \ / \ / | \ | 8 /| \_____/ \_____/ |\ 29 | / | | | | | | \ | / | /| | | |\ | \ | 7 0 / | | | | \ 5 28 | / 1 2 3 4 \ | 6 27 |""" # Encryption class PandorasComb: def __init__(self,key_62): if type(key_62) == str: key_62 = bytes.fromhex(key_62) self.key = key_62 key_62 = list(key_62) self.state = [[' ']+key_62[:9]+[' '],key_62[9:20],key_62[20:31], key_62[31:42],key_62[42:53],[' ']+key_62[53:]+[' ']] def shoot(self, indir, ray, verbose=False): shoot_dic = { 0 : [[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9]], 1 : [[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[1,10]], 2 : [[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],[2,10]], 3 : [[3,0],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6],[3,7],[3,8],[3,9],[3,10]], 4 : [[4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[4,6],[4,7],[4,8],[4,9],[4,10]], 5 : [[5,1],[5,2],[5,3],[5,4],[5,5],[5,6],[5,7],[5,8],[5,9]], 6 : [[1,0],[2,0],[2,1],[3,1],[3,2],[4,2],[4,3],[5,3],[5,4]], 7 : [[0,1],[1,1],[1,2],[2,2],[2,3],[3,3],[3,4],[4,4],[4,5],[5,5],[5,6]], 8 : [[0,2],[0,3],[1,3],[1,4],[2,4],[2,5],[3,5],[3,6],[4,6],[4,7],[5,7],[5,8]], 9 : [[0,4],[0,5],[1,5],[1,6],[2,6],[2,7],[3,7],[3,8],[4,8],[4,9],[5,9]], 10 : [[0,6],[0,7],[1,7],[1,8],[2,8],[2,9],[3,9],[3,10],[4,10]], 11 : [[0,4],[0,3],[1,3],[1,2],[2,2],[2,1],[3,1],[3,0],[4,0]], 12 : [[0,6],[0,5],[1,5],[1,4],[2,4],[2,3],[3,3],[3,2],[4,2],[4,1],[5,1]], 13 : [[0,8],[0,7],[1,7],[1,6],[2,6],[2,5],[3,5],[3,4],[4,4],[4,3],[5,3],[5,2]], 14 : [[0,9],[1,9],[1,8],[2,8],[2,7],[3,7],[3,6],[4,6],[4,5],[5,5],[5,4]], 15 : [[1,10],[2,10],[2,9],[3,9],[3,8],[4,8],[4,7],[5,7],[5,6]] } if indir > 15: indir %= 16 path = shoot_dic[indir] for i in range(len(shoot_dic[indir])): ray ^= self.state[path[-(i+1)][0]][path[-(i+1)][1]] self.state[path[-(i+1)][0]][path[-(i+1)][1]] = ray else: path = shoot_dic[indir] for i in range(len(path)): ray ^= self.state[path[i][0]][path[i][1]] self.state[path[i][0]][path[i][1]] = ray if verbose: print(self.state) return ray def __main__(): try: PB = PandorasComb(os.urandom(62)) print('|\n|\n| "Here, this is that Comb I was talking about..."') print(HDR) print('|\n|\n| "It seems any byte-ray we send in, interacts with the vertices of the Comb."') print('| "At every vertex, the ray XORs itself with the internal state of the Comb at said vertex."') print('| "So, we have new_state = new_ray = ray ^ state."') print('|\n| "The numbers in the schematic represent the directions from which we can shoot our bytes through the Comb."') while True: print('|\n|\n| "What shall we do with it?"') print('|') print('| [1] Send a byte') print('| [2] Press the button') print('| [3] Shake the Comb (angrily)') print('| [4] Run away') pick = input("|\n| >> ") if pick == '1': print('|\n|\n| "What do you want to send and where?" - (direction, byte) e.g. (1, 255)') send = input("|\n| >> ") try: recv = send.replace('(','').replace(')','').replace(' ','').split(',') print('|\n| And out comes:', PB.shoot(int(recv[0]),int(recv[1]))) except: print('|\n| "Sorry I don\'t understand that..."') continue elif pick == '2': print('|\n|\n| "Alright, here goes nothing..."\n|') for i,byt in enumerate(FLAG): indir = int(os.urandom(1)[0]/256*6) print('| ({}, {})'.format(indir, PB.shoot(indir, byt))) elif pick == '3': print("|\n|\n| After some shaking, the Comb buzzes lightly. Hearing it fills you with Determination.") print("| Its inner state has been randomised.") PB = PandorasComb(os.urandom(62)) elif pick == '4': print("|\n| You can't run away from Trainer Battles!") elif pick in ['exit','quit','leave']: print('\n|\n| "Are you just gonna leave me with it?"\n|\n|') break else: print('|\n| "I can\'t do that!?"\n|') continue except KeyboardInterrupt: print('\n|\n| "Are you just gonna leave me with it?"\n|\n|') except: print('|') print('| *BOOOOOM !!!*') print('|') print('| "Hey.. hey! What have you done to my box!?"') print('|') print('| "Get out you!"') print('|') __main__()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/1-800-758-6237/1-800-758-6237.py
ctfs/K3RN3L/2021/crypto/1-800-758-6237/1-800-758-6237.py
#!/usr/bin/env python3 # # Polymero # # Imports from Crypto.Cipher import AES import os, time, random # Local imports with open('flag.txt', 'rb') as f: FLAG = f.read() f.close() def leak(drip): rinds = sorted(random.sample(range(len(drip)+1), 16)) for i in range(len(rinds)): ind = rinds[i] + i*len(b'*drip*') drip = drip[:ind] + b'*drip*' + drip[ind:] aes = AES.new(key=server_key, mode=AES.MODE_CTR, nonce=b'NEEDaPLUMBER') return aes.encrypt(drip).hex() server_key = os.urandom(16) while True: print(leak(FLAG)) time.sleep(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/3in1/AES.py
ctfs/K3RN3L/2021/crypto/3in1/AES.py
from Crypto.Cipher import AES from Crypto.Hash import SHA256 f = open('progress.txt', 'r') password = ("abda") hash_obj = SHA256.new(password.encode('utf-8')) hkey = hash_obj.digest() def encrypt(info): msg = info BLOCK_SIZE = 16 PAD = "{" padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD cipher = AES.new(hkey, AES.MODE_ECB) result = cipher.encrypt(padding(msg).encode('utf-8')) return result msg = f.read() cipher_text = encrypt(msg) print(cipher_text) #Encrypted: b'\x1bkw\x00\x01#\x1dv\xd1\x1e\xfb\xba\xac_b\x02T\xfbZ\xca\xac8Y\\8@4\xba;\xe1\x11$\x19\xe8\x89t\t\xc8\xfd\x93\xd8-\xba\xaa\xbe\xf1\xa0\xab\x18\xa0\x12$\x9f\xdb\x08~\x81O\xf0y\xe9\xef\xc41\x1a$\x1cN3\xe8F\\\xef\xc1G\xeb\xdb\xa1\x93*F\x1b|\x1c\xec\xa3\x04\xbf\x8a\xd9\x16\xbc;\xd2\xaav6pWX\xc1\xc0o\xab\xd5V^\x1d\x11\xe4}6\xa4\x1b\\G\xd4e\xc2mP\xdb\x9b\x9f\xb0Z\xf12'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/United_Trees_Of_America/main.py
ctfs/K3RN3L/2021/crypto/United_Trees_Of_America/main.py
import random import math from Crypto.Util.number import * def isPrime(p): for i in range(2,int(math.sqrt(p))+1): if p%i==0: return False return True flag = bytes_to_long(open('flag.txt','rb').read()) p = int(input('Enter a prime: ')) assert 10<p, 'Prime too small' assert p<250, 'Prime too big' assert isPrime(p), 'Number not prime' coeffs = [random.getrandbits(128) for _ in range(1000)] k = sum([coeffs[i] for i in range(0,len(coeffs),p-1)]) coeffs[0] += flag - k def poly(coeffs,n,p): return sum([c*pow(n,i,p) for i,c in enumerate(coeffs)])%p n = int(input('Enter a number: ')) assert 1<n<p-1, 'We\'re feeling sneaky today, hmm?' op = 0 for i in range(1,p): op += poly(coeffs,pow(n,i,p),p) print(op%p)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/HADIOR/hadior.py
ctfs/K3RN3L/2021/crypto/HADIOR/hadior.py
#!/usr/bin/env python3 # # Polymero # # Imports from Crypto.Util.number import inverse, getPrime, isPrime from secrets import randbelow from base64 import urlsafe_b64encode, urlsafe_b64decode from hashlib import sha256 import json, os, time # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() HDR = r"""| | Security provided by HADIOR | _ | _ _____________( )__________ | | | (_____________ _________ \ | | |___________ _| | _____) ) | | ___ ___ | / | | __ / | | | | | | |__/ /| |___| | \ \ | |_| |_| |_____/ \_____/ \_\ | | HADIOR will hold the DOOR |""" MENU = r"""| | | [G]enerate user token | [R]equest access |""" def legendre_symbol(a, p): ls = pow(a, (p - 1) // 2, p) return -1 if ls == p - 1 else ls def modular_sqrt(a, p): if legendre_symbol(a, p) != 1: return 0 elif a == 0: return 0 elif p == 2: return 0 elif p % 4 == 3: return pow(a, (p + 1) // 4, p) s = p - 1 e = 0 while s % 2 == 0: s //= 2 e += 1 n = 2 while legendre_symbol(n, p) != -1: n += 1 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 class HADIOR: """ HADIOR will hold the DOOR. """ def __init__(self, bits=512): # Generate *field with large prime order self.q = 0 while not self.q: self.p = getPrime(bits) for k in range(2,128+1): if (self.p-1) % k == 0 and isPrime((self.p-1)//k): self.q = (self.p-1) // k self.g = pow(2,k,self.p) # Generate keys self.sk = randbelow(self.q) self.pk = pow(self.g, self.sk, self.p) def tokenify(self, data): out = [] for i in data: try: if type(i) == int: j = i.to_bytes((i.bit_length()+7)//8,'big') out += [urlsafe_b64encode(j).decode()[:(len(j)*8+5)//6]] else: out += [urlsafe_b64encode(i).decode()[:(len(i)*8+5)//6]] except: pass return '.'.join(out) def __repr__(self): return 'Domain parameters ' + self.tokenify([self.g,self.p]) # Signatures def d(self, x): if type(x) == bytes: x = int.from_bytes(x,'big') x %= self.p return sum([int(i) for i in list('{:0512b}'.format(x ^ self.sk))]) def h(self, x): if type(x) == int: x = x.to_bytes((x.bit_length()+7)//8,'big') return int.from_bytes(sha256(x).digest(),'big') def sign(self, m): k = randbelow(self.q) r = pow(self.g,k,self.p) % self.q s = pow( inverse(k,self.q) * (self.h(m) + self.sk * r), self.d(m), self.q) return r,s def verify(self, m, r, s): h = self.h(m) d = self.d(m) if d % 2: s = pow(s, inverse(d, self.q-1), self.q) u = inverse(s, self.q) v = ( h * u ) % self.q w = ( r * u ) % self.q return r == ( ( pow(self.g,v,self.p) * pow(self.pk,w,self.p) ) % self.p ) % self.q else: lst = [] for si in [modular_sqrt(s, self.q), (-modular_sqrt(s, self.q))%self.q]: sj = pow(si, inverse(d, self.q-1), self.q) u = inverse(sj, self.q) v = ( h * u ) % self.q w = ( r * u ) % self.q lst += [r == ( ( pow(self.g,v,self.p) * pow(self.pk,w,self.p) ) % self.p ) % self.q] return any(lst) # Cookies! def bake(self, username, admin=False): while True: salt = os.urandom(4).hex() data = json.dumps({'user' : username, 'admin' : admin, 'salt' : salt}).encode() db64 = urlsafe_b64encode(data)[:(len(data)*8+5)//6] tb64 = urlsafe_b64encode(int(time.time()).to_bytes(4,'big'))[:-2] cb64 = db64 + b'.' + tb64 r, s = self.sign(cb64) if self.verify(cb64, r, s): return cb64.decode() + '.' + self.tokenify([r, s]) def inspect(self, cookie): data, t, r, s = cookie.split('.') r = int.from_bytes(urlsafe_b64decode(r + '==='),'big') s = int.from_bytes(urlsafe_b64decode(s + '==='),'big') if not self.verify((data + '.' + t).encode(), r, s): return 'INSPECT ERROR -- Invalid cookie.' try: data = json.loads(urlsafe_b64decode(data + '===').decode()) except: return 'INSPECT ERROR -- Broken cookie.' return data # Challenge print(HDR) print('| ' + 'Establishing connection...', end='\r', flush=True) t0 = time.time() hadior = HADIOR() t1 = time.time() print('| ' + 'Connection established in {:.2f} s.'.format(t1-t0)) print('|\n| ' + str(hadior)) while True: try: print(MENU) choice = input('| >> ') if choice.lower() == 'g': username = input('|\n| Username: ') cookie = hadior.bake(username=username) print('|\n| Token: ' + cookie) elif choice.lower() == 'r': cookie = input('|\n| User token: ') try: inspect = hadior.inspect(cookie) except: print('|\n| HADIOR ERROR -- Invalid input.') continue if type(inspect) == dict: if 'admin' in inspect and 'user' in inspect: if inspect['admin'] is True: print('|\n|\n| WELCOME admin {}.'.format(inspect['user'])) print('|\n| There is 1 new message for you.') print('|\n| From: Polymero') print('| Congrats! Here is a little gift from me - {}'.format(FLAG.decode())) _ = input('|\n|\n| Press enter to log out...') else: print('|\n|\n| WELCOME user {}.'.format(inspect['user'])) print('|\n| There are no new messages for you.') _ = input('|\n|\n| Press enter to log out...') else: print('|\n| HADIOR ERROR -- Invalid user token.') else: print('|\n| ' + inspect) except KeyboardInterrupt: print('\n|\n| ~ The DOOR remains secured.\n|') break except: print('|\n| HADIOR ERROR -- Unexpected error, please contact a service admin.\n|')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Non-Square_Freedom_1/nonsquarefreedom_easy.py
ctfs/K3RN3L/2021/crypto/Non-Square_Freedom_1/nonsquarefreedom_easy.py
#!/usr/bin/env python3 # # Polymero # # Imports from Crypto.Util.number import getPrime import os # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() # Key gen P = getPrime(512//8) Q = getPrime(256) R = getPrime(256) N = P**8 * Q * R E = 0x10001 def pad_easy(m): m <<= (512//8) m += (-(m % (P**2)) % P) return m # Pad FLAG M = pad_easy(int.from_bytes(FLAG,'big')) print('M < N :',M < N) print('M < P**8 :',M < (P**8)) print('M < Q*R :',M < (Q*R)) # Encrypt FLAG C = pow(M,E,N) print('\nn =',N) print('e =',E) print('c =',C) # Hint F = P**7 * (P-1) * (Q-1) * (R-1) D = inverse(E,F) print('\nD(C) =',pow(C,D,N)) #---------------------------------------------------- # Output #---------------------------------------------------- # M < N : True # M < P**8 : True # M < Q*R : True # # n = 68410735253478047532669195609897926895002715632943461448660159313126496660033080937734557748701577020593482441014012783126085444004682764336220752851098517881202476417639649807333810261708210761333918442034275018088771547499619393557995773550772279857842207065696251926349053195423917250334982174308578108707 # e = 65537 # c = 4776006201999857533937746330553026200220638488579394063956998522022062232921285860886801454955588545654394710104334517021340109545003304904641820637316671869512340501549190724859489875329025743780939742424765825407663239591228764211985406490810832049380427145964590612241379808722737688823830921988891019862 # # D(C) = 58324527381741086207181449678831242444903897671571344216578285287377618832939516678686212825798172668450906644065483369735063383237979049248667084304630968896854046853486000780081390375682767386163384705607552367796490630893227401487357088304270489873369870382871693215188248166759293149916320915248800905458 #
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Game_of_Secrets/gameofsecrets.py
ctfs/K3RN3L/2021/crypto/Game_of_Secrets/gameofsecrets.py
#!/usr/bin/env python3 # # Polymero # # Imports import os, base64 from hashlib import sha256 # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() class GoS: def __init__(self, key=None, spacing=12): self.spacing = spacing if type(key) == str: try: key = bytes.fromhex(key) except: key = None if (key is None) or (len(key) != 8) or (type(key) != bytes): key = os.urandom(8) self.RKs = [ sha256(key).hexdigest()[i:i+16] for i in range(0,256//4,16) ] self.ratchet() self.state = self.slicer(self.RKs[0]) self.i = 0 def slicer(self, inp): if type(inp) == str: inp = bytes.fromhex(inp) return [ [ int(i) for i in list('{:08b}'.format(j)) ] for j in inp ] def ratchet(self): self.RKs = [ sha256(rk.encode()).hexdigest()[:16] for rk in self.RKs ] def update(self): rk_plane = self.slicer( self.RKs[ (self.i // self.spacing) % 4 ] ) for yi in range(8): for xi in range(8): self.state[yi][xi] = self.state[yi][xi] ^ rk_plane[yi][xi] def get_sum(self, x, y): ret = [ self.state[(y-1) % 8][i % 8] for i in [x-1, x, x+1] ] ret += [ self.state[ y % 8][i % 8] for i in [x-1, x+1] ] ret += [ self.state[(y+1) % 8][i % 8] for i in [x-1, x, x+1] ] return sum(ret) def rule(self, ownval, neighsum): if ( neighsum < 2 ) or ( neighsum > 3 ): return 0 return 1 if neighsum == 3: return 1 return ownval def tick(self): new_state = [ [ 0 for _ in range(8) ] for _ in range(8) ] for yi in range(8): for xi in range(8): new_state[yi][xi] = self.rule( self.state[yi][xi], self.get_sum(xi, yi) ) self.state = new_state self.i += 1 if (self.i % (4 * self.spacing)) == 0: self.ratchet() if (self.i % self.spacing) == 0: self.update() def output(self): return bytes([int(''.join([str(j) for j in i]),2) for i in self.state]).hex() def stream(self, nbyt): lst = '' for _1 in range(-(-nbyt//8)): for _2 in range(3): for _3 in range(self.spacing): self.tick() lst += self.output() return ''.join(lst[:2*nbyt]) def xorstream(self, msgcip): if type(msgcip) == str: msgcip = bytes.fromhex(msgcip) keystream = list(bytes.fromhex(self.stream(len(msgcip)))) bytstream = list(msgcip) return bytes([ bytstream[i] ^ keystream[i] for i in range(len(msgcip)) ]).hex() def __main__(): gos = GoS() print("\n -- Here's your free stream to prepare you for your upcoming game! --\n") print(base64.urlsafe_b64encode(bytes.fromhex(gos.stream(1200*8))).decode()) print('\n -- They are indistinguishable from noise, they are of variable length, and they are the key to your victory.') print(' Ladies and Gentlemen, give it up for THE ENCRYPTED PADDED FLAG!!! --\n') print(base64.urlsafe_b64encode(bytes.fromhex( gos.xorstream( os.urandom(int(os.urandom(1).hex(),16)+8) + FLAG + os.urandom(int(os.urandom(1).hex(),16)+8) ))).decode().rstrip('=')) print('\nGood Luck! ~^w^~\n') __main__()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Non-Square_Freedom_2/nonsquarefreedom_hard.py
ctfs/K3RN3L/2021/crypto/Non-Square_Freedom_2/nonsquarefreedom_hard.py
#!/usr/bin/env python3 # # Polymero # # Imports from Crypto.Util.number import getPrime import os # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() # Key gen P = getPrime(512//8) Q = getPrime(256) R = getPrime(256) N = P**8 * Q * R E = 0x10001 def pad_hard(m): m <<= (512//2) m += int.from_bytes(os.urandom(256//8),'big') m += (-(m % (P**2)) % (P**2)) m += (-(m % (P**3)) % (P**3)) return m # Pad FLAG M = pad_hard(int.from_bytes(FLAG,'big')) print('M < N :',M < N) print('M < P**8 :',M < (P**8)) print('M < Q*R :',M < (Q*R)) # Encrypt FLAG C = pow(M,E,N) print('\nn =',N) print('e =',E) print('c =',C) # Hint F = P**7 * (P-1) * (Q-1) * (R-1) D = inverse(E,F) print('\nD(C) =',pow(C,D,N)) #---------------------------------------------------- # Output #---------------------------------------------------- # M < N : True # M < P**8 : False # M < Q*R : False # # n = 51214772223826458947343903953001487476278631390021520449180482250318402223871910467589821176474724615270573620128351792442696435406924016685353662124634928276565604574767844305337546301974967758679072483930469188209450741154719808928273796360060047042981437882233649203901005093617276209822357002895662878141 # e = 65537 # c = 41328763458934302623886982279989290133391941143474825043156612786022747186181626092904440906629512249693098336428292454473471954816980834113337123971593864752166968333372184013915759408279871722264574280860701217968784830530130601590818131935509927605432477384634437968100579272192406391181345133757405127746 # # D(C) = 36121865463995782277296293158498110427613111962414238045946490101935688033022876541418793886469647898078579120189419552431787379541843120009675223060979171856818401470674058515557901674369835328155371791544935440499813846484080003978652786490718806523938327240659684439275298596339460595405316567186468069580 #
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Total_Encryption/ltet.py
ctfs/K3RN3L/2021/crypto/Total_Encryption/ltet.py
#!/usr/bin/env python3 # # Polymero # # Imports import os, time, base64 from Crypto.Util.number import getPrime, inverse, GCD, long_to_bytes # Shorthand def b64enc(x): return base64.urlsafe_b64encode(long_to_bytes(x)).rstrip(b'=') class LTET: """ Layered Totally Encrypted Terminal. """ def __init__(self, max_bit_length): self.maxlen = max_bit_length # Set bit lengths self.bitlen = { 'inner block' : self.maxlen, 'inner clock' : (7 * self.maxlen) // 125 } self.bitlen['outer block'] = 16 + (4 * (self.bitlen['inner block'] + self.bitlen['inner clock'] + 9)) // 3 self.bitlen['outer blind'] = 8 + (4 * self.bitlen['inner clock']) // 3 # Key generation self.public = { 'n' : [], 'e' : [65537, 5, 127]} self.private = { 'p' : [], 'q' : [], 'd' : []} for i in range(3): nbit = [self.bitlen[j] for j in ['inner clock', 'inner block', 'outer block']][i] while True: p, q = [getPrime((nbit + 1) // 2) for _ in range(2)] if GCD(self.public['e'][i], (p-1)*(q-1)) == 1: d = inverse(self.public['e'][i], (p-1)*(q-1)) break self.private['p'] += [p] self.private['q'] += [q] self.private['d'] += [d] self.public['n'] += [p * q] def encrypt(self, msg): assert len(msg) * 8 <= self.maxlen clock = pow(int(time.time()), self.public['e'][0], self.public['n'][0]) block = b64enc(pow(int.from_bytes(msg, 'big') ^ int(clock), self.public['e'][1], self.public['n'][1])) blind = int.from_bytes(os.urandom((self.bitlen['outer blind'] + 7) // 8), 'big') >> (8 - (self.bitlen['outer blind'] % 8)) block = pow(int.from_bytes(block + b'.' + b64enc(clock) ,'big') ^ blind, self.public['e'][2], self.public['n'][2]) return (b64enc(blind) + b'.' + b64enc(block)).decode()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/MathyOracle/main.py
ctfs/K3RN3L/2021/crypto/MathyOracle/main.py
print('Find my number N, and I will give you the flag.') def f(N,k): while min(N,k)>0: if k>N: N,k = k,N N%=k return max(N,k) import random N = random.getrandbits(512) for i in range(600): print(f"Try #{i+1}: ") k = input(f'Enter k: ') l = input(f'Enter l: ') try: k= int(k) assert 0<k<pow(10,500) l= int(l) assert 0<l<pow(10,500) except: print('Invalid input. Exiting...') quit() print(f'f(N+l,k) = {f(int(N+l),k)}\n') guess = input('What is N?') if str(N)==guess: print(open('flag.txt').read().strip()) else: print('Wrong answer. The number was '+str(N))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Poly-Proof/polyproof.py
ctfs/K3RN3L/2021/crypto/Poly-Proof/polyproof.py
#!/usr/bin/env python3 # # Polymero # # Imports import os # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() HDR = r"""| | ________ ________ ___ ___ ___ ________ ________ ________ ________ ________ | |\ __ \|\ __ \|\ \ |\ \ / /| |\ __ \|\ __ \|\ __ \|\ __ \|\ _____\ | \ \ \|\ \ \ \|\ \ \ \ \ \ \/ / / \ \ \|\ \ \ \|\ \ \ \|\ \ \ \|\ \ \ \__/ | \ \ ____\ \ \\\ \ \ \ \ \ / / \ \ ____\ \ _ _\ \ \\\ \ \ \\\ \ \ __\ | \ \ \___|\ \ \\\ \ \ \____ \/ / / \ \ \___|\ \ \\ \\ \ \\\ \ \ \\\ \ \ \_| | \ \__\ \ \_______\ \_______\__/ / / \ \__\ \ \__\\ _\\ \_______\ \_______\ \__\ | \|__| \|_______|\|_______|\___/ / \|__| \|__|\|__|\|_______|\|_______|\|__| | \|___|/ |""" class Server: def __init__(self, difficulty): self.difficulty = difficulty self.coefficients = None self.limit = 8 self.i = 0 self.set_up() def _eval_poly(self, x): return sum([ self.coefficients[i] * x**i for i in range(len(self.coefficients)) ]) def _prod(self, intlst): ret = 1 for i in intlst: ret *= i return ret def set_up(self, verbose=False): print(HDR) print("| To prove to you that I own the flag, I used it to make a polynomial. Challenge me all you want!") noise = [ self._prod(list(os.urandom(self.difficulty))) for i in range(len(FLAG)) ] self.coefficients = [ noise[i] * FLAG[i] for i in range(len(FLAG)) ] def accept_challenge(self): print("|\n| Name your challenge (as ASCII string):") try: user_input = int.from_bytes(str(input("| >> ")).encode(),'big') except ValueError: print("|\n| ERROR - That ain't working... s m h ") return if user_input == 0: print("|\n| ERROR - You clearly don't know what ZERO-KNOWLEDGE means eh?") return if user_input <= 0: print("|\n| ERROR - Your clever tricks will not work here, understood?") return print("|\n| Here's my commitment: {}".format(self._eval_poly(user_input))) self.i += 1 def run(self): while self.i < self.limit: try: self.accept_challenge() except: break if self.i >= self.limit: print("|\n| Are you trying to steal my polynomial or something?") print("| I think I have proven enough to you...") print("|\n|\n| ~ See you back in polynomial time! o/ \n|") S = Server(15) S.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Aint_No_Mountain_High_Enough/mountaincipher.py
ctfs/K3RN3L/2021/crypto/Aint_No_Mountain_High_Enough/mountaincipher.py
#!/usr/bin/env python3 # # Polymero # #------------------------------------------------------------------------------- # IMPORTS #------------------------------------------------------------------------------- import os from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse #------------------------------------------------------------------------------- # LINEAR ALGEBRA FUNCTIONS (no numpy.linalg, no sage :3) #------------------------------------------------------------------------------- # Matrix determinant def det(m): if len(m) == 2: return m[0][0]*m[1][1] - m[0][1]*m[1][0] else: return sum( (-1)**(i) * m[0][i] * det( [list(mi[:i]) + list(mi[i+1:]) for mi in m[1:]] ) for i in range(len(m)) ) # Matrix transpose def trans(m): return [[m[j][i] for j in range(len(m))] for i in range(len(m))] # Matrix adjoint (to calculate the inverse) def adjoint(m): adj = [[0 for _ in range(len(m))] for _ in range(len(m))] for i in range(len(m)): for j in range(len(m)): adj[i][j] = (-1)**(i+j) * det( [ list(mi[:j])+list(mi[j+1:]) for mi in list(m[:i])+list(m[i+1:]) ] ) return trans(adj) # Simple matrix multiplication (mod p) def matmult(A, B, p): assert len(A) == len(B) n = len(A) C = [[0 for _ in range(n)] for _ in range(n)] for ri in range(n): for ci in range(n): C[ri][ci] = sum( [A[ri][i]*B[i][ci] for i in range(n)] ) % p # Return return C #------------------------------------------------------------------------------- # CIPHER HELPER FUNCTIONS #------------------------------------------------------------------------------- # (u)Random key gen def keygen(n, p): i = 0 while i < 1000: try: keycube = [[[int(bytes_to_long(os.urandom(p//256 + 1))/256*p) % p for _ in range(n)] for _ in range(n)] for _ in range(n)] keyDINV = [int(inverse(det(k),p)) for k in keycube] keyCINV = [[[c*keyDINV[i] % p for c in r] for r in adjoint(k)] for i,k in enumerate(keycube)] return keycube, keyCINV[::-1] except: i += 1 continue raise ValueError('Key generation failed, try again or try with a different p...') # Padding and msg matrixfier def pad(msg, n): # Bytestrings only pls if type(msg) == str: msg = msg.encode() # Apply random padding while (len(msg) % (n*n) != 0): msg += os.urandom(1) # Matrixfy and return return [[list(i[j:j+n]) for j in range(0,n*n,n)] for i in [msg[k:k+n*n] for k in range(0,len(msg),n*n)]] #------------------------------------------------------------------------------- # MOUNTAIN CIPHER #------------------------------------------------------------------------------- # Mountain Cipher Encryption Function def encMC(msg, n, p, key=None, verbose=False): # Create key if none given if key is None: key, _ = keygen(n, p) # Convert msg to matrix if type(msg) != list: msg = pad(msg, n) # For all nxn msg matrices ct = [] for mi in msg: # Hill-cipher encrypt with every key matrix for i in range(n): mi = matmult(key[i], mi, p) # Add result to ciphertext ct += [mi] # Debug if verbose: print('Key Cube\n',key, '\n') print('Message Cube\n',msg, '\n') print('Cipher Cube\n',ct, '\n') if p < 256: print('Msg\n',bytes([i for j in [i for j in msg for i in j] for i in j]), '\n') print('Cip\n',bytes([i for j in [i for j in ct for i in j] for i in j]), '\n') # Return ciphertext in hex if False and all(i < 256 for i in [i for j in [i for j in ct for i in j] for i in j]): return bytes([i for j in [i for j in ct for i in j] for i in j]).hex() else: return ct # Mountain Cipher Decryption Function def decMC(cip, n, p, key): # Transform cipher text if type(cip) == str: cip = bytes.fromhex(cip) if type(cip) != list: cip = pad(cip, n) # Decryption key from key detinvs = [int(inverse(det(k),p)) for k in key[::-1]] deckey = [[[c*detinvs[i] % p for c in r] for r in adjoint(k)] for i,k in enumerate(key[::-1])] # Get decryption through encryption with decryption key return encMC(cip, n, p, key=deckey, verbose=False) #------------------------------------------------------------------------------- # PROOF OF CONCEPT #------------------------------------------------------------------------------- def __main__(): # (key) Cube length n = 8 # Prime modulo p = 10001 # Generate random key set kpub, kpriv = keygen(n, p) # Encrypt :) print(encMC('Hello there! Can I find a flag somewhere around here?', n, p, key=kpub, verbose=True)) #__main__()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Aint_No_Mountain_High_Enough/server.py
ctfs/K3RN3L/2021/crypto/Aint_No_Mountain_High_Enough/server.py
#!/usr/bin/env python3 # # Polymero # # Local imports from mountaincipher import * with open('flag.txt','rb') as f: FLAG = f.read() f.close() # Encryption parameters N = 5 P = 251 VERSION = '1.0' HDR_3 = r"""| | | ___ ___ ___ _________ _ | / / / /\ (_________) _ (_) | /___/___/___/ \ _ _ _ ___ _ _ ____ _| |_ _____ _ ____ | / / / /\ /\ | | |_| | | / _ \ | | | | | _ \ (_ _) (____ | | | | _ \ | /___/___/___/ \/ \ | | | | | |_| | | |_| | | | | | | |_ / ___ | | | | | | | | / / / /\ /\ /\ |_| |_| \___/ |____/ |_| |_| \__) \_____| |_| |_| |_| | /___/___/___/ \/ \/ \ | \ \ \ \ /\ /\ / _______ _ _ | \___\___\___\/ \/ \/ (_______) (_) | | | \ \ \ \ /\ / _ _ ____ | |__ _____ ____ | \___\___\___\/ \/ | | | | | _ \ | _ \ | ___ | / ___) | \ \ \ \ / | |_____ | | | |_| | | | | | | ____| | | | \___\___\___\/ \______) |_| | __/ |_| |_| |_____) |_| | |_| |""" CUBE = r"""| | | Key Cube (5x5x5) | ___ ___ ___ ___ ___ | / / / / / /\ | /___/___/___/___/___/ \ | / / / / / /\ /\ | /___/___/___/___/___/ \/ \ | / / / / / /\ /\ /\ | /___/___/___/___/___/ \/ \/ \ | / / / / / /\ /\ /\ /\ | /___/___/___/___/___/ \/ \/ \/ \ | / / / / / /\ /\ /\ /\ /\ | Message Cuboid ---> /___/___/___/___/___/ \/ \/ \/ \/ \ ---> Cipher Cuboid | \ \ \ \ \ \ /\ /\ /\ /\ / | \___\___\___\___\___\/ \/ \/ \/ \/ | \ \ \ \ \ \ /\ /\ /\ / | \___\___\___\___\___\/ \/ \/ \/ | \ \ \ \ \ \ /\ /\ / | \___\___\___\___\___\/ \/ \/ | \ \ \ \ \ \ /\ / | \___\___\___\___\___\/ \/ | \ \ \ \ \ \ / | \___\___\___\___\___\/ | | | | | | | | | | | | | | | | | | | Current slices: {} {} {} {} {} |""" # Server def __main__(): KEYS = ['K1','K2','K3','K4','K5'] KEYCUBE, _ = keygen(N, P) K1, K2, K3, K4, K5 = KEYCUBE[::1] FL = [list(FLAG[i:i+N]) for i in range(0,N*N,N)] print(HDR_3) print('|\n| Welcome to the Mountain Cipher Encryption Service!\n|') print('| Current version: {} (Insert Challenge)\n|'.format(VERSION)) while True: try: print('|') print('| MENU:\n| [0] Show info\n| [1] Inspect key cube\n| [2] Insert FLAG slice\n|\n| [3] Encrypt\n| [4] Decrypt\n|\n| [5] Exit') choice_1 = input('|\n| >> ') if choice_1 == '0': print('|\n|\n| Mountain Cipher Encryption Service (MCES) v{}'.format(VERSION)) print('|\n| "Hills are easy to climb, but mountains? Hoho, they sure are something else!"') print('|\n| KEY CUBE\n| Dimensions (n): {0}x{0}x{0}\n| Prime Modulus (p): {1}\n|\n| CIPHER TEXT\n| Matrix Output: True\n| Hex Output: True'.format(N,P)) print('|\n| Challenge: recover the FLAG by inserting it into the KEY CUBE.\n|') elif choice_1 == '1': print(CUBE.format(KEYS[0],KEYS[1],KEYS[2],KEYS[3],KEYS[4])) elif choice_1 == '2': print("|\n|\n| Current setup: {}".format(KEYS)) print("|\n| Swap KEY slice 'X' for FLAG slice (0 for None):") choice_2 = input('|\n| >> X = ') if choice_2 == '0': KEYS = ['K1','K2','K3','K4','K5'] KEYCUBE = [K1,K2,K3,K4,K5] elif choice_2 == '5': KEYS = ['K1','K2','K3','K4','FL'] KEYCUBE = [K1,K2,K3,K4,FL] elif choice_2 == '4': KEYS = ['K1','K2','K3','FL','K5'] KEYCUBE = [K1,K2,K3,FL,K5] elif choice_2 == '3': KEYS = ['K1','K2','FL','K4','K5'] KEYCUBE = [K1,K2,FL,K4,K5] elif choice_2 == '2': KEYS = ['K1','FL','K3','K4','K5'] KEYCUBE = [K1,FL,K3,K4,K5] elif choice_2 == '1': KEYS = ['FL','K2','K3','K4','K5'] KEYCUBE = [FL,K2,K3,K4,K5] print('|\n| Current setup: {}\n|'.format(KEYS)) elif choice_1 == '3': print('|\n|\n| Please enter ASCII message to encrypt (check [1] for key cube setup):') msg_to_enc = input('| >> M = ') enc_msg = encMC(msg_to_enc, N, P, key=KEYCUBE) print('|\n|\n| Key Cube: {}'.format(KEYS)) print('|\n| Cipher Cuboid:') for block in enc_msg: for row in block: print('| [{:3d}, {:3d}, {:3d}, {:3d}, {:3d}]'.format(row[0],row[1],row[2],row[3],row[4])) print('|') print('|') print('| C = {}'.format(bytes([i for j in [i for j in enc_msg for i in j] for i in j]).hex())) print('|') elif choice_1 == '4': print('|\n|\n| Please enter HEX cipher text to decrypt (check [1] for key cube setup):') cip_to_dec = input('| >> C = ') dec_msg = decMC(cip_to_dec, N, P, key=KEYCUBE) print('|\n|\n| Key Cube: {}'.format(KEYS)) print('|\n| Message Cuboid:') for block in dec_msg: for row in block: print('| [{:3d}, {:3d}, {:3d}, {:3d}, {:3d}]'.format(row[0],row[1],row[2],row[3],row[4])) print('|') print('|') print('| M(hex) = {}'.format(bytes([i for j in [i for j in dec_msg for i in j] for i in j]).hex())) print('|') print('| M(bytes) = {}'.format(bytes([i for j in [i for j in dec_msg for i in j] for i in j]))) print('|') elif choice_1 in ['5','q','quit','exit']: raise KeyboardInterrupt else: print('|\n| Option not recognised\n|') except KeyboardInterrupt: print('|\n|\n| Goodbye!\n|') break except: break __main__()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py
ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py
#!/usr/bin/env python3 # # Polymero # # Imports import random from Crypto.Util.number import GCD, inverse, bytes_to_long, long_to_bytes, getPrime from time import sleep class Pravrallier: def __init__(self): # Keygen while True: p, q = getPrime(512), getPrime(512) if GCD(p*q, (p-1)*(q-1)) == 1: break self.n = p * q # Blinding self.r = { r+1 : random.randint(2, self.n-1) for r in range(128) } self.i = 1 def fortune(self, msg): """ Generate fortune ticket flavour text. """ nums = [int.from_bytes(msg[i:i+2],'big') for i in range(0,len(msg),2)] luck = [''] spce = b'\x30\x00'.decode('utf-16-be') for num in nums: if num >= 0x4e00 and num <= 0x9fd6: luck[-1] += num.to_bytes(2,'big').decode('utf-16-be') else: luck += [''] luck += [''] maxlen = max([len(i) for i in luck]) for i in range(len(luck)): luck[i] += spce * (maxlen - len(luck[i])) card = [spce.join([luck[::-1][i][j] for i in range(len(luck))]) for j in range(maxlen)] return card def encrypt_worry(self, msg): # Generate fortune ticket card = self.fortune(msg) # Encrypt gm = pow(1 + self.n, bytes_to_long(msg), self.n**2) rn = pow(self.r[len(card[0])] * self.i, self.n + self.i, self.n**2) cip = (gm * rn) % self.n**2 self.i += 1 return cip, card def encrypt_flag(self, msg, order, txt): # Generate fortune ticket card = self.fortune(msg) # Encrypt up to given order cip = bytes_to_long(msg) for o in range(2,order+1): cip = pow(1 + self.n, cip, self.n**(o)) # ??? print("| {}".format(txt[(o-2) % len(txt)])) sleep(3) return cip, card def print_card(self, cip, card): """ Print fortune ticket to terminal. """ upper_hex = long_to_bytes(cip).hex().upper() fwascii = list(''.join([(ord(i)+65248).to_bytes(2,'big').decode('utf-16-be') for i in list(upper_hex)])) enclst = [''.join(fwascii[i:i+len(card[0])]) for i in range(0, len(fwascii), len(card[0]))] # Frame elements sp = b'\x30\x00'.decode('utf-16-be') dt = b'\x30\xfb'.decode('utf-16-be') hl = b'\x4e\x00'.decode('utf-16-be') vl = b'\xff\x5c'.decode('utf-16-be') # Print fortune ticket enclst[-1] += sp*(len(card[0])-len(enclst[-1])) print() print(2*sp + dt + hl*(len(card[0])+2) + dt) print(2*sp + vl + dt + hl*len(card[0]) + dt + vl) for row in card: print(2*sp + 2*vl + row + 2*vl) print(2*sp + vl + dt + hl*len(card[0]) + dt + vl) for row in enclst: print(2*sp + vl + sp + row + sp + vl) print(2*sp + dt + hl*(len(card[0])+2) + dt) print()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py
ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py
#!/usr/bin/env python3 # # Nika Soltas # # Imports import os from hashlib import sha256 # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() class Map: def __init__(self, maptype, params): """Initialise map object""" if maptype.lower() in ['l','lm','logic']: self.f = self.__LOGI elif maptype.lower() in ['e','el','elm','extended logic']: self.f = self.__EXT_LOGI else: raise ValueError('Invalid Map Type.') try: self.p = list(params) except: self.p = [params] def __LOGI(self, x): # <--- p in [3.7, 4] """Logistic map""" return self.p[0] * x * (1 - x) def __EXT_LOGI(self, x): # <--- p in [2, 4] """Extended logistic map""" if x < 0.5: return self.__LOGI(x) else: return self.p[0] * (x * (x - 1) + 1 / 4) def sample(self, x_i, settles, samples): """Generates outputs after certain number of settles""" x = x_i for _ in range(settles): x = self.f(x) ret = [] for _ in range(samples): x = self.f(x) ret += [x] return ret class Mowhock: def __init__(self, key=None, iv=None): """Initialise Mowhock class object.""" if (key is None) or (len(key) != 64): key = os.urandom(32).hex() self.key = key if (iv is None) or (len(iv) != 16): iv = os.urandom(8).hex() self.iv = iv self.maps = self.map_schedule() self.buffer_raw = None self.buffer_byt = None def key_schedule(self): """Convert key into 8 round subkeys.""" KL, KR = self.key[:32], self.key[32:] VL, VR = self.ctr[:8], self.ctr[8:] HL, HR = [sha256(bytes.fromhex(i)).digest() for i in [VL+KL,VR+KL]] hlbits, hrbits = ['{:0256b}'.format(int.from_bytes(H,'big')) for H in [HL,HR]] bitweave = ''.join([hlbits[i]+hrbits[i] for i in range(256)]) subkeys = [int(bitweave[i:i+64],2) for i in range(0,512,64)] return [self.read_subkey(i) for i in subkeys] def map_schedule(self): """Convert IV into 8 maps with iv-dependent parameters""" iv = bytes.fromhex(self.iv) maps = [ Map('L', iv[0]*(4.00 - 3.86)/255 + 3.86), Map('L', iv[1]*(4.00 - 3.86)/255 + 3.86), Map('L', iv[2]*(4.00 - 3.86)/255 + 3.86), Map('L', iv[3]*(4.00 - 3.86)/255 + 3.86), Map('E', iv[4]*(4.00 - 3.55)/255 + 3.55), Map('E', iv[5]*(4.00 - 3.55)/255 + 3.55), Map('E', iv[6]*(4.00 - 3.55)/255 + 3.55), Map('E', iv[7]*(4.00 - 3.55)/255 + 3.55), ] order = self.hop_order(int(self.key[:2],16),8) return [maps[i] for i in order] def read_subkey(self, subkey): """Convert subkey int from key schedule to orbit parameters.""" # Integer to bits byts = subkey.to_bytes(8, 'big') bits = ''.join(['{:08b}'.format(i) for i in byts]) # Read key elements hpsn = int(bits[0:8],2) seed = float('0.00'+str(int(bits[8:32],2))) offset = float('0.0000'+str(int(bits[32:48],2))) settles = int(bits[48:56],2) + 512 orbits = int(bits[56:60],2) + 4 samples = int(bits[60:64],2) + 4 # Processing key elements hopord = self.hop_order(hpsn,orbits) x_i = [seed + offset*i for i in hopord] # Return subkey dictionary return { 'order' : hopord, 'hpsn' : hpsn, 'seed' : seed, 'offset' : offset, 'x_i' : x_i, 'settles' : settles, 'orbits' : orbits, 'samples' : samples } def hop_order(self, hpsn, orbits): """Determine orbit hop order""" i = 1 ret = [] while len(ret) < orbits: o = (pow(hpsn,i,256)+i) % orbits if o not in ret: ret += [o] i += 1 return ret def ctr_increment(self): """Increments IV and reschedules key.""" self.ctr = (int(self.ctr,16) + 1).to_bytes(8, 'big').hex() self.subkeys = self.key_schedule() self.fill_buffers() def fill_buffers(self, save_raw=False): """Fills internal buffer with pseudorandom bytes""" self.buffer_raw = [] self.buffer_byt = [] raw = [] for i in range(8): settles = self.subkeys[i]['settles'] samples = self.subkeys[i]['samples'] for x_i in self.subkeys[i]['x_i']: raw += self.maps[i].sample(x_i, settles, samples) if save_raw: self.buffer_raw += raw bitstr = ['{:032b}'.format(int(i*2**53)) for i in raw] byt = [] for b32 in bitstr: byt += [int(b32[:8],2) ^ int(b32[16:24],2), int(b32[8:16],2) ^ int(b32[24:32],2)] self.buffer_byt += bytes(byt) def encrypt(self, msg): """Encrypts a message through the power of chaos""" # Fill initial buffers self.ctr = self.iv self.subkeys = self.key_schedule() self.fill_buffers() # Encrypt (increment and refill buffers if necessary) cip = b'' if type(msg) == str: msg = bytes.fromhex(msg) for byt in msg: try: cip += bytes( [byt ^ self.buffer_byt.pop(0)] ) except: self.ctr_increment() cip += bytes( [byt ^ self.buffer_byt.pop(0)] ) # Return IV and ciphertext return self.iv + cip.hex() #----------------------------------------------------------------------------------------------------- # CHALLENGE #----------------------------------------------------------------------------------------------------- HDR = r"""| | __ __ _____ _ _ __ __ _____ _____ __ __ | /_/\ /\_\ ) ___ ( /_/\ /\_\ /\_\ /_/\ ) ___ ( /\ __/\ /\_\\ /\ | ) ) \/ ( ( / /\_/\ \ ) ) )( ( (( ( (_) ) )/ /\_/\ \ ) )__\/( ( (/ / / | /_/ \ / \_\/ /_/ (_\ \/_/ //\\ \_\\ \___/ // /_) \_\ \/ / / \ \_ / / | \ \ \\// / /\ \ )_/ / /\ \ / \ / // / _ \ \\ \ \_( / /\ \ \_ / / \ \ | )_) )( (_( \ \/_\/ / )_) /\ (_(( (_( )_) )\ \/_\/ / ) )__/\( (_(\ \ \ | \_\/ \/_/ )_____( \_\/ \/_/ \/_/ \_\/ )_____( \/___\/ \/_//__\/ | | ENCRYPTION through the POWER of CHAOS |""" MEN = r"""| | | Menu: | [1] Encrypt custom message | [2] Encrypt FLAG |""" print(HDR) used_ivs = [] while True: try: print(MEN) choice = input("| >> ") if choice == "1": print("|\n|\n| Custom encryption parameters (HEX) [empty for RANDOM]:") key = input("| Key: ") iv = input("| IV : ") msg = input("| Msg: ") try: bytes.fromhex(key); bytes.fromhex(iv); bytes.fromhex(msg) assert len(key) in [0,64] and len(iv) in [0,16] except: print('|\n| ERROR -- Invalid user input.') continue while True: cip = Mowhock(key=key,iv=iv).encrypt(msg) used_iv = cip[:16] if used_iv not in used_ivs: used_ivs += [used_iv] break print("|\n| Output:") print("| {}".format(cip)) elif choice == "2": print("|\n|\n| FLAG encryption parameters (HEX) [empty for RANDOM]:") print("| Key: <RANDOM>") iv = input("| IV : ") print("| Msg: <RANDOM>|<FLAG>|<RANDOM>") try: bytes.fromhex(iv) assert len(iv) in [0,16] except: print('|\n| ERROR -- Invalid user input.') continue rnum = [int(i,16) for i in list(os.urandom(1).hex())] cip = Mowhock(key=None,iv=iv).encrypt(os.urandom(rnum[0])+FLAG+os.urandom(rnum[1])) if cip[:16] in used_ivs: print('|\n| ERROR -- IV re-use detected.') continue used_ivs += [cip[:16]] print("|\n| Output:") print("| {}".format(cip)) except KeyboardInterrupt: print("\n|\n| May your day be CHAOTIC!\n|") exit(0) except: print("|\n|\n| ERROR --- TOO MUCH CHAOS ---\n|")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Fractional_Fractions/main.py
ctfs/K3RN3L/2021/crypto/Fractional_Fractions/main.py
from Crypto.Util.number import bytes_to_long flag = str(bytes_to_long(open('flag.txt','rb').read())) from fractions import Fraction enc = Fraction(0/1) for c in flag: enc += Fraction(int(c)+1) enc = 1/enc print(enc) #7817806454609461952471483475242846271662326/63314799458349217804506955537187514185318043
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Pryby/main.py
ctfs/K3RN3L/2021/crypto/Pryby/main.py
from Crypto.Util.number import bytes_to_long def f(n): q=[True]*(n + 1) r=2 while r**2<=n: if q[r]: for i in range(r**2,n+1,r):q[i] = False r += 1 return [p for p in range(2,n+1) if q[p]] class G: def __init__(self, f): self.f = f self.state = 1 def move(self): q=1 for p in self.f: if self.state%p!=0: self.state=self.state*p//q return q*=p flag = open('flag.txt','r').read().strip().encode() flag=bytes_to_long(flag) gen = G(f(pow(10,6))) for _ in range(flag):gen.move() print('enc =',gen.state) # enc = 31101348141812078335833805605789286074261282187811930228543150731391596197753398457711668323158766354340973336627910072170464704090430596544129356812212375629361633100544710283538309695623654512578122336072914796577236081667423970014267246553110800667267853616970529812738203125516169205531952973978205310
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/K3RN3L/2021/crypto/Tick_Tock/ticktock.py
ctfs/K3RN3L/2021/crypto/Tick_Tock/ticktock.py
#!/usr/bin/env python3 # # Polymero # # Imports from Crypto.Util.number import getPrime, isPrime from Crypto.Util.Padding import pad from Crypto.Cipher import AES from random import randint from hashlib import sha256 # Local imports with open('flag.txt','rb') as f: FLAG = f.read() f.close() assert len(FLAG) % 8 == 0 # Helper functions def legendre_symbol(a, p): ls = pow(a, (p - 1) // 2, p) return -1 if ls == p - 1 else ls def modular_sqrt(a, p): if legendre_symbol(a, p) != 1: return 0 elif a == 0: return 0 elif p == 2: return p elif p % 4 == 3: return pow(a, (p + 1) // 4, p) s = p - 1 e = 0 while s % 2 == 0: s //= 2 e += 1 n = 2 while legendre_symbol(n, p) != -1: n += 1 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 # TickTock class class TickTock: def __init__(self, x, y, P): self.x = x self.y = y self.P = P assert self.is_on_curve() def __repr__(self): return '({}, {}) over {}'.format(self.x, self.y, self.P) def __eq__(self, other): return self.x == other.x and self.y == other.y and self.P == other.P def is_on_curve(self): return (self.x*self.x + self.y*self.y) % self.P == 1 def add(self, other): assert self.P == other.P x3 = (self.x * other.y + self.y * other.x) % self.P y3 = (self.y * other.y - self.x * other.x) % self.P return self.__class__(x3, y3, self.P) def mult(self, k): ret = self.__class__(0, 1, self.P) base = self.__class__(self.x, self.y, self.P) while k: if k & 1: ret = ret.add(base) base = base.add(base) k >>= 1 return ret def lift_x(x, P, ybit=0): y = modular_sqrt((1 - x*x) % P, P) if ybit: y = (-y) % P return TickTock(x, y, P) def domain_gen(bits): while True: q = getPrime(bits) if isPrime(4*q + 1): P = 4*q + 1 break while True: i = randint(2, P) try: G = lift_x(i, P) G = G.mult(4) break except: continue return P, G def key_gen(): sk = randint(2, P-1) pk = G.mult(sk) return sk, pk def key_derivation(point): dig1 = sha256(b'x::' + str(point).encode()).digest() dig2 = sha256(b'y::' + str(point).encode()).digest() return sha256(dig1 + dig2 + b'::key_derivation').digest() # Challenge flagbits = [FLAG[i:i+len(FLAG)//8] for i in range(0,len(FLAG),len(FLAG)//8)] for i in range(8): print('# Exchange {}:'.format(i+1)) P, G = domain_gen(48) print('\nP =', P) print('G = ({}, {})'.format(G.x, G.y)) alice_sk, alice_pk = key_gen() bobby_sk, bobby_pk = key_gen() assert alice_pk.mult(bobby_sk) == bobby_pk.mult(alice_sk) print('\nA_pk = ({}, {})'.format(alice_pk.x, alice_pk.y)) print('B_pk = ({}, {})'.format(bobby_pk.x, bobby_pk.y)) key = key_derivation(alice_pk.mult(bobby_sk)) cip = AES.new(key=key, mode=AES.MODE_CBC) enc = cip.iv + cip.encrypt(pad(flagbits[i], 16)) print('\nflagbit_{} = "{}"'.format(i+1, enc.hex())) print('\n\n\n')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1753CTF/2025/crypto/Update/update_update.py
ctfs/1753CTF/2025/crypto/Update/update_update.py
#!/usr/bin/env python3 import json from Crypto.Hash import CMAC from Crypto.Cipher import AES from Crypto.PublicKey import RSA from Crypto.Signature import pkcs1_15 from secret import FLAG, CMAC_KEY, PUBKEY_TAG, try_read_cmac_key def mac(msg): cmac = CMAC.new(CMAC_KEY, ciphermod=AES) cmac.oid = '2.16.840.1.101.3.4.2.42' cmac.update(msg) return cmac def do_update(): update = json.loads(input('update package: ')) n_bytes = bytes.fromhex(update['pubkey']) signature_bytes = bytes.fromhex(update['signature']) payload_bytes = bytes.fromhex(update['payload']) key_tag = mac(n_bytes).digest() if key_tag != PUBKEY_TAG: print('verification failed') return n = int.from_bytes(n_bytes, 'big') e = 0x10001 pubkey = RSA.construct((n, e)) verifier = pkcs1_15.new(pubkey) h = mac(payload_bytes) signature = signature_bytes try: verifier.verify(h, signature) except: print('verification failed') return print('signature correct') if payload_bytes == b'Gimmie a flag, pretty please.': print(FLAG) print('update succesfull') def main(): while True: print('1. try to read cmac key') print('2. do an update') choice = int(input('your choice: ')) if choice == 1: print(try_read_cmac_key()) elif choice == 2: do_update() else: break main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2024/crypto/sym_signin/task_utils.py
ctfs/D3CTF/2024/crypto/sym_signin/task_utils.py
import hashlib import struct S = [0xc, 0x5, 0x6, 0xb, 0x9, 0x0, 0xa, 0xd, 0x3, 0xe, 0xf, 0x8, 0x4, 0x7, 0x1, 0x2] P = [0, 8, 16, 24, 1, 9, 17, 25, 2, 10, 18, 26, 3, 11, 19, 27, 4, 12, 20, 28, 5, 13, 21, 29, 6, 14, 22, 30, 7, 15, 23, 31] def S_16bit(x: int) -> int: result = 0 for i in range(4): block = (x >> (i * 4)) & 0xF sbox_result = S[block] result |= sbox_result << (i * 4) return result def S_layer(x: int) -> int: return (S_16bit(x >> 16) << 16) | S_16bit(x & 0xffff) def P_32bit(x: int) -> int: binary_result = format(x, '032b') permuted_binary = ''.join(binary_result[i] for i in P) result = int(permuted_binary, 2) return result def key_schedule(key): return ((key << 31 & 0xffffffff) + (key << 30 & 0xffffffff) + key) & 0xffffffff def enc_round(message: int, key: int) -> int: result = message ^ key result = S_layer(result) result = P_32bit(result) return result def encrypt(message: int, key: int, ROUND: int) -> int: ciphertext = message for _ in range(ROUND): ciphertext = enc_round(ciphertext, key) key = key_schedule(key) ciphertext = S_layer(ciphertext) ciphertext ^= key return ciphertext def key_ex(num: int) -> int: result = 0 bit_position = 0 while num > 0: original_bits = num & 0b111 parity_bit = bin(original_bits).count('1') % 2 result |= (original_bits << (bit_position + 1) ) | (parity_bit << bit_position) num >>= 3 bit_position += 4 return result def write_to_binary_file(uint32_list, output_file): with open(output_file, 'wb') as f: for number in uint32_list: # Pack the integer as an unsigned 32-bit integer (using 'I' format) packed_data = struct.pack('<I', number) f.write(packed_data) def read_from_binary_file(input_file): uint32_list = [] with open(input_file, 'rb') as f: while True: # Read 4 bytes (32 bits) from the file data = f.read(4) if not data: break # End of file reached number = struct.unpack('<I', data)[0] uint32_list.append(number) return uint32_list def bytes_to_uint32_list(byte_string, fill_value=None): uint32_list = [] remainder = len(byte_string) % 4 if remainder != 0: padding_bytes = 4 - remainder if fill_value is not None: byte_string += bytes([fill_value] * padding_bytes) for i in range(0, len(byte_string), 4): data_chunk = byte_string[i:i+4] number = struct.unpack('<I', data_chunk)[0] uint32_list.append(number) return uint32_list def l6shad(x): # Convert the 24-bit integer x to a bytes object (3 bytes) x_bytes = x.to_bytes(3, 'big') sha256_hash = hashlib.sha256(x_bytes).hexdigest() last_six_hex_digits = sha256_hash[-6:] result_int = int(last_six_hex_digits, 16) return result_int
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2024/crypto/sym_signin/task.py
ctfs/D3CTF/2024/crypto/sym_signin/task.py
import random from secret import secret_KEY, flag from task_utils import * plain = read_from_binary_file('plain') cipher = [] for i in range(len(plain)): x = encrypt(message=plain[i], key=secret_KEY, ROUND=8192) cipher.append(x) write_to_binary_file(cipher, 'cipher') plain_flag = bytes_to_uint32_list(flag) enc_flag = [] temp_key = l6shad(secret_KEY) for i in range(len(plain_flag)): enc_flag.append(encrypt(message=plain_flag[i], key=temp_key, ROUND=8192)) temp_key = l6shad(temp_key) write_to_binary_file(enc_flag, 'flag.enc')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2024/crypto/myRSA/task.py
ctfs/D3CTF/2024/crypto/myRSA/task.py
from random import randint from gmpy2 import * from Crypto.Util.number import * from secret import flag class LFSR: def __init__(self, seed, length): self.mask = 0b10000100100100100100100100100100100100100100100100100100100100100100100100100100100100110 self.length = length self.lengthmask = 2**self.length - 1 self.state = seed def next(self): i = self.state & self.mask self.state = (self.state << 1) & self.lengthmask lastbit = 0 while i != 0: lastbit ^= i & 1 i = i >> 1 self.state ^= lastbit return lastbit seed = randint(0, 2**89) lfsr = LFSR(seed, 89) def get_bits(n): s = "" for _ in range(n): s += str(lfsr.next()) return s bits = 256 a = [get_bits(bits) for _ in range(8)] b = [get_bits(bits) for _ in range(8)] p1 = next_prime(int(b[1], 2)) q1 = next_prime(int(b[0] + "".join(a[2:]), 2)) p2 = next_prime(int(a[1], 2)) q2 = next_prime(int(a[0] + "".join(b[2:]), 2)) N1 = p1 * q1 N2 = p2 * q2 e = 65537 m = bytes_to_long(flag) c = pow(m, e, N2) print(f"{N1 = }") print(f"{N2 = }") print(f"{c = }") # N1 = 11195108435418195710792588075406654238662413452040893604269481198631380853864777816171135346615239847585274781942826320773907414919521767450698159152141823148113043170072260905000812966959448737906045653134710039763987977024660093279241536270954380974093998238962759705207561900626656220185252467266349413165950122829268464816965028949121220409917771866453266522778041491886000765870296070557269360794230165147639201703312790976341766891628037850902489808393224528144341687117276366107884626925409318998153959791998809250576701129098030933612584038842347204032289231076557168670724255156010233010888918002630018693299 # N2 = 15100254697650550107773880032815145863356657719287915742500114525591753087962467826081728465512892164117836132237310655696249972190691781679185814089899954980129273157108546566607320409558512492474972517904901612694329245705071789171594962844907667870548108438624866788136327638175865250706483350097727472981522495023856155253124778291684107340441685908190131143526592231859940556416271923298043631447630144435617140894108480182678930181019645093766210388896642127572162172851596331016756329494450522133805279328640942549500999876562756779916153474958590607156569686953857510763692124165713467629066731049974996526071 # c = 4814924495615599863001719377787452659409530421473568305028025012566126400664362465878829645297418472853978736123334486954531551369698267539790007454131291197238666548347098462574649698959650399163371262093116196849478966536838813625531493756454672767925688817717023571267320336512019086040845336203876733170680765788230657626290346741730982737645243576591521512217549028162039336681342312618225110504010746912604698079363106352791499951364510694837846064947033912634697178711135807010770985698854383359436879061864935030256963597840531276583023488437671584864430423908673190679945703404235633491522955548722332086120
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2024/crypto/S0DH/challenge.py
ctfs/D3CTF/2024/crypto/S0DH/challenge.py
from sage.all import * from Crypto.Util.number import bytes_to_long from secret import flag import hashlib flag_start = b'd3ctf{' assert flag.startswith(flag_start) flag = flag[len(flag_start):-1] assert len(flag) == 32 a = 38 b = 25 p = 2**a * 3**b - 1 assert is_prime(p) Fp = GF(p) Fpx = PolynomialRing(Fp, "x") x = Fpx.gen() Fp2 = Fp.extension(x**2 + 1, "ii") ii = Fp2.gen() A0 = Fp2(6) E0 = EllipticCurve(Fp2, [0, A0, 0, 1, 0]) E0.set_order((p+1)**2) sqrtof2 = Fp2(2).sqrt() f = x**3 + A0 * x**2 + x Pa = E0(0) Qa = E0(0) Pa_done = False Qa_done = False d = 0 for c in range(0, p): Rx = ii + c Ry_square = f(ii + c) if not Ry_square.is_square(): continue Ra = E0.lift_x(Rx) Pa = 3**b * Ra Ta = 2 ** (a - 1) * Pa if Ta.is_zero(): continue Tax_plus_3 = Ta.xy()[0] + 3 if Tax_plus_3 == 2 * sqrtof2 or Tax_plus_3 == -2 * sqrtof2: Pa_done = True elif Tax_plus_3 == 3 and not Qa_done: Qa = Pa Qa_done = True else: raise ValueError('Unexcepted order 2 point.') if Pa_done and Qa_done: break assert Pa.order() == 2**a and Qa.order() == 2**a assert Pa.weil_pairing(Qa, 2**a) ** (2 ** (a - 1)) != 1 Pb = E0(0) while (3**(b-1))*Pb == 0: Pb = 2**a * E0.random_point() Qb = Pb while Pb.weil_pairing(Qb, 3**b)**(3**(b-1)) == 1: Qb = 2**a * E0.random_point() print(f'Pa = {Pa.xy()}') print(f'Qa = {Qa.xy()}') print(f'Pb = {Pb.xy()}') print(f'Qb = {Qb.xy()}') sa = randint(0, 2**a-1) Ra = Pa + sa * Qa phia = E0.isogeny(kernel=Ra, algorithm='factored', model='montgomery', check=False) Ea = phia.codomain() sb = randint(0, 3**b-1) Rb = Pb + sb * Qb phib = E0.isogeny(kernel=Rb, algorithm='factored', model='montgomery', check=False) Ea, phia_Pb, phia_Qb = phia.codomain(), phia(Pb), phia(Qb) Eb, phib_Pa, phib_Qa = phib.codomain(), phib(Pa), phib(Qa) print(f'phib_Pa = {phib_Pa.xy()}') print(f'phib_Qa = {phib_Qa.xy()}') print(f'Ea: {Ea}') print(f'Eb: {Eb}') phib_Ra = phib_Pa + sa * phib_Qa Eab = Eb.isogeny(kernel=phib_Ra, algorithm='factored', model='montgomery', check=False).codomain() jab = Eab.j_invariant() phia_Rb = phia_Pb + sb * phia_Qb Eba = Ea.isogeny(kernel=phia_Rb, algorithm='factored', model='montgomery', check=False).codomain() jba = Eba.j_invariant() assert jab == jba h = bytes_to_long(hashlib.sha256(str(jab).encode()).digest()) enc = h ^ bytes_to_long(flag) print(f'enc = {enc}') """ Pa = (199176096138773310217268*ii + 230014803812894614137371, 21529721453350773259901*ii + 106703903226801547853572) Qa = (8838268627404727894538*ii + 42671830598079803454272, 232086518469911650058383*ii + 166016721414371687782077) Pb = (200990566762780078867585*ii + 156748548599313956052974, 124844788269234253758677*ii + 161705339892396558058330) Qb = (39182754631675399496884*ii + 97444897625640048145787, 80099047967631528928295*ii + 178693902138964187125027) phib_Pa = (149703758091223422379828*ii + 52711226604051274601866, 112079580687990456923625*ii + 147229726400811363889895) phib_Qa = (181275595028116997198711*ii + 186563896197914896999639, 181395845909382894304538*ii + 69293294106635311075792) Ea: Elliptic Curve defined by y^2 = x^3 + (11731710804095179287932*ii+170364860453198752624563)*x^2 + x over Finite Field in ii of size 232900919541184113672191^2 Eb: Elliptic Curve defined by y^2 = x^3 + (191884939246592021710422*ii+96782382528277357218650)*x^2 + x over Finite Field in ii of size 232900919541184113672191^2 enc = 48739425383997297710665612312049549178322149326453305960348697253918290539788 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2024/crypto/enctwice/enctwice.py
ctfs/D3CTF/2024/crypto/enctwice/enctwice.py
import os import secret from random import seed, choice from Crypto.Cipher import ChaCha20,AES from Crypto.Util.number import * from string import ascii_letters, digits from hashlib import sha256 D3 = 300 def proof_of_work(): seed(os.urandom(8)) proof = ''.join([choice(ascii_letters + digits) for _ in range(20)]) digest = sha256(proof.encode('latin-1')).hexdigest() print('sha256(XXXX + {}) == {}'.format(proof[4:], digest)) msg = input('Give me XXXX >') if msg != proof[:4]: return False return True def pad(msg): need = (0x20) - (len(msg) & (0x1F)) return msg + bytes([need]) * need def unpad(msg): need = msg[-1] for i in msg[-need:]: assert i == need return msg[:-need] class MYENC: def __init__(self): self.CHACHA_KEY = os.urandom(32) self.AUTH_DATA = os.urandom(32) self.AES_KEY = os.urandom(32) self.P = getPrime(256) self.LIMIT = 2**250 self.X = getPrime(251) self.LEGAL = "0123456789ABCDEF" def hash(self, r, s, ct): L = self.AUTH_DATA + ct + long_to_bytes(len(self.AUTH_DATA), 16) + long_to_bytes(len(ct), 16) res = 0 for i in range(0, len(L), 32): res = (res + bytes_to_long(L[i:i+32]) + 2**256) * r % self.P return (res + s) % self.LIMIT def encrypt1(self, msg): msg = pad(msg) nonce = os.urandom(12) cipher = ChaCha20.new(key = self.CHACHA_KEY, nonce = nonce) ct = cipher.encrypt(bytes([0]) * 32 + msg) r, s, ct = bytes_to_long(ct[:16]), bytes_to_long(ct[16:32]), ct[32:] tag = self.hash(r, s, ct) return ct, tag, nonce def encrypt2(self, msg): msg = pad(msg) iv = os.urandom(16) cipher = AES.new(key = self.AES_KEY, mode = AES.MODE_OFB, iv = iv) ct = cipher.encrypt(msg) return ct, iv def encrypt_msg(self, msg): assert len(msg) < 32 ct1, tag, nonce = self.encrypt1(msg) ct2, iv = self.encrypt2(msg) return ct1 + long_to_bytes(tag + bytes_to_long(ct2) * self.X) + iv + nonce def decrypt1(self, msg, tag, nonce): cipher = ChaCha20.new(key = self.CHACHA_KEY, nonce = nonce) pt = cipher.decrypt(bytes([0]) * 32 + msg) r, s, pt = bytes_to_long(pt[:16]), bytes_to_long(pt[16:32]), pt[32:] assert tag == self.hash(r, s, msg) return unpad(pt) def decrypt2(self, msg, iv): cipher = AES.new(key = self.AES_KEY, mode = AES.MODE_OFB, iv = iv) pt = cipher.decrypt(msg) return unpad(pt) def verify_msg(self, msg): ct1, val, iv, nonce = msg[:32], bytes_to_long(msg[32:-28]), msg[-28:-12], msg[-12:] tag, ct2 = val % self.X, long_to_bytes(val // self.X) pt1 = self.decrypt1(ct1, tag, nonce) pt2 = self.decrypt2(ct2, iv) for i, j in zip(pt1, pt2): assert i == j return "Valid message!" def change_X(self, msg): for i in msg: assert i in self.LEGAL try: new_X = eval(msg) except: new_X = eval("0x" + msg) new_X = getPrime(new_X) if new_X < self.LIMIT: return "Invalid X!" self.X = new_X return "Valid X!" if __name__ == "__main__": if not proof_of_work(): exit() myenc = MYENC() cnt = 7 print(f"Now, you have {cnt} chances to modify the encryption or encrypt your own message.") print(f"Good luck!") for i in range(cnt): type = input("> ") if "encrypt" in type : try: msg = bytes.fromhex(input("input your message >").replace(" ","").strip())[:31] res = myenc.encrypt_msg(msg) print(res.hex()) except: print("Invalid message!") elif "change X" in type : try: msg = input("input your X >")[:2] res = myenc.change_X(msg) print(res) except: print("Invalid X!") flag = secret.flag enc_flag = myenc.encrypt_msg(flag) print(f"Here is your flag:") print(enc_flag.hex()) print(f"Now, feel free to verify your encrypted message!") while(True): msg = input(">") if msg == "exit" : break try: msg = bytes.fromhex(msg.replace(" ","").strip()) res = myenc.verify_msg(msg) print(res) except: print("Invalid message!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2023/crypto/d3bdd/util.py
ctfs/D3CTF/2023/crypto/d3bdd/util.py
from Crypto.Util.number import * class PRNG: def __init__(self , seed): self.state = bytes_to_seedlist(seed) self.m = 738136690439 # f = [randint(0 , m) for _ in range(16)] self.f = [172726532595, 626644115741, 639699034095, 505315824361, 372926623247, 517574605128, 185188664643, 151765551359, 246806484646, 313551698318, 366113530275, 546914911952, 246941706000, 157807969353, 36763045564, 110917873937] self.mbit = 40 self.d = 16 for i in range(self.d): self.generate() def generate(self): res = 0 for i in range(self.d): res += self.f[i] * self.state[i] res %= self.m self.state = self.state[1:] + [res] def raw_rand(self): temp = self.state[0] self.generate() return temp q = 2**32-5 n = 512 class polynomial: # polynomial in Zq[x]/(x^n - 1) def __init__(self,flist): if type(flist) == list: assert len(flist) == n self.f = [flist[i] % q for i in range(n)] def __add__(self , other): assert type(other) == polynomial return polynomial([(self.f[i] + other.f[i])%q for i in range(n)]) def __sub__(self , other): assert type(other) == polynomial return polynomial([(self.f[i] - other.f[i])%q for i in range(n)]) def __mul__(self , other): assert type(other) == polynomial res = [0]*n for i in range(n): for j in range(n): res[(i+j)%n] += self.f[i] * other.f[j] res[(i+j)%n] %= q return polynomial(res) def bytes_to_seedlist(seedbytes): seedlist = [] for i in range(16): seedlist.append(bytes_to_long(seedbytes[i*4:i*4+4])) return seedlist def sample_poly(seed , lower , upper): prng = PRNG(seed) polylist = [] for i in range(n): polylist.append((prng.raw_rand() % (upper - lower)) + lower) return polynomial(polylist) def encode_m(m): m = bytes_to_long(m) flist = [] for i in range(n): flist = [m&1] + flist m >>= 1 return polynomial(flist)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2023/crypto/d3bdd/task.py
ctfs/D3CTF/2023/crypto/d3bdd/task.py
from util import * from hashlib import * import os from secret import flag from Crypto.Util.number import * assert flag[:9] == b'antd3ctf{' and flag[-1:] == b'}' and len(flag) == 64 assert sha256(flag).hexdigest() == '8ea9f4a9de94cda7a545ae8e7c7c96577c2e640b86efe1ed738ecbb5159ed327' seed = sha256(b"welcome to D3CTF").digest() + sha256(b"have a nice day").digest() A = sample_poly(seed , 0 , 2**32 - 5) e = sample_poly(os.urandom(64) , -4 , 4) s = encode_m(flag) b = A*s + e print(b.f) ''' [3926003029, 1509165306, 3106651955, 2983949872, 2393378576, 284179519, 2886272223, 1233125702, 3238739406, 2644118828, 3957954911, 3691185583, 1700019866, 2347785071, 1123825909, 2465646007, 401380313, 2707319872, 4202699559, 931784437, 3583947386, 2536644387, 2751259493, 1013056277, 1594454226, 3085910471, 3351540180, 2578522714, 2124408803, 1473642602, 2384063470, 215471267, 2252434344, 840082094, 1706153260, 628595906, 2138641953, 1768585251, 3672294042, 2648955311, 1101545943, 1462829980, 2490861499, 3154433480, 3991951537, 4073147435, 3072173371, 2030645383, 2273617209, 610264621, 698372144, 965611111, 3030212709, 3123517391, 1661563411, 2903488892, 4125601987, 3275402564, 3358433812, 1301393717, 183795461, 1088441539, 2652556595, 2457427974, 358582424, 3817487396, 3425059438, 3815131707, 3220004354, 3593522122, 323522616, 2934869693, 1474202000, 3934228907, 2196320858, 789973717, 2041502218, 3287331728, 4058939697, 4049446313, 348017657, 312085362, 2087430022, 2409976112, 4182313358, 2820922003, 3439144715, 2835376655, 4164304483, 3992296837, 713727154, 3972583007, 2995414574, 2136905409, 2369686792, 4225590417, 2855379895, 2894275304, 4218198385, 1863573123, 152470219, 209356356, 2181932671, 87528118, 1509977039, 4251082194, 2394181037, 2698855020, 2791852460, 2343631203, 3588377079, 3883095017, 950749052, 1959173107, 444526794, 1655217840, 1576152947, 1208885396, 1891439027, 2519060478, 3957349805, 2330774404, 1021949515, 626605966, 1495609785, 3059250785, 10735841, 631635858, 2165633772, 1024411702, 1473058591, 1486765493, 1116319646, 2246642032, 136293218, 2809056783, 1207288553, 2490191164, 2022388061, 685418618, 1646546899, 2121499626, 1520638759, 2692413636, 1600251896, 1096615514, 377802389, 2828283506, 1184471637, 1095772453, 2518678208, 2091649527, 2790341258, 2122133496, 2008741414, 1931789532, 3407552039, 2037926317, 3785173109, 537388020, 1347520697, 555823746, 45926964, 2223751155, 2244475841, 1543489738, 722236260, 509055199, 3467634480, 580843748, 1285583898, 762172276, 174622846, 3028903527, 3614079217, 1967089235, 2384435424, 2300454112, 1916488680, 1677513486, 3104896162, 3091029091, 2119463387, 4203135624, 2423205596, 4230847292, 2736568150, 1684068, 4250784177, 741156803, 3460657451, 3249083929, 2818353339, 1641238652, 2040105975, 4195607442, 1149072667, 3335478071, 1960764664, 3978941663, 3482443697, 2656259541, 2956574333, 1327577034, 2436857858, 2073805906, 1802723277, 2678500274, 2972947230, 3132107182, 3467032578, 2426347344, 882119229, 3525375754, 10703769, 2277849193, 2317934043, 4065668868, 1502526735, 2829798591, 491620775, 996910215, 917195400, 1260108701, 2336814388, 37709213, 2901142063, 237197224, 1598485695, 2742667143, 1006207745, 1310704554, 534238429, 3112353574, 2380924842, 488678141, 2362251562, 3671650202, 1373474649, 3770563775, 938589647, 1910576969, 2028715086, 2361257827, 2670923858, 3965429861, 3439583492, 2533589001, 3994264580, 939094829, 3362711263, 704355043, 2954166903, 3966370527, 507768808, 556128950, 113005142, 801326514, 2148700895, 3781985160, 509773408, 3517580267, 2066978314, 2580741498, 3483049277, 3402728951, 1376657292, 1005665197, 2226368584, 1962189041, 671306169, 3775557986, 829941861, 2266480501, 3373215874, 2066458459, 3942151992, 836495238, 3356308384, 1790629422, 577081693, 3896293081, 3143007239, 29998790, 3635296087, 1778531590, 3529468062, 1032288519, 4158133379, 670147084, 786100224, 4145211264, 3106208132, 2414940297, 816565256, 2421147924, 1115269055, 84397462, 450125894, 2616534041, 933989700, 2830477525, 3491928047, 1947624924, 2686771420, 2902325901, 160232448, 3325505253, 2612766083, 2059426891, 3360947950, 2872564882, 1622992720, 2098871616, 431960929, 4066245272, 846589370, 3614792013, 869087998, 3621673292, 3219192545, 3554446061, 2122297338, 1894053711, 3712869523, 3175426433, 1121610839, 1230706582, 883221652, 3378895464, 4209309584, 2997558184, 409046034, 2009074657, 3796666708, 3103438558, 3534784496, 1554926466, 3746409084, 644630989, 847404069, 3238052834, 3158156927, 2168700780, 2867150561, 462828594, 3242835677, 3788069093, 2758603660, 1152155811, 1634934432, 3750823533, 1966238016, 3434703051, 2587050497, 369972874, 1571180588, 502826002, 1394977871, 4209562869, 3661291539, 655998304, 3002301529, 738694423, 1318870183, 1813578224, 2117155417, 2792274549, 469969773, 2885986431, 1205074516, 2141754983, 2119779464, 1794537683, 2109156365, 4041147529, 4112783190, 3639979267, 2833631339, 4023397109, 3724794745, 2898586369, 4243064815, 3173181480, 3547135838, 4216682410, 2537261684, 2850433542, 219483902, 243293295, 3201931974, 3383998262, 2891064412, 2210611534, 1659936487, 2238921384, 1601586549, 1727355629, 2573540630, 397538418, 3982181296, 592903988, 1371833230, 2459822880, 3557146354, 2701900698, 3989213446, 3905799266, 2347299592, 2697290465, 1591743964, 2197267136, 1589688875, 2236270312, 522765112, 3207165428, 1317506342, 3816533175, 1982758394, 3243657510, 3691510923, 3611761928, 1421484363, 2228564874, 2666808060, 340876439, 1909587779, 3453796155, 563826858, 3667231388, 3801779454, 1450891603, 114865654, 1771017530, 1269957854, 3247368682, 829473682, 765526246, 2549194701, 1799890469, 4040022163, 2804947409, 723163470, 2851338295, 743766905, 1623487669, 3706971079, 1857049314, 3001074984, 2428057325, 965966662, 4147994952, 3435363246, 840837590, 1851376608, 1264280015, 3969646217, 2330457493, 3252447459, 1425491214, 1800245805, 1416249314, 3749252176, 617972101, 2161483583, 507648049, 4125775896, 225981076, 1543568816, 1606049079, 3418639383, 4203621112, 2298305661, 918844283, 1829417811, 3035193519, 899008380, 1911356195, 2266791547, 3222899067, 40452845, 285832361, 3748962583, 1501732506, 3660444087, 115130006, 2069772771, 1407520491, 1003548491, 1077094436, 1418848957, 3098099734, 3358357308, 1389355789, 3500246690, 67778141, 630658758, 1075172903, 2989608028, 1987981397, 254794036, 2707266088, 950342808, 1590742759, 2671217284, 494050210, 1914378487, 4230572038, 1798463290, 1484078510, 2214019553, 2674514189] '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2023/crypto/d3sys/server.py
ctfs/D3CTF/2023/crypto/d3sys/server.py
from Crypto.Util.number import long_to_bytes,bytes_to_long,getPrime,inverse from gmssl.SM4 import CryptSM4,SM4_ENCRYPT,xor from hashlib import sha256 from secret import secret import signal import time import json import os FLAG = b'ant' + secret banner = br""" :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '########::::'###::::'#######::::::'######::'########:'########:::::'#######::::'#####::::'#######:::'#######:: ##.... ##::'## ##::'##.... ##::::'##... ##:... ##..:: ##.....:::::'##.... ##::'##.. ##::'##.... ##:'##.... ##: ##:::: ##:'##:. ##:..::::: ##:::: ##:::..::::: ##:::: ##::::::::::..::::: ##:'##:::: ##:..::::: ##:..::::: ##: ##:::: ##:..:::..:::'#######::::: ##:::::::::: ##:::: ######:::::::'#######:: ##:::: ##::'#######:::'#######:: ##:::: ##:::::::::::...... ##:::: ##:::::::::: ##:::: ##...:::::::'##:::::::: ##:::: ##:'##:::::::::...... ##: ##:::: ##::::::::::'##:::: ##:::: ##::: ##:::: ##:::: ##:::::::::: ##::::::::. ##:: ##:: ##::::::::'##:::: ##: ########:::::::::::. #######:::::. ######::::: ##:::: ##:::::::::: #########::. #####::: #########:. #######:: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::""" MENU1 = br''' ====------------------------------------------------------------------------------------------------------==== | | +---------------------------------------------------------------------+ | | | | | [R]egister [L]ogin [T]ime [E]xit | | | | | +---------------------------------------------------------------------+ | | ====------------------------------------------------------------------------------------------------------==== ''' MENU2 = br''' ====------------------------------------------------------------------------------------------------------==== | | +---------------------------------------------------------------------+ | | | | | [G]et_dp_dq [F]lag [T]ime [E]xit | | | | | +---------------------------------------------------------------------+ | | ====------------------------------------------------------------------------------------------------------==== ''' def pad(msg): tmp = 16 - len(msg)%16 return msg + bytes([tmp] * tmp) def get_token(id:str,nonce:str,_time:int): msg = {"id":id,"admin":0,"nonce":nonce,"time":_time} return str(json.dumps(msg)).encode() class CRT_RSA_SYSTEM: nbit = 1024 blind_bit = 128 unknownbit = 193 def __init__(self): e = 0x10001 p,q = [getPrime(self.nbit // 2) for _ in "AntCTF"[:2]] n = p * q self.pub = (n,e) dp = inverse(e,p - 1) dq = inverse(e,q - 1) self.priv = (p,q,dp,dq,e,n) self.blind() def blind(self): p,q,dp,dq,e,n = self.priv rp,rq = [getPrime(self.blind_bit) for _ in "D^3CTF"[:2]] dp_ = (p-1) * rp + dp dq_ = (q-1) * rq + dq self.priv = (p,q,dp_,dq_,e,n) def get_priv_exp(self): p,q,dp,dq,e,n = self.priv dp_ = dp & (2**(self.nbit//2 + self.blind_bit - self.unknownbit) - 1) dq_ = dq & (2**(self.nbit//2 + self.blind_bit - self.unknownbit) - 1) return (dp_,dq_) def encrypt(self,m): n,e = self.pub return pow(m,e,n) def decrypt(self,c): p,q,dp,dq,e,n = self.priv mp = pow(c,dp,p) mq = pow(c,dq,q) m = crt([mp,mq],[p,q]) assert pow(m,e,n) == c return m class SM4_CTR(CryptSM4): block_size = 16 def _get_timers(self, iv, msgLen): blockSZ = self.block_size blocks = int((msgLen + blockSZ - 1) // blockSZ) timer = bytes_to_long(iv) timers = iv for i in range(1, blocks): timer += 1 timers += long_to_bytes(timer) return timers def encrypt_ctr(self, input_data,count = None): assert len(input_data) % self.block_size == 0 if count == None: count = os.urandom(16) counters = self._get_timers(count,len(input_data)) blocks = xor(self.crypt_ecb(counters), input_data) ciphertext = bytes(blocks) return count + ciphertext[:len(input_data)] def decrypt_ctr(self, input_data): assert len(input_data) % self.block_size == 0 pt = self.encrypt_ctr(input_data[self.block_size:], input_data[:self.block_size]) return pt[self.block_size:] class D3_ENC: def __init__(self,key:bytes,authdate:bytes): self.crt_rsa = CRT_RSA_SYSTEM() self.block = SM4_CTR() self.block.set_key(key, SM4_ENCRYPT) self.authdate = bytes_to_long(authdate) def encrypt(self,msg): assert len(msg) % 16 == 0 cipher = self.block.encrypt_ctr(msg) tag = self.get_tag(msg) return cipher,tag def decrypt(self,cipher): assert len(cipher) % 16 == 0 msg = self.block.decrypt_ctr(cipher) tag = self.get_tag(msg) return msg,tag def get_tag(self,msg): auth_date = self.authdate msg_block = [bytes_to_long(msg[i*16:(i+1)*16]) for i in range(len(msg)//16)] for mi in msg_block: auth_date = int(sha256(str(self.crt_rsa.encrypt(auth_date)).encode()).hexdigest()[:32],16) ^ mi return int(sha256(str(self.crt_rsa.encrypt(auth_date)).encode()).hexdigest()[:32],16) class D3_SYS: def register(self): print('Welcome to D^3 CTF 2023!') username = input("[D^3] USERNAME:") if username in self.UsernameDict: print(f'[D^3] Sorry,the USERNAME {username} has been registered.') return elif len(username) >= 20: print('[D^3] Sorry,the USERNAME can\'t be longer than 20.') return nonce = os.urandom(8).hex() token = get_token(username,nonce,int(time.time())) cipher_token,tag = self.d3block.encrypt(pad(token)) self.UsernameDict[username] = tag print('[D^3] ' + username + ', token is ' + cipher_token.hex() + '& nonce is ' + nonce) def login(self): print('Welcome to D^3 CTF 2023!') username = input("[D^3] USERNAME:") if username not in self.UsernameDict: print('[D^3] Sorry,the username has never been registered.') return False veritag = self.UsernameDict[username] cipher_token = bytes.fromhex(input("[D^3] Token:")) try: msg,tag = self.d3block.decrypt(cipher_token) except: print("[D^3] Something Wrong...quiting....") return False if tag != veritag : print('[D^3] Ouch! HACKER? Get Out!') return False try: token_dict = json.loads(msg.decode('latin-1').strip().encode('utf-8')) except: print('[D^3] Sorry,try again plz..') return False ID = token_dict["id"] if ID != username: print('[D^3] Change name?') return False elif abs(int(time.time()) - token_dict['time']) >= 1: print('[D^3] oh...no...out....') return False elif token_dict['admin'] != True: print("[D^3] Logining.") return False else: print("[D^3] Logining.") return True def time(self): print('[D^3] D^3\' clock shows '+str(int(time.time()))) return def get_dp_dq(self): return self.d3block.crt_rsa.get_priv_exp() def enc_flag(self): flag = FLAG + os.urandom(16) n,e = self.d3block.crt_rsa.pub enc_flag = pow(bytes_to_long(flag),e,n) return enc_flag def handle(self): print(banner.decode()) key = os.urandom(16) authdate = os.urandom(16) self.d3block = D3_ENC(key,authdate) print('[D^3] My initial Authdate is ' + authdate.hex()) print('[D^3] My Auth pubkey is ' + str(self.d3block.crt_rsa.pub)) self.UsernameDict = {} admin = None # signal.alarm(60) # in server....... while 1: print(MENU1.decode()) option = input('option >') if option == 'R': self.register() elif option == 'L': admin = self.login() break elif option == 'T': self.time() else: break if admin != True: print("ByeBye! You are not admin.......") exit() print("Hello,Admin.Now, you have 2 chances to operate.") for __ in 'D^3 CTF'[:2]: print(MENU2.decode()) option = input('option >') if option == 'F': cip = self.enc_flag() print('Encrypted Flag: ' + hex(cip)) elif option == 'G': dp,dq = self.get_dp_dq() print(f'dp,dq:{[dp,dq]}') elif option == 'T': self.time() else: break if __name__ == "__main__": d3sys = D3_SYS() d3sys.handle()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2023/crypto/d3sys/gmssl/SM4.py
ctfs/D3CTF/2023/crypto/d3sys/gmssl/SM4.py
# -*-coding:utf-8-*- # https://github.com/duanhongyi/gmssl import copy from random import choice xor = lambda a, b:list(map(lambda x, y: x ^ y, a, b)) rotl = lambda x, n:((x << n) & 0xffffffff) | ((x >> (32 - n)) & 0xffffffff) get_uint32_be = lambda key_data:((key_data[0] << 24) | (key_data[1] << 16) | (key_data[2] << 8) | (key_data[3])) put_uint32_be = lambda n:[((n>>24)&0xff), ((n>>16)&0xff), ((n>>8)&0xff), ((n)&0xff)] pkcs7_padding = lambda data, block=16: data + [(16 - len(data) % block)for _ in range(16 - len(data) % block)] zero_padding = lambda data, block=16: data + [0 for _ in range(16 - len(data) % block)] pkcs7_unpadding = lambda data: data[:-data[-1]] zero_unpadding = lambda data,i =1:data[:-i] if data[-i] == 0 else i+1 list_to_bytes = lambda data: b''.join([bytes((i,)) for i in data]) bytes_to_list = lambda data: [i for i in data] random_hex = lambda x: ''.join([choice('0123456789abcdef') for _ in range(x)]) # Expanded SM4 box table SM4_BOXES_TABLE = [ 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48, ] # System parameter SM4_FK = [0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc] # fixed parameter SM4_CK = [ 0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9, 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9, 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299, 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279 ] SM4_ENCRYPT = 0 SM4_DECRYPT = 1 PKCS7 = 0 ZERO = 1 class CryptSM4(object): def __init__(self, mode=SM4_ENCRYPT, padding_mode=PKCS7): self.sk = [0] * 32 self.mode = mode self.padding_mode = padding_mode # Calculating round encryption key. # args: [in] a: a is a 32 bits unsigned value; # return: sk[i]: i{0,1,2,3,...31}. @classmethod def _round_key(cls, ka): b = [0, 0, 0, 0] a = put_uint32_be(ka) b[0] = SM4_BOXES_TABLE[a[0]] b[1] = SM4_BOXES_TABLE[a[1]] b[2] = SM4_BOXES_TABLE[a[2]] b[3] = SM4_BOXES_TABLE[a[3]] bb = get_uint32_be(b[0:4]) rk = bb ^ (rotl(bb, 13)) ^ (rotl(bb, 23)) return rk # Calculating and getting encryption/decryption contents. # args: [in] x0: original contents; # args: [in] x1: original contents; # args: [in] x2: original contents; # args: [in] x3: original contents; # args: [in] rk: encryption/decryption key; # return the contents of encryption/decryption contents. @classmethod def _f(cls, x0, x1, x2, x3, rk): # "T algorithm" == "L algorithm" + "t algorithm". # args: [in] a: a is a 32 bits unsigned value; # return: c: c is calculated with line algorithm "L" and nonline # algorithm "t" def _sm4_l_t(ka): b = [0, 0, 0, 0] a = put_uint32_be(ka) b[0] = SM4_BOXES_TABLE[a[0]] b[1] = SM4_BOXES_TABLE[a[1]] b[2] = SM4_BOXES_TABLE[a[2]] b[3] = SM4_BOXES_TABLE[a[3]] bb = get_uint32_be(b[0:4]) c = bb ^ ( rotl( bb, 2)) ^ ( rotl( bb, 10)) ^ ( rotl( bb, 18)) ^ ( rotl( bb, 24)) return c return (x0 ^ _sm4_l_t(x1 ^ x2 ^ x3 ^ rk)) def set_key(self, key, mode): key = bytes_to_list(key) MK = [0, 0, 0, 0] k = [0] * 36 MK[0] = get_uint32_be(key[0:4]) MK[1] = get_uint32_be(key[4:8]) MK[2] = get_uint32_be(key[8:12]) MK[3] = get_uint32_be(key[12:16]) k[0:4] = xor(MK[0:4], SM4_FK[0:4]) for i in range(32): k[i + 4] = k[i] ^ ( self._round_key(k[i + 1] ^ k[i + 2] ^ k[i + 3] ^ SM4_CK[i])) self.sk[i] = k[i + 4] self.mode = mode if mode == SM4_DECRYPT: for idx in range(16): t = self.sk[idx] self.sk[idx] = self.sk[31 - idx] self.sk[31 - idx] = t def one_round(self, sk, in_put): out_put = [] ulbuf = [0] * 36 ulbuf[0] = get_uint32_be(in_put[0:4]) ulbuf[1] = get_uint32_be(in_put[4:8]) ulbuf[2] = get_uint32_be(in_put[8:12]) ulbuf[3] = get_uint32_be(in_put[12:16]) for idx in range(32): ulbuf[idx + 4] = self._f(ulbuf[idx], ulbuf[idx + 1], ulbuf[idx + 2], ulbuf[idx + 3], sk[idx]) out_put += put_uint32_be(ulbuf[35]) out_put += put_uint32_be(ulbuf[34]) out_put += put_uint32_be(ulbuf[33]) out_put += put_uint32_be(ulbuf[32]) return out_put def crypt_ecb(self, input_data): # SM4-ECB block encryption/decryption input_data = bytes_to_list(input_data) if self.mode == SM4_ENCRYPT: if self.padding_mode == PKCS7: input_data = pkcs7_padding(input_data) elif self.padding_mode == ZERO: input_data = zero_padding(input_data) length = len(input_data) i = 0 output_data = [] while length > 0: output_data += self.one_round(self.sk, input_data[i:i + 16]) i += 16 length -= 16 if self.mode == SM4_DECRYPT: if self.padding_mode == PKCS7: return list_to_bytes(pkcs7_unpadding(output_data)) elif self.padding_mode == ZERO: return list_to_bytes(zero_unpadding(output_data)) return list_to_bytes(output_data) def crypt_cbc(self, iv, input_data): # SM4-CBC buffer encryption/decryption i = 0 output_data = [] tmp_input = [0] * 16 iv = bytes_to_list(iv) if self.mode == SM4_ENCRYPT: input_data = pkcs7_padding(bytes_to_list(input_data)) length = len(input_data) while length > 0: tmp_input[0:16] = xor(input_data[i:i + 16], iv[0:16]) output_data += self.one_round(self.sk, tmp_input[0:16]) iv = copy.deepcopy(output_data[i:i + 16]) i += 16 length -= 16 return list_to_bytes(output_data) else: length = len(input_data) while length > 0: output_data += self.one_round(self.sk, input_data[i:i + 16]) output_data[i:i + 16] = xor(output_data[i:i + 16], iv[0:16]) iv = copy.deepcopy(input_data[i:i + 16]) i += 16 length -= 16 return list_to_bytes(pkcs7_unpadding(output_data))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2023/crypto/d3noisy/task.py
ctfs/D3CTF/2023/crypto/d3noisy/task.py
from Crypto.Util.number import * from random import shuffle from sympy import nextprime def getKey(): p = getPrime(1024) q = getPrime(1024) n = p * q N = [getRandomNBitInteger(3211) for _ in range(15)] d = 0 for _ in N: d = d ^ _ d = nextprime(d) e = inverse(d,(p-1)*(q-1)) return N, n, e def leak(N): p,S = [],[] for i in range(15): p.append(getPrime(321)) r = [N[_]%p[i] for _ in range(15)] shuffle(r) S.append(r) return p, S m = bytes_to_long(flag) N,n,e = getKey() p,S = leak(N) c = pow(m,e,n) print(f"n = {n}") print(f"p = {p}") print(f"S = {S}") print(f"c = {c}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2023/web/EscapePlan/challenge/app.py
ctfs/D3CTF/2023/web/EscapePlan/challenge/app.py
import base64 from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def challenge_3(): cmd = request.form.get("cmd", "") if not cmd: return """<pre> import requests, base64 exp = '' requests.post("", data={"cmd": base64.b64encode(exp.encode())}).text </pre> """ try: cmd = base64.b64decode(cmd).decode() except Exception: return "bad base64" black_char = [ "'", '"', '.', ',', ' ', '+', '__', 'exec', 'eval', 'str', 'import', 'except', 'if', 'for', 'while', 'pass', 'with', 'assert', 'break', 'class', 'raise', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ] for char in black_char: if char in cmd: return f'failed: `{char}`' msg = "success" try: eval(cmd) except Exception: msg = "error" return msg
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2022/pwn/d3guard/run.py
ctfs/D3CTF/2022/pwn/d3guard/run.py
import os, subprocess import random def main(): try: ret = subprocess.call([ "qemu-system-x86_64", "-m", f"{256+random.randint(0, 512)}", "-drive", f"if=pflash,format=raw,file=OVMF.fd", "-drive", "file=fat:rw:contents,format=raw", "-net", "none", "-monitor", "/dev/null", "-nographic" ], stderr=subprocess.DEVNULL) print("Return:", ret) except: print("Error!") finally: print("Done.") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2022/rev/d3thon/main.py
ctfs/D3CTF/2022/rev/d3thon/main.py
import byte_analizer as ba with open("bcode.lbc", "r") as fi: statmts = fi.read().split("\n") for i in statmts: ba.analize(i)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2022/crypto/d3bug/task.py
ctfs/D3CTF/2022/crypto/d3bug/task.py
from Crypto.Util.number import * from secret import flag assert flag.startswith("D3CTF{") assert flag.endswith("}") message = bytes_to_long(flag[6:-1]) assert message < 2**64 mask = 0b1010010000001000000010001001010010100100000010000000100010010100 def lfsr_MyCode(R,mask): output = (R << 1) & 0xffffffffffffffff i = (R ^ mask) & 0xffffffffffffffff lastbit = 0 while i != 0: lastbit ^= (i & 1) i = i>>1 output ^= lastbit return (output,lastbit) def lfsr_CopiedfromInternet(R,mask): output = (R << 1) & 0xffffffffffffffff i = (R & mask) & 0xffffffffffffffff lastbit = 0 while i != 0: lastbit ^= (i & 1) i = i>>1 output ^= lastbit return (output,lastbit) f=open("standardResult","w") R=message for i in range(35): (R, out) = lfsr_CopiedfromInternet(R,mask) f.write(str(out)) f.close() f=open("myResult","w") R=message for i in range(35): (R, out) = lfsr_MyCode(R,mask) f.write(str(out)) f.close() #Why are the results always different?!! #Can you help me debug my code? QAQ
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2022/crypto/d3qcg/babyqcg_d93b0b026b8855bd98709388883c98c7.py
ctfs/D3CTF/2022/crypto/d3qcg/babyqcg_d93b0b026b8855bd98709388883c98c7.py
from Crypto.Util.number import * import random from random import randint from gmpy2 import * from secret import flag import hashlib assert b'd3ctf' in flag Bits = 512 UnKnownBits = 146 class QCG(): def __init__(self,bit_length): p = getPrime(bit_length) a = randint(0,p) c = randint(0,p) self._key = {'a':a,'c':c,'p':p} self.secret = randint(0,p) self.high = [] def Qnext(self,num): return ((self._key['a'])*num**2+self._key['c'])%self._key['p'] def hint(self): num = self.secret for i in range(2): num = self.Qnext(num) self.high.append(num>>UnKnownBits) def get_key(self): return self._key def get_hint(self): return self.high Q1 = QCG(Bits) print(Q1.get_key()) #{'a': 3591518680290719943596137190796366296374484536382380061852237064647969442581391967815457547858969187198898670115651116598727939742165753798804458359397101, 'c': 6996824752943994631802515921125382520044917095172009220000813718617441355767447428067985103926211738826304567400243131010272198095205381950589038817395833, 'p': 7386537185240346459857715381835501419533088465984777861268951891482072249822526223542514664598394978163933836402581547418821954407062640385756448408431347} Q1.hint() print(Q1.get_hint()) #[67523583999102391286646648674827012089888650576715333147417362919706349137337570430286202361838682309142789833, 70007105679729967877791601360700732661124470473944792680253826569739619391572400148455527621676313801799318422] enc = bytes_to_long(hashlib.sha512(b'%d'%(secret)).digest())^bytes_to_long(flag) print(enc) # 6176615302812247165125832378994890837952704874849571780971393318502417187945089718911116370840334873574762045429920150244413817389304969294624001945527125
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2022/crypto/equivalent/task.py
ctfs/D3CTF/2022/crypto/equivalent/task.py
from collections import namedtuple from Crypto.Util import number from Crypto.Random import random PublicKey = namedtuple('PublicKey', ['a']) SecretKey = namedtuple('SecretKey', ['s', 'e', 'p']) def keygen(sbit, N): s_ = [random.getrandbits(sbit) | 1 for _ in range(N)] pbit = sum(s_).bit_length() + 1 p = number.getPrime(pbit) while not (sum(s_) < p < 2*sum(s_)): p = number.getPrime(pbit) e = random.randint(p//2, p-1) a_ = [e*s_i % p for s_i in s_] assert 2**N > max(a_) pk = PublicKey(a_) sk = SecretKey(s_, e, p) return (pk, sk) def enc(m, pk): assert 0 <= m < 2 n = len(pk.a) r_ = [random.getrandbits(1) for _ in range(n-1)] r_n = (m - sum(r_)) % 2 r_.append(r_n) c = sum(a_i*r_i for a_i, r_i in zip(pk.a, r_)) return c def dec(c, sk): e_inv = number.inverse(sk.e, sk.p) m = (e_inv * c % sk.p) % 2 return m def encrypt(msg, pk): bits = bin(number.bytes_to_long(msg))[2:] cip = [enc(m, pk) for m in map(int, bits)] return cip def decrypt(cip, sk): bits = [dec(c, sk) for c in cip] msg = number.long_to_bytes(int(''.join(map(str, bits)), 2)) return msg if __name__ == "__main__": from secret import FLAG pk, sk = keygen(sbit=80, N=100) msg = FLAG.removeprefix(b"d3ctf{").removesuffix(b"}") cip = encrypt(msg, pk) assert msg == decrypt(cip, sk) with open("data.txt", 'w') as f: f.write(f"pk = {pk}\n") f.write(f"cip = {cip}\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/D3CTF/2022/crypto/d3factor/d3factor.py
ctfs/D3CTF/2022/crypto/d3factor/d3factor.py
from Crypto.Util.number import bytes_to_long, getPrime from secret import msg from sympy import nextprime from gmpy2 import invert from hashlib import md5 flag = 'd3ctf{'+md5(msg).hexdigest()+'}' p = getPrime(256) q = getPrime(256) assert p > q n = p * q e = 0x10001 m = bytes_to_long(msg) c = pow(m, e, n) N = pow(p, 7) * q phi = pow(p, 6) * (p - 1) * (q - 1) d1 = getPrime(2000) d2 = nextprime(d1 + getPrime(1000)) e1 = invert(d1, phi) e2 = invert(d2, phi) print(f'c = {c}') print(f'N = {N}') print(f'e1 = {e1}') print(f'e2 = {e2}') ''' c = 2420624631315473673388732074340410215657378096737020976722603529598864338532404224879219059105950005655100728361198499550862405660043591919681568611707967 N = 1476751427633071977599571983301151063258376731102955975364111147037204614220376883752032253407881568290520059515340434632858734689439268479399482315506043425541162646523388437842149125178447800616137044219916586942207838674001004007237861470176454543718752182312318068466051713087927370670177514666860822341380494154077020472814706123209865769048722380888175401791873273850281384147394075054950169002165357490796510950852631287689747360436384163758289159710264469722036320819123313773301072777844457895388797742631541101152819089150281489897683508400098693808473542212963868834485233858128220055727804326451310080791 e1 = 425735006018518321920113858371691046233291394270779139216531379266829453665704656868245884309574741300746121946724344532456337490492263690989727904837374279175606623404025598533405400677329916633307585813849635071097268989906426771864410852556381279117588496262787146588414873723983855041415476840445850171457530977221981125006107741100779529209163446405585696682186452013669643507275620439492021019544922913941472624874102604249376990616323884331293660116156782891935217575308895791623826306100692059131945495084654854521834016181452508329430102813663713333608459898915361745215871305547069325129687311358338082029 e2 = 1004512650658647383814190582513307789549094672255033373245432814519573537648997991452158231923692387604945039180687417026069655569594454408690445879849410118502279459189421806132654131287284719070037134752526923855821229397612868419416851456578505341237256609343187666849045678291935806441844686439591365338539029504178066823886051731466788474438373839803448380498800384597878814991008672054436093542513518012957106825842251155935855375353004898840663429274565622024673235081082222394015174831078190299524112112571718817712276118850981261489528540025810396786605197437842655180663611669918785635193552649262904644919 '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/misc/MAnaGerfAker/verifier.py
ctfs/AzureAssassinAlliance/2023/misc/MAnaGerfAker/verifier.py
from secret import flag import os, subprocess, tempfile from base64 import b64decode hash_mod = 1 << 32 hash_mask = hash_mod - 1 def sign_ext(val): if val >= 0x80: return val - 256 + hash_mod return val def calc_hash(data): assert len(data) == 0x33b, "Bad length" base_hash = 1 for v in data: base_hash = (base_hash * 31 + sign_ext(v)) & hash_mask return base_hash wanted_hash = 868400328 print('Wanted hash:', hex(wanted_hash)) print('Please input your apk file(base64-encoded, <10MB, ends with EOF in new line):', end=' ') apk = '' while True: line = input().strip() if line == 'EOF': break apk += line if len(apk) > 20 * 1024 * 1024: print('Too long!') exit() cwd = os.getcwd() apk_data = b64decode(apk) with tempfile.TemporaryDirectory(prefix="MAnaGerfAker") as dir: os.chdir(dir) with open('test.apk', 'wb') as f: f.write(apk_data) ret = subprocess.run(['java', '-jar', os.path.join(cwd, "apksigner.jar"), "verify", "--verbose", "--max-sdk-version", "33", "--min-sdk-version", "27", "test.apk"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if ret.returncode != 0 or len(ret.stderr.strip()) > 0: print('Error(%d):' % (ret.returncode, ), ret.stderr.decode()) exit() ret :str= ret.stdout.decode().strip().replace('\r', '') lower_ret = ret.lower() if 'warning' in lower_ret or 'error' in lower_ret or 'does not verify' in lower_ret or '\nVerifies\n' not in ret or ret.count('Verified using v3 scheme (APK Signature Scheme v3):') != 1 or ret.count('Verified using v2 scheme (APK Signature Scheme v2):') != 1 or '\nVerified using v2 scheme (APK Signature Scheme v2): true\n' not in ret or '\nVerified using v3 scheme (APK Signature Scheme v3): true\n' not in ret: print('Bad apk!') exit() exported_cer = [calc_hash(open(file, 'rb').read()) for file in os.listdir(".") if file.endswith(".cer") and file.startswith("x509_exported_")] if len(exported_cer) == 0 or any([x != wanted_hash for x in exported_cer]): print('No exported cer!') exit() print('Good! You prove it.') print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/misc/SLM/service/service.py
ctfs/AzureAssassinAlliance/2023/misc/SLM/service/service.py
import socketserver import threading import sys import hashlib import string import random import socket import subprocess import requests import os import time import json from termcolor import colored HOST, PORT = "0.0.0.0", 9999 SHOST, SPORT = XXX, XXX NUMBER = 4 POW_DIFFICULTY = 21 TIMEOUT = 60 * 5 POST_TIMEOUT = 60 * 4 SECRET = os.getenv("SERVER_SECRET") log_lock = threading.Lock() bot_lock = threading.Lock() banner = colored(''' /$$$$$$ /$$ /$$ /$$ /$$__ $$ | $$ | $$$ /$$$ | $$ \__/ | $$ | $$$$ /$$$$ | $$$$$$ | $$ | $$ $$/$$ $$ \____ $$ | $$ | $$ $$$| $$ /$$ \ $$ | $$ | $$\ $ | $$ | $$$$$$/ | $$$$$$$$ | $$ \/ | $$ \______/ |________/ |__/ |__/ ''', 'red') def log_wrapper(s): log_lock.acquire() print(colored(f"log - {s}", "yellow")) sys.stdout.flush() log_lock.release() def pow(request): candidates = string.hexdigits + string.ascii_letters prefix = '' for _ in range(4): prefix += candidates[random.randint(0, len(candidates) - 1)] request.sendall( "Proof-of-Work, the resource is quite limited hence the pow is somehow difficult XD\n" f"sha256({ prefix } + ???).binary.startswith('{ '0' * POW_DIFFICULTY }')\n" .encode()) request.sendall(b"> your ???: ") answer = request.recv(256).decode().strip() h = hashlib.sha256() h.update((prefix + answer).encode()) bits = "".join(bin(i)[2:].zfill(8) for i in h.digest()) log_wrapper(f"calculate bits {bits}") return bits.startswith("0" * POW_DIFFICULTY) class SLMTCPHandler(socketserver.BaseRequestHandler): def handle(self): self.request.settimeout(TIMEOUT) try: if not pow(self.request): self.request.sendall(b"failed pow ... try again\n") self.request.close() return # actual service here self.request.send(banner.encode()) self.request.send(b"\n") self.request.send("I'm a math question bot powered by langchain + RWKV 🤖️\n".encode()) self.request.send(b"\n") self.request.send(b"For example, you can ask me:\n") self.request.send(b"Olivia has $23. She bought five bagels for $3 each. ") self.request.send(b"How much money does she have left?\n") self.request.send(b"\n") self.request.send(colored("------------------------------- Your Question -------------------------------\n", "red").encode()) self.request.send(b"> ") question_bytes = self.request.recv(256) for q in question_bytes: if chr(q) not in string.printable: self.request.send(b"> ") self.request.send(b"! bad question !") return question_str = question_bytes.decode().strip() log_wrapper(f"receive {question_str}") start_time = time.time() server_url = f"http://{SHOST}:{SPORT}/api/lsm" r = requests.post(server_url, json={"secret": SECRET, "question": question_str}, timeout=POST_TIMEOUT) if r.status_code != 200: self.request.send(b"> ") self.request.send(b"! internal error !") return reply_json = json.loads(r.text) answer = reply_json["result"] end_time = time.time() cost_time = int(end_time - start_time) self.request.send(colored("------------------------------- Your Answer ---------------------------------\n", "red").encode()) self.request.send(b"\n") self.request.send(f"-->\tafter {cost_time} seconds\n".encode()) self.request.send(f"-->\tyour answer: {answer}\n".encode()) self.request.send(b"\n") except socket.timeout: log_wrapper("Connection timed out") except Exception as e: log_wrapper(f"An error occurred: {e}") if __name__ == "__main__": with socketserver.TCPServer((HOST, PORT), SLMTCPHandler) as server: 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/AzureAssassinAlliance/2023/misc/SLM/server/server.py
ctfs/AzureAssassinAlliance/2023/misc/SLM/server/server.py
import os from flask import Flask, jsonify, request import threading import signal import socket import multiprocessing from langchain.chains import PALChain from langchain.llms.rwkv import RWKV model_path = "/data/model.pth" tokenizer_path = "/data/tokenizer.json" model = None HOST, PORT = "0.0.0.0", 19999 SECRET = os.getenv("SERVER_SECRET") TIMEOUT = 60 * 4 bot_lock = threading.Lock() app = Flask(__name__) def check_question(question): return True def handle_question(question, shared): # sorry but we have no idea due to the limited computing resource T.T with bot_lock: try: pal_chain = PALChain.from_math_prompt(model, verbose=True) question_ans = pal_chain.run(question) shared["result"] = question_ans except Exception as err: print(err) shared["result"] = "internal error" @app.route('/api/lsm', methods=['POST']) def handle(): data = request.get_json() secret = data.get('secret') question = data.get('question') if secret != SECRET or not check_question(question): return jsonify({"result": "-1"}) manager = multiprocessing.Manager() shared = manager.dict() p = multiprocessing.Process(target=handle_question, args=(question, shared)) p.start() p.join(TIMEOUT) if p.is_alive(): # timeout p.terminate() return jsonify({"result": "timeout"}) else: return jsonify(dict(shared.copy())) def init_bot(): global model, pal_chain model = RWKV( model=model_path, tokens_path=tokenizer_path, strategy="cpu fp32" ) if __name__ == '__main__': init_bot() app.run(host=HOST,port=PORT)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/misc/SLM/server/test.py
ctfs/AzureAssassinAlliance/2023/misc/SLM/server/test.py
import os from flask import Flask, jsonify, request import threading import signal import socket import multiprocessing from langchain.chains import PALChain from langchain.llms.rwkv import RWKV model_path = "/data/model.pth" tokenizer_path = "/data/tokenizer.json" model = None HOST, PORT = "0.0.0.0", XXX SECRET = os.getenv("SERVER_SECRET") TIMEOUT = 60 * 4 bot_lock = threading.Lock() app = Flask(__name__) def check_question(question): return True def handle_question(question, shared): # sorry but we have no idea due to the limited computing resource T.T with bot_lock: try: pal_chain = PALChain.from_math_prompt(model, verbose=True) question_ans = pal_chain.run(question) shared["result"] = question_ans except Exception as err: print(err) shared["result"] = "internal error" @app.route('/api/lsm', methods=['POST']) def handle(): data = request.get_json() secret = data.get('secret') question = data.get('question') if secret != SECRET or not check_question(question): return jsonify({"result": "-1"}) manager = multiprocessing.Manager() shared = manager.dict() p = multiprocessing.Process(target=handle_question, args=(question, shared)) p.start() p.join(TIMEOUT) if p.is_alive(): # timeout p.terminate() return jsonify({"result": "timeout"}) else: return jsonify(dict(shared.copy())) def init_bot(): global model, pal_chain model = RWKV( model=model_path, tokens_path=tokenizer_path, strategy="cpu fp32" ) if __name__ == '__main__': init_bot() app.run(host=HOST,port=PORT)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/rev/Tree/server.py
ctfs/AzureAssassinAlliance/2023/rev/Tree/server.py
import os import uuid import signal remote_ip_addr = os.getenv("REMOTE_HOST", "localhost") identifier = remote_ip_addr + '_' + str(uuid.uuid4()) temp_file = "tmp_{}.cpp".format(identifier) try: signal.alarm(20) print('Give me your source code with no header. Input "EOF" to end:', flush=True) codes = [] while True: line = input() if line == "EOF": break codes.append(line) with open(temp_file, 'w') as f: f.writelines(codes) res = os.popen(f"./chall {temp_file}").read() if(res == "Right!\n"): with open("./flag.txt",'r') as f: print(f"Here is your flag: {f.read()}", flush=True, end='') else: print("Try harder.", flush=True) except: print("Hacker!", flush=True) finally: print("Bye~", flush=True) os.popen(f"rm {temp_file}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/crypto/claw_crane/task.py
ctfs/AzureAssassinAlliance/2023/crypto/claw_crane/task.py
#!/usr/bin/env python3 from Crypto.Util.number import ( bytes_to_long, long_to_bytes ) from hashlib import md5 import os, signal import sys import random BITS = 128 class ClawCrane(object): def __init__(self) -> None: self.seed = bytes_to_long(os.urandom(BITS//8)) self.bless = 0 self.score = 0 def get_input(self, prompt="> "): print(prompt, end="") sys.stdout.flush() return input() def check_pos(self, pos, moves): col, row = 0, 0 for move in moves: if move == "W": if row < 15: row += 1 elif move == "S": if row > 0: row -= 1 elif move == "A": if col > 0: col -= 1 elif move == "D": if col < 15: col += 1 else: return -1 print(col, row) return pos == [col, row] def gen_chaos(self, inp): def mapping(x): if x=='W': return "0" if x=='S': return "1" if x=='A': return "2" if x=='D': return "3" vs = int("".join(map(mapping, inp)), 4) chaos = bytes_to_long(md5( long_to_bytes((self.seed + vs) % pow(2,BITS)) ).digest()) self.seed = (self.seed + chaos + 1) % pow(2,BITS) return chaos def destiny_claw(self, delta): bits = bin(delta)[2:] if len(bits) < 128+self.bless: bits += "0"*(128+self.bless - len(bits)) c = random.choice(bits) if c=='0': return True else: return False def run(self): pos = [random.randrange(1,16), random.randrange(1,16)] moves = self.get_input(f"i am at {pos}, claw me.\nYour moves: ") if len(moves) > 100: print("too many steps") return if not self.check_pos(pos, moves): print("sorry, clawed nothing") return r = self.gen_chaos(moves[:64]) print(f"choas: {r}") p, q = map(int, self.get_input(f"give me your claw using p,q and p,q in [0, 18446744073709551615] (e.g.: 1,1): ").split(",")) if not (p>0 and p<pow(2,BITS//2) and q>0 and q<pow(2,BITS//2)): print("not in range") return delta = abs(r*q - p*pow(2,BITS)) if self.destiny_claw(delta): self.score += 10 self.bless = 0 print("you clawed it") else: self.bless += 16 print("sorry, clawed nothing") def main(): signal.alarm(600) cc = ClawCrane() for _ in range(256): try: cc.run() print(f"your score: {cc.score}") except: print(f"abort") break if cc.score >= 2220: print(f"flag: {open('/flag.txt').read()}") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/crypto/mt_speed_run/server.py
ctfs/AzureAssassinAlliance/2023/crypto/mt_speed_run/server.py
import random, os, hashlib, base64, signal from secret import FLAG sys_rng = random.SystemRandom() def rand_magic(): while True: value = sys_rng.getrandbits(32) if 10 <= bin(value).count('1') <= 22: return value MAGIC_A = rand_magic() MAGIC_B = rand_magic() MAGIC_C = rand_magic() MAGIC_D = rand_magic() MAGIC_E = sys_rng.randrange(0, 32) # YES, YOU HAVE SEEN THIS PROBLEM MANY TIMES N = 624 NN = 30000 def temper(state): y = state y ^= y >> 11 y ^= (y << 7) & MAGIC_A y ^= (y << 15) & MAGIC_B y ^= (y << MAGIC_E) & MAGIC_D y ^= y >> 18 return y def update_mt(mt): M = 397 UPPER_MASK = 0x80000000 LOWER_MASK = 0x7FFFFFFF for kk in range(N - M): y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK) mt[kk] = mt[kk + M] ^ (y >> 1) ^ (y % 2) * MAGIC_C for kk in range(N - M, N - 1): y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK) mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ (y % 2) * MAGIC_C y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK) mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ (y % 2) * MAGIC_C state = [sys_rng.getrandbits(32) for _ in range(N)] state_i = 0 def next_rand(): global state, state_i ret = temper(state[state_i]) >> 31 state_i += 1 if state_i >= 624: state_i -= 624 update_mt(state) return ret update_mt(state) rands = [next_rand() for _ in range(NN)] ans = hashlib.sha256(','.join(map(str, state)).encode()).hexdigest() print('RANDS = {}'.format(base64.b64encode(int(''.join(map(str, rands)), 2).to_bytes(NN // 8, 'big')).decode())) time_out = False def handler(_signum, _frame): global FLAG, time_out FLAG = None time_out = True signal.signal(signal.SIGALRM, handler) signal.alarm(10) print(f'{MAGIC_A = :#x}') print(f'{MAGIC_B = :#x}') print(f'{MAGIC_C = :#x}') print(f'{MAGIC_D = :#x}') print(f'{MAGIC_E = :#x}') if input('ANS = ') == ans: if time_out: print('CONTINUE OPTIMIZE!!!') else: print('FLAG = {}'.format(FLAG)) else: print('CONTINUE DEBUGGING!!!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/crypto/EasyRSA/task.py
ctfs/AzureAssassinAlliance/2023/crypto/EasyRSA/task.py
from secret import flag from Crypto.Util.number import * def genKey(nbits, dbits): bbits = (nbits // 2 - dbits) // 2 while True: a = getRandomNBitInteger(dbits) b = getRandomNBitInteger(bbits) c = getRandomNBitInteger(bbits) p1 = a * b * c + 1 if isPrime(p1): # print("p1 =", p1) break while True: d = getRandomNBitInteger(dbits) p2 = b * c * d + 1 if isPrime(p2): # print("p2 =", p2) break while True: e = getRandomNBitInteger(bbits) f = getRandomNBitInteger(bbits) q1 = e * d * f + 1 p3 = a * e * f + 1 if isPrime(q1) and isPrime(p3): # print("p3 =", p3) # print("q1 =", q1) break while True: d_ = getRandomNBitInteger(dbits) if GCD(a * b * c * d * e * f, d_) != 1: continue e_ = inverse(d_, a * b * c * d * e * f) k1 = (e_ * d_ - 1) // (a * b * c * d * e * f) assert e_ * d_ == (a * b * c * d * e * f) * k1 + 1 q2 = k1 * e * f + 1 q3 = k1 * b * c + 1 if isPrime(q2) and isPrime(q3): # print("q2 =", q2) # print("q3 =", q3) # print("e =", e_) # print("d =", d_) break n1 = p1 * q1 n2 = p2 * q2 n3 = p3 * q3 assert pow(pow(0xdeadbeef, e_, n1), d_, n1) == 0xdeadbeef assert pow(pow(0xdeadbeef, e_, n2), d_, n2) == 0xdeadbeef assert pow(pow(0xdeadbeef, e_, n3), d_, n3) == 0xdeadbeef return(e_, n1, n2, n3) nbits = 0x600 dbits = 0x210 m = bytes_to_long(flag) e, n1, n2, n3 = genKey(nbits, dbits) c = pow(m, e, n1) print("c =", c) print("e =", e) print("n1 =", n1) print("n2 =", n2) print("n3 =", n3) # c = 63442255298812942222810837512019302954917822996915527697525497640413662503768308023517128481053593562877494934841788054865410798751447333551319775025362132176942795107214528962480350398519459474033659025815248579631003928932688495682277210240277909527931445899728273182691941548330126199931886748296031014210795428593631253184315074234352536885430181103986084755140024577780815130067722355861473639612699372152970688687877075365330095265612016350599320999156644 # e = 272785315258275494478303901715994595013215169713087273945370833673873860340153367010424559026764907254821416435761617347240970711252213646287464416524071944646705551816941437389777294159359383356817408302841561284559712640940354294840597133394851851877857751302209309529938795265777557840238332937938235024502686737802184255165075195042860413556866222562167425361146312096189555572705076252573222261842045286782816083933952875990572937346408235562417656218440227 # n1 = 473173031410877037287927970398347001343136400938581274026578368211539730987889738033351265663756061524526288423355193643110804217683860550767181983527932872361546531994961481442866335447011683462904976896894011884907968495626837219900141842587071512040734664898328709989285205714628355052565784162841441867556282849760230635164284802614010844226671736675222842060257156860013384955769045790763119616939897544697150710631300004180868397245728064351907334273953201 # n2 = 327163771871802208683424470007561712270872666244394076667663345333853591836596054597471607916850284565474732679392694515656845653581599800514388800663813830528483334021178531162556250468743461443904645773493383915711571062775922446922917130005772040139744330987272549252540089872170217864935146429898458644025927741607569303966038195226388964722300472005107075179204987774627759625183739199425329481632596633992804636690274844290983438078815836605603147141262181 # n3 = 442893163857502334109676162774199722362644200933618691728267162172376730137502879609506615568680508257973678725536472848428042122350184530077765734033425406055810373669798840851851090476687785235612051747082232947418290952863499263547598032467577778461061567081620676910480684540883879257518083587862219344609851852177109722186714811329766477552794034774928983660538381764930765795290189612024799300768559485810526074992569676241537503405494203262336327709010421
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/crypto/CRCRC/CRCRC.py
ctfs/AzureAssassinAlliance/2023/crypto/CRCRC/CRCRC.py
from base64 import * def crc128(data, poly = 0x883ddfe55bba9af41f47bd6e0b0d8f8f): crc = (1 << 128) - 1 for b in data: crc ^= b for _ in range(8): crc = (crc >> 1) ^ (poly & -(crc & 1)) return crc ^ ((1 << 128) - 1) with open('./flag.txt','r') as f: flag = f.readline() YourInput = input().encode() YourDecode = b64decode(YourInput, validate=True) print(len(YourDecode)) assert len(YourDecode) <= 127 and YourDecode.startswith(b'Dear guest, welcome to CRCRC Magic House, If you input ') and YourDecode.endswith(b", you will get 0x9c6a11fbc0e97b1fff5844fa88b1ee2d") YourCRC = crc128(YourInput) print(hex(YourCRC)) if(YourCRC) == 0x9c6a11fbc0e97b1fff5844fa88b1ee2d: print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/crypto/MidRSA/task.py
ctfs/AzureAssassinAlliance/2023/crypto/MidRSA/task.py
from secret import flag from Crypto.Util.number import * def genKey(nbits, dbits): bbits = (nbits // 2 - dbits) // 2 while True: a = getRandomNBitInteger(dbits) b = getRandomNBitInteger(bbits) c = getRandomNBitInteger(bbits) p1 = a * b * c + 1 if isPrime(p1): # print("p1 =", p1) break while True: d = getRandomNBitInteger(dbits) p2 = b * c * d + 1 if isPrime(p2): # print("p2 =", p2) break while True: e = getRandomNBitInteger(bbits) f = getRandomNBitInteger(bbits) q1 = e * d * f + 1 p3 = a * e * f + 1 if isPrime(q1) and isPrime(p3): # print("p3 =", p3) # print("q1 =", q1) break while True: d_ = getRandomNBitInteger(dbits) if GCD(a * b * c * d * e * f, d_) != 1: continue e_ = inverse(d_, a * b * c * d * e * f) k1 = (e_ * d_ - 1) // (a * b * c * d * e * f) assert e_ * d_ == (a * b * c * d * e * f) * k1 + 1 q2 = k1 * e * f + 1 q3 = k1 * b * c + 1 if isPrime(q2) and isPrime(q3): # print("q2 =", q2) # print("q3 =", q3) # print("e =", e_) print("d =", d_) break n1 = p1 * q1 n2 = p2 * q2 n3 = p3 * q3 assert pow(pow(0xdeadbeef, e_, n1), d_, n1) == 0xdeadbeef assert pow(pow(0xdeadbeef, e_, n2), d_, n2) == 0xdeadbeef assert pow(pow(0xdeadbeef, e_, n3), d_, n3) == 0xdeadbeef return(e_, n1, n2, n3) nbits = 0x600 dbits = 0x240 m = bytes_to_long(flag) e, n1, n2, n3 = genKey(nbits, dbits) c = pow(m, e, n1) print("c =", c) print("e =", e) print("n1 =", n1) print("n2 =", n2) print("n3 =", n3) # c = 598823083137858565473505718525815255620672892612784824187302545127574115000325539999824374357957135208478070797113625659118825530731575573239221853507638809719397849963861367352055486212696958923800593172417262351719477530809870735637329898331854130533160020420263724619225174940214193740379571953951059401685115164634005411478583529751890781498407518739069969017597521632392997743956791839564573371955246955738575593780508817401390102856295102225132502636316844 # e = 334726528702628887205076146544909357751287869200972341824248480332256143541098971600873722567713812425364296038771650383962046800505086167635487091757206238206029361844181642521606953049529231154613145553220809927001722518303114599682529196697410089598230645579658906203453435640824934159645602447676974027474924465177723434855318446073578465621382859962701578350462059764095163424218813852195709023435581237538699769359084386399099644884006684995755938605201771 # n1 = 621786427956510577894657745225233425730501124908354697121702414978035232119311662357181409283130180887720760732555757426221953950475736078765267856308595870951635246720750862259255389006679454647170476427262240270915881126875224574474706572728931213060252787326765271752969318854360970801540289807965575654629288558728966771231501959974533484678236051025940684114262451777094234017210230731492336480895879764397821363102224085859281971513276968559080593778873231 # n2 = 335133378611627373902246132362791381335635839627660359611198202073307340179794138179041524058800936207811546752188713855950891460382258433727589232119735602364790267515558352318957355100518427499530387075144776790492766973547088838586041648900788325902589777445641895775357091753360428198189998860317775077739054298868885308909495601041757108114540069950359802851809227248145281594107487276003206931533768902437356652676341735882783415106786497390475670647453821 # n3 = 220290953009399899705676642623181513318918775662713704923101352853965768389363281894663344270979715555659079125651553079702318700200824118622766698792556506368153467944348604006011828780474050012010677204862020009069971864222175380878120025727369117819196954091417740367068284457817961773989542151049465711430065838517386380261817772422927774945414543880659243592749932727798690742051285364898081188510009069286094647222933710799481899960520270189522155672272451
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/web/easy_latex/vip-service/app.py
ctfs/AzureAssassinAlliance/2023/web/easy_latex/vip-service/app.py
from flask import Flask, request from Crypto.Cipher import DES from hashlib import md5 import os PORT = int(os.environ.get('PORT', '5000')) app = Flask(__name__) invitation_codes = [] def new_invitation_code(): return os.urandom(8).hex() def check_invitation_code(username:str, code:str): des = DES.new(md5(username.encode()).digest()[:8], DES.MODE_CFB) code = des.decrypt(code.encode()).hex()[:16] if code in invitation_codes: invitation_codes.remove(code) return True return False @app.get('/') def index(): return "Welcome to VIP service. To get an invite code, please contact ppk@aaa.com" @app.post('/<username>') def check(username): token = request.cookies.get('token') if not token: return "unauthorized access?" code = request.form.get('code') if not code: return "no invitation code specified" if check_invitation_code(username, code): return 'ok' return 'invalid invitation code' @app.get('/new') def new_code(): code = new_invitation_code() invitation_codes.append(code) print('new invitation code:', code) return "done" if __name__ == '__main__': app.run('0.0.0.0', PORT)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/web/story/app.py
ctfs/AzureAssassinAlliance/2023/web/story/app.py
from flask import Flask, render_template_string, jsonify, request, session, render_template, redirect import random from utils.captcha import Captcha, generate_code from utils.minic import * app = Flask(__name__) app.config['SECRET_KEY'] = '' @app.route('/', methods=['GET', 'POST']) def index(): username = session.get('username', '') if username != "" and username is not None: return render_template("home.html") return render_template('index.html') @app.route('/captcha') def captcha(): gen = Captcha(200, 80) buf , captcha_text = gen.generate() session['captcha'] = captcha_text return buf.getvalue(), 200, { 'Content-Type': 'image/png', 'Content-Length': str(len(buf.getvalue())) } @app.route('/login', methods=['POST']) def login(): username = request.json.get('username', '') captcha = request.json.get('captcha', '').upper() if captcha == session.get('captcha', '').upper(): session['username'] = username return jsonify({'status': 'success', 'message': 'login success'}) return jsonify({'status': 'error', 'message': 'captcha error'}), 400 @app.route('/vip', methods=['POST']) def vip(): captcha = generate_code() captcha_user = request.json.get('captcha', '') if captcha == captcha_user: session['vip'] = True return render_template("home.html") @app.route('/write', methods=['POST','GET']) def rename(): if request.method == "GET": return redirect('/') story = request.json.get('story', '') if session.get('vip', ''): if not minic_waf(story): session['username'] = "" session['vip'] = False return jsonify({'status': 'error', 'message': 'no way~~~'}) session['story'] = story return jsonify({'status': 'success', 'message': 'success'}) return jsonify({'status': 'error', 'message': 'Please become a VIP first.'}), 400 @app.route('/story', methods=['GET']) def story(): story = session.get('story','') if story is not None and story != "": tpl = open('templates/story.html', 'r').read() return render_template_string(tpl % story) return redirect("/") if __name__ == '__main__': app.run(host="0.0.0.0", port=5001)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/web/story/utils/captcha.py
ctfs/AzureAssassinAlliance/2023/web/story/utils/captcha.py
# coding: utf-8 import os import random import typing as t from PIL.Image import new as createImage, Image, QUAD, BILINEAR from PIL.ImageDraw import Draw, ImageDraw from PIL.ImageFilter import SMOOTH from PIL.ImageFont import FreeTypeFont, truetype from io import BytesIO import time ColorTuple = t.Union[t.Tuple[int, int, int], t.Tuple[int, int, int, int]] DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') DEFAULT_FONTS = [os.path.join(DATA_DIR, 'DroidSansMono.ttf')] class Captcha: lookup_table: t.List[int] = [int(i * 1.97) for i in range(256)] def __init__(self, width: int = 160, height: int = 60, key: int = None, length: int = 4, fonts: t.Optional[t.List[str]] = None, font_sizes: t.Optional[t.Tuple[int]] = None): self._width = width self._height = height self._length = length self._key = (key or int(time.time())) + random.randint(1,100) self._fonts = fonts or DEFAULT_FONTS self._font_sizes = font_sizes or (42, 50, 56) self._truefonts: t.List[FreeTypeFont] = [] random.seed(self._key) @property def truefonts(self) -> t.List[FreeTypeFont]: if self._truefonts: return self._truefonts self._truefonts = [ truetype(n, s) for n in self._fonts for s in self._font_sizes ] return self._truefonts @staticmethod def create_noise_curve(image: Image, color: ColorTuple) -> Image: w, h = image.size x1 = random.randint(0, int(w / 5)) x2 = random.randint(w - int(w / 5), w) y1 = random.randint(int(h / 5), h - int(h / 5)) y2 = random.randint(y1, h - int(h / 5)) points = [x1, y1, x2, y2] end = random.randint(160, 200) start = random.randint(0, 20) Draw(image).arc(points, start, end, fill=color) return image @staticmethod def create_noise_dots(image: Image, color: ColorTuple, width: int = 3, number: int = 30) -> Image: draw = Draw(image) w, h = image.size while number: x1 = random.randint(0, w) y1 = random.randint(0, h) draw.line(((x1, y1), (x1 - 1, y1 - 1)), fill=color, width=width) number -= 1 return image def _draw_character(self, c: str, draw: ImageDraw, color: ColorTuple) -> Image: font = random.choice(self.truefonts) left, top, right, bottom = draw.textbbox((0, 0), c, font=font) w = int((right - left)*1.7) or 1 h = int((bottom - top)*1.7) or 1 dx1 = random.randint(0, 4) dy1 = random.randint(0, 6) im = createImage('RGBA', (w + dx1, h + dy1)) Draw(im).text((dx1, dy1), c, font=font, fill=color) # rotate im = im.crop(im.getbbox()) im = im.rotate(random.uniform(-30, 30), BILINEAR, expand=True) # warp dx2 = w * random.uniform(0.1, 0.3) dy2 = h * random.uniform(0.2, 0.3) x1 = int(random.uniform(-dx2, dx2)) y1 = int(random.uniform(-dy2, dy2)) x2 = int(random.uniform(-dx2, dx2)) y2 = int(random.uniform(-dy2, dy2)) w2 = w + abs(x1) + abs(x2) h2 = h + abs(y1) + abs(y2) data = ( x1, y1, -x1, h2 - y2, w2 + x2, h2 + y2, w2 - x2, -y1, ) im = im.resize((w2, h2)) im = im.transform((w, h), QUAD, data) return im def create_captcha_image(self, chars: str, color: ColorTuple, background: ColorTuple) -> Image: image = createImage('RGB', (self._width, self._height), background) draw = Draw(image) images: t.List[Image] = [] for c in chars: if random.random() > 0.5: images.append(self._draw_character(" ", draw, color)) images.append(self._draw_character(c, draw, color)) text_width = sum([im.size[0] for im in images]) width = max(text_width, self._width) image = image.resize((width, self._height)) average = int(text_width / len(chars)) rand = int(0.25 * average) offset = int(average * 0.1) for im in images: w, h = im.size mask = im.convert('L').point(self.lookup_table) image.paste(im, (offset, int((self._height - h) / 2)), mask) offset = offset + w + random.randint(-rand, 0) if width > self._width: image = image.resize((self._width, self._height)) return image def generate_image(self, chars: str) -> Image: background = random_color(238, 255) color = random_color(10, 200, random.randint(220, 255)) im = self.create_captcha_image(chars, color, background) self.create_noise_dots(im, color) self.create_noise_curve(im, color) im = im.filter(SMOOTH) return im def generate(self, format: str = 'png') -> (BytesIO,str): code = generate_code(self._length) im = self.generate_image(code) out = BytesIO() im.save(out, format=format) out.seek(0) return out, code def write(self, output: str, format: str = 'png') -> (Image, str): code = generate_code(self._length) im = self.generate_image(code) im.save(output, format=format) return im, code def random_color(start: int, end: int, opacity: t.Optional[int] = None) -> ColorTuple: red = random.randint(start, end) green = random.randint(start, end) blue = random.randint(start, end) if opacity is None: return (red, green, blue) return (red, green, blue, opacity) def generate_code(length: int = 4): characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' return ''.join(random.choice(characters) for _ in range(length))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2023/web/story/utils/minic.py
ctfs/AzureAssassinAlliance/2023/web/story/utils/minic.py
import random rule = [ ['\\x','[',']','.','getitem','print','request','args','cookies','values','getattribute','config'], # rule 1 ['(',']','getitem','_','%','print','config','args','values','|','\'','\"','dict',',','join','.','set'], # rule 2 ['\'','\"','dict',',','config','join','\\x',')','[',']','attr','__','list','globals','.'], # rule 3 ['[',')','getitem','request','.','|','config','popen','dict','doc','\\x','_','\{\{','mro'], # rule 4 ['\\x','(',')','config','args','cookies','values','[',']','\{\{','.','request','|','attr'], # rule 5 ['print', 'class', 'import', 'eval', '__', 'request','args','cookies','values','|','\\x','getitem'] # rule 6 ] # Make waf more random def transfrom(number): a = random.randint(0,20) b = random.randint(0,100) return (a * number + b) % 6 def singel_waf(input, rules): input = input.lower() for rule in rules: if rule in input: return False return True def minic_waf(input): waf_seq = random.sample(range(21),3) for index in range(len(waf_seq)): waf_seq[index] = transfrom(waf_seq[index]) if not singel_waf(input, rule[waf_seq[index]]): return False return True
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/secure_connection/client.py
ctfs/AzureAssassinAlliance/2022/crypto/secure_connection/client.py
from socket import socket import socketserver import argparse from core import connection_engine, connection_handle_socket import socket def banner(): print(''' ___ ___ ___ _ _ _ __ ___ ___ ___ _ __ _ __ / __|/ _ \/ __| | | | '__/ _ \/ __/ _ \| '_ \| '_ \ \__ \ __/ (__| |_| | | | __/ (_| (_) | | | | | | | |___/\___|\___|\__,_|_| \___|\___\___/|_| |_|_| |_| CLIENT ''') if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-a", "--address", required=True, help="remote ip address") parser.add_argument( "-p", "--port", help="server running port", type=int, required=True) parser.add_argument("-d", "--dump", action="store_true", default=False, help="dump payload of packet") parser.add_argument("-e", "--encrypt", action="store_true", default=False, help="enable secure encrypted connection") args = parser.parse_args() HOST, PORT = args.address, args.port banner() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) handler = connection_handle_socket(s, "master", args.dump) connection_engine(handler, "master", args.encrypt)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/secure_connection/core.py
ctfs/AzureAssassinAlliance/2022/crypto/secure_connection/core.py
import base64 from dataclasses import dataclass from enum import Enum from Crypto.Cipher import AES import random from telnetlib import SE import libscrc def bytes_xor_16(bytes1, bytes2): v1 = int.from_bytes(bytes1, 'big') v2 = int.from_bytes(bytes2, 'big') v3 = v1 ^ v2 return (v3).to_bytes(16, 'big') def secure_encrypt(key, plain): aes = AES.new(key=key, mode=AES.MODE_ECB) return aes.encrypt(plain) def secure_encrypt_packet(key, plain, nonce): aes = AES.new(key=key, mode=AES.MODE_CCM, nonce=nonce) return aes.encrypt(plain) def secure_decrypt_packet(key, plain, nonce): aes = AES.new(key=key, mode=AES.MODE_CCM, nonce=nonce) return aes.decrypt(plain) def secure_confirm(key, r, p1, p2): return secure_encrypt(key, bytes_xor_16(secure_encrypt(key, bytes_xor_16(r, p1)), p2)) class PktOpcode(Enum): HELLO = 1 SC_REQ = 2 SC_RSP = 3 M_CONFIRM = 4 S_CONFIRM = 5 M_RANDOM = 6 S_RANDOM = 7 DATA = 8 class connection_handle: def __init__(self, type) -> None: self.type = type def send(self, data) -> None: pass def recv(self, length) -> bytes: return b"" def dump_packet(prefix: str, pkt: bytes, logfile: str): log_content = "" print(prefix + "\t", end="") log_content += prefix + "\t" for i in range(len(pkt)): d = pkt[i] print(hex(d)[2:].rjust(2, '0'), end="") log_content += hex(d)[2:].rjust(2, '0') if (i + 1) % 16 == 0 and i + 1 != len(pkt): print("\n\t", end="") log_content += "\n\t" else: print(" ", end="") log_content += " " print("") log_content += "\n" with open(logfile, "a") as f: f.write(log_content) class connection_handle_socket(connection_handle): def __init__(self, s, role, dump) -> None: super().__init__("socket") self.socket = s self.role = role self.dump = dump self.dumpfile = self.role + ".txt" def send(self, data) -> None: self.socket.send(data) if self.dump: dump_packet(">", data, self.dumpfile) def recv(self, length) -> bytes: data = self.socket.recv(length) if self.dump: dump_packet("<", data, self.dumpfile) return data class connection_handle_request(connection_handle): def __init__(self, request, role, dump) -> None: super().__init__("request") self.request = request self.role = role self.dump = dump self.dumpfile = self.role + ".txt" def send(self, data) -> None: self.request.sendall(data) if self.dump: dump_packet(">", data, self.dumpfile) def recv(self, length) -> bytes: data = self.request.recv(length) if self.dump: dump_packet("<", data, self.dumpfile) return data class connection_state: def __init__(self, role, encrypt) -> None: self.role = role self.local_counter = 0 self.remote_counter = 0 self.encrypt = encrypt self.initCRC = b"" def inc_local_counter(self): self.local_counter += 1 def inc_remote_counter(self): self.remote_counter += 1 def calc_crc(self, pdu): initvalue = int.from_bytes(self.initCRC, "little") crc = libscrc.hacker24(data=pdu, poly=0x00065B, init=initvalue, xorout=0x00000000, refin=True, refout=True) return crc.to_bytes(3, "little") def prepare_hello_packet(self): hello_packet = b"" hello_packet += int(self.encrypt << 7 | (PktOpcode.HELLO.value & 0x3f)).to_bytes(1, "little") hello_packet += int(3).to_bytes(1, "little") if not self.initCRC: self.initCRC = random.randbytes(3) hello_packet += self.initCRC hello_packet += self.calc_crc(hello_packet) # no encryption for hello return hello_packet def decrypt_data_packet(self, data): if self.encrypt: return secure_decrypt_packet( self.sessionkey, data, (self.remote_counter).to_bytes( 13, "little") ) else: return data def prepare_data_packet(self, data, moredata): data_packet = b"" data_packet += int(self.encrypt << 7 | moredata << 6 | (PktOpcode.DATA.value & 0x3f)).to_bytes(1, "little") data_packet += len(data).to_bytes(1, "little") if self.encrypt: data_packet += secure_encrypt_packet( self.sessionkey, data, (self.local_counter).to_bytes( 13, "little") ) else: data_packet += data data_packet += self.calc_crc(data_packet) return data_packet def prepare_sc_request_packet(self): sc_request_packet = b"" sc_request_packet += int(self.encrypt << 7 | (PktOpcode.SC_REQ.value & 0x3f)).to_bytes(1, "little") sc_request_packet += int(16).to_bytes(1, "little") IV = random.randbytes(8) Secret = random.randbytes(8) self.IVm = IV self.Secretm = Secret sc_request_packet += IV sc_request_packet += Secret sc_request_packet += self.calc_crc(sc_request_packet) return sc_request_packet def prepare_sc_respond_packet(self): sc_request_packet = b"" sc_request_packet += int(self.encrypt << 7 | (PktOpcode.SC_RSP.value & 0x3f)).to_bytes(1, "little") sc_request_packet += int(16).to_bytes(1, "little") IV = random.randbytes(8) Secret = random.randbytes(8) self.IVs = IV self.Secrets = Secret sc_request_packet += IV sc_request_packet += Secret sc_request_packet += self.calc_crc(sc_request_packet) return sc_request_packet def prepare_master_confirm_packet(self): master_confirm_packet = b"" master_confirm_packet += int(self.encrypt << 7 | (PktOpcode.M_CONFIRM.value & 0x3f)).to_bytes(1, "little") master_confirm_packet += int(16).to_bytes(1, "little") master_random = random.randbytes(16) master_confirm = secure_confirm( self.numeric_key_bytes, master_random, b"\x00" * 16, b"\xff" * 16) self.MRandom = master_random self.MConfirm = master_confirm master_confirm_packet += master_confirm master_confirm_packet += self.calc_crc(master_confirm_packet) return master_confirm_packet def prepare_slave_confirm_packet(self): slave_confirm_packet = b"" slave_confirm_packet += int(self.encrypt << 7 | (PktOpcode.S_CONFIRM.value & 0x3f)).to_bytes(1, "little") slave_confirm_packet += int(16).to_bytes(1, "little") slave_random = random.randbytes(16) slave_confirm = secure_confirm( self.numeric_key_bytes, slave_random, b"\x00" * 16, b"\xff" * 16) self.SRandom = slave_random self.SConfirm = slave_confirm slave_confirm_packet += slave_confirm slave_confirm_packet += self.calc_crc(slave_confirm_packet) return slave_confirm_packet def prepare_master_random_packet(self): master_random_packet = b"" master_random_packet += int(self.encrypt << 7 | (PktOpcode.M_RANDOM.value & 0x3f)).to_bytes(1, "little") master_random_packet += int(16).to_bytes(1, "little") master_random_packet += self.MRandom master_random_packet += self.calc_crc(master_random_packet) return master_random_packet def prepare_slave_random_packet(self): slave_random_packet = b"" slave_random_packet += int(self.encrypt << 7 | (PktOpcode.S_RANDOM.value & 0x3f)).to_bytes(1, "little") slave_random_packet += int(16).to_bytes(1, "little") slave_random_packet += self.SRandom slave_random_packet += self.calc_crc(slave_random_packet) return slave_random_packet def check_master_confirm(self, recvMrandom): should_Mconfirm = secure_confirm( self.numeric_key_bytes, recvMrandom, b"\x00" * 16, b"\xff" * 16) if should_Mconfirm == self.MConfirm: self.MRandom = recvMrandom return True else: return False def check_slave_confirm(self, recvSrandom): should_Sconfirm = secure_confirm( self.numeric_key_bytes, recvSrandom, b"\x00" * 16, b"\xff" * 16) if should_Sconfirm == self.SConfirm: self.SRandom = recvSrandom return True else: return False def setup_session(self): self.storekey = secure_encrypt( self.numeric_key_bytes, self.MRandom[:8] + self.SRandom[8:]) self.sessionkey = secure_encrypt( self.storekey, self.Secretm + self.Secrets) def showChoice(): print("================ CHOICE ================") print("[0] Receive a message") print("[1] Send a message") print("[2] Leave") print("-----------------======-----------------") def goodBye(): print("-----------------======-----------------") print("See you next time\n") def recieve_message(state: connection_state, handler: connection_handle): entire_data_payload = b"" while True: dataheader = handler.recv(2) more_data = (dataheader[0] >> 6) & 0b1 opcode = dataheader[0] & 0x3f if opcode != PktOpcode.DATA.value: print("Weird not data packet receieved") return datalength = dataheader[1] payload = handler.recv(datalength) crc = handler.recv(3) should_crc = state.calc_crc(dataheader + payload) payload = state.decrypt_data_packet(payload) state.inc_remote_counter() if crc != should_crc: print("CRC check failed in receive message") return entire_data_payload += payload if not more_data: break decoded_data = base64.b64decode(entire_data_payload).decode() print("Your recv : " + decoded_data) def send_message(state: connection_state, handler: connection_handle): data = input("Your data > ").strip().encode() encoded_data = base64.b64encode(data) # split into segements encoded_data_len = len(encoded_data) for start in range(0, encoded_data_len, 255): if start + 255 > encoded_data_len: end = encoded_data_len moreData = False else: end = start + 255 moreData = True data_segment = encoded_data[start: end] data_packet = state.prepare_data_packet(data_segment, moreData) handler.send(data_packet) state.inc_local_counter() def master_hello_procedure(handler: connection_handle, state: connection_state): handler.send(state.prepare_hello_packet()) state.inc_local_counter() hello_pkt = handler.recv(2 + 255 + 3) state.inc_remote_counter() if hello_pkt[0] & 0x3f != PktOpcode.HELLO.value: return False encrypt_or_not = (hello_pkt[0] >> 7) & 0b1 if not encrypt_or_not: return True handler.send(state.prepare_sc_request_packet()) state.inc_local_counter() numeric_key = int(input("Shared numeric key > ")) numeric_key = numeric_key % 0x1000000 state.numeric_key = numeric_key state.numeric_key_bytes = (numeric_key).to_bytes(16, "little") sc_respond_pkt = handler.recv(2 + 255 + 3) state.inc_remote_counter() if sc_respond_pkt[0] & 0x3f != int(PktOpcode.SC_RSP.value): return False recvIVs = sc_respond_pkt[2: 10] recvSecrets = sc_respond_pkt[10: 18] crc = sc_respond_pkt[18: 18 + 3] should_crc = state.calc_crc(sc_respond_pkt[:18]) if crc != should_crc: print("CRC check failed in hello procedure") return False state.IVs = recvIVs state.Secrets = recvSecrets handler.send(state.prepare_master_confirm_packet()) state.inc_local_counter() sconfirm_pkt = handler.recv(2 + 255 + 3) state.inc_remote_counter() if sconfirm_pkt[0] & 0x3f != int(PktOpcode.S_CONFIRM.value): return False recvSConfirm = sconfirm_pkt[2: 18] crc = sconfirm_pkt[18: 18 + 3] should_crc = state.calc_crc(sconfirm_pkt[:18]) if crc != should_crc: print("CRC check failed in hello procedure") return False state.SConfirm = recvSConfirm handler.send(state.prepare_master_random_packet()) state.inc_local_counter() srandom_pkt = handler.recv(2 + 255 + 3) state.inc_remote_counter() if srandom_pkt[0] & 0x3f != int(PktOpcode.S_RANDOM.value): return False recvSRandom = srandom_pkt[2: 18] crc = srandom_pkt[18: 18 + 3] should_crc = state.calc_crc(srandom_pkt[:18]) if crc != should_crc: print("CRC check failed in hello procedure") return False if not state.check_slave_confirm(recvSRandom): return False state.setup_session() return True def slave_hello_procedure(handler: connection_handle, state: connection_state): hello_pkt = handler.recv(2 + 255 + 3) state.inc_remote_counter() if hello_pkt[0] & 0x3f != int(PktOpcode.HELLO.value): return False encrypt_or_not = (hello_pkt[0] >> 7) & 0b1 state.encrypt = encrypt_or_not hello_pkt_len = hello_pkt[1] hello_pkt_payload = hello_pkt[2: 2 + hello_pkt_len] state.initCRC = hello_pkt_payload handler.send(state.prepare_hello_packet()) state.inc_local_counter() if not encrypt_or_not: return True else: sc_request_pkt = handler.recv(2 + 255 + 3) state.inc_remote_counter() if sc_request_pkt[0] & 0x3f != int(PktOpcode.SC_REQ.value): return False recvIVm = sc_request_pkt[2: 10] recvSecretm = sc_request_pkt[10: 18] crc = sc_request_pkt[18: 18 + 3] should_crc = state.calc_crc(sc_request_pkt[:18]) if crc != should_crc: print("CRC check failed in hello procedure") return False state.IVm = recvIVm state.Secretm = recvSecretm handler.send(state.prepare_sc_respond_packet()) state.inc_local_counter() numeric_key = int(input("Shared numeric key > ")) numeric_key = numeric_key % 0x1000000 state.numeric_key = numeric_key state.numeric_key_bytes = (numeric_key).to_bytes(16, "little") mconfirm_packet = handler.recv(2 + 255 + 3) state.inc_remote_counter() if mconfirm_packet[0] & 0x3f != int(PktOpcode.M_CONFIRM.value): return False recvMConfirm = mconfirm_packet[2: 18] crc = mconfirm_packet[18: 18 + 3] should_crc = state.calc_crc(mconfirm_packet[:18]) if crc != should_crc: print("CRC check failed in hello procedure") return False state.MConfirm = recvMConfirm handler.send(state.prepare_slave_confirm_packet()) state.inc_local_counter() mrandom_packet = handler.recv(2 + 255 + 3) state.inc_remote_counter() if mrandom_packet[0] & 0x3f != int(PktOpcode.M_RANDOM.value): return False recvMRandom = mrandom_packet[2: 18] crc = mrandom_packet[18: 18 + 3] should_crc = state.calc_crc(mrandom_packet[:18]) if crc != should_crc: print("CRC check failed in hello procedure") return False if not state.check_master_confirm(recvMRandom): return False handler.send(state.prepare_slave_random_packet()) state.inc_local_counter() state.setup_session() return True def connection_engine(handler: connection_handle, role: str, encrypt: bool): state = connection_state(role, encrypt) if role == "master": if not master_hello_procedure(handler, state): print("hello fail") exit(1) if role == "slave": if not slave_hello_procedure(handler, state): print("hello fail") exit(1) while True: try: showChoice() choice = int(input("Your choice > ")) if choice < 0 or choice > 2: raise ValueError if choice == 0: recieve_message(state, handler) elif choice == 1: send_message(state, handler) elif choice == 2: goodBye() return except ValueError as err: print("Bad Input T.T") continue except KeyboardInterrupt as err: goodBye() return # except Exception as err: # print("Bad thing happens") # print(err) # return
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/RSA_LEAK/task.py
ctfs/AzureAssassinAlliance/2022/crypto/RSA_LEAK/task.py
from sage.all import * from secret import flag from Crypto.Util.number import bytes_to_long def leak(a, b): p = random_prime(pow(2, 64)) q = random_prime(pow(2, 64)) n = p*q e = 65537 print(n) print((pow(a, e) + pow(b, e) + 0xdeadbeef) % n) def gen_key(): a = randrange(0, pow(2,256)) b = randrange(0, pow(2,256)) p = pow(a, 4) q = pow(b, 4) rp = randrange(0, pow(2,24)) rq = randrange(0, pow(2,24)) pp = next_prime(p+rp) qq = next_prime(q+rq) if pp % pow(2, 4) == (pp-p) % pow(2, 4) and qq % pow(2, 4) == (qq-q) % pow(2, 4): n = pp*qq rp = pp-p rq = qq-q return n, rp, rq n, rp, rq = gen_key() e = 65537 c = pow(bytes_to_long(flag), e, n) print("n =", n) print("e =", e) print("c =", c) print("=======leak=======") leak(rp, rq) ''' n = 3183573836769699313763043722513486503160533089470716348487649113450828830224151824106050562868640291712433283679799855890306945562430572137128269318944453041825476154913676849658599642113896525291798525533722805116041675462675732995881671359593602584751304602244415149859346875340361740775463623467503186824385780851920136368593725535779854726168687179051303851797111239451264183276544616736820298054063232641359775128753071340474714720534858295660426278356630743758247422916519687362426114443660989774519751234591819547129288719863041972824405872212208118093577184659446552017086531002340663509215501866212294702743 e = 65537 c = 48433948078708266558408900822131846839473472350405274958254566291017137879542806238459456400958349315245447486509633749276746053786868315163583443030289607980449076267295483248068122553237802668045588106193692102901936355277693449867608379899254200590252441986645643511838233803828204450622023993363140246583650322952060860867801081687288233255776380790653361695125971596448862744165007007840033270102756536056501059098523990991260352123691349393725158028931174218091973919457078350257978338294099849690514328273829474324145569140386584429042884336459789499705672633475010234403132893629856284982320249119974872840 =======leak======= 122146249659110799196678177080657779971 90846368443479079691227824315092288065 '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/casino/players.py
ctfs/AzureAssassinAlliance/2022/crypto/casino/players.py
from qunetsim.components import Host from qunetsim.objects import Qubit from qunetsim.objects import Logger from Crypto.Util.number import long_to_bytes from Crypto.Cipher import AES from casino import WIN_MSG, LOSE_MSG from secret import flag import sys import math import base64 import random import os # Logger.DISABLED = False AAA_ID = "aaa" GAMBLER_ID = "gambler" class CASINO_REFEREE(): def __init__(self): pass @staticmethod def get_position(): pos = [0,1,2] random.shuffle(pos) return pos[:2] @staticmethod def arbitrate(r1, r2, res1, res2): if (r1 == 0 and r2 == 2) or (r1 == 2 and r2 == 0): if res1 == res2: return -2 else: return 1 else: if res1 == res2: return 1 else: return -2 @staticmethod def encrypt(key, iv, msg): def padding(msg): msg = msg + bytes([16 - len(msg) % 16] * (16 - len(msg) % 16)) return msg aes = AES.new(key=key, iv=iv, mode=AES.MODE_CBC) cipher = aes.encrypt(padding(msg)) return base64.b64encode(cipher) @staticmethod def decrypt(key, cipher, id): def unpad(msg): return msg[:-msg[-1]] cipher = base64.b64decode(cipher) if len(cipher) % 16 != 0: return base64.b64encode(b"") if id != AAA_ID and len(cipher) > 16*2: return base64.b64encode(b"sorry, this function is restricted to AAA.") iv = cipher[:16] aes = AES.new(key=key, iv=iv, mode=AES.MODE_CBC) msg = unpad(aes.decrypt(cipher[16:])) return base64.b64encode(msg) class Player(object): def __init__(self): pass def get_input(self, prompt="> "): print(prompt, end="") sys.stdout.flush() return input() def get_next_classical_message(self, receiver_id, buffer, count): buffer.append(self.host.get_next_classical(receiver_id, wait=-1)) msg = b"ACK" while msg == b"ACK" or type(msg) != bytes or (msg != b"FIN" and (msg.split(b':')[0] != (b"%d" % count))): if len(buffer) == 0: buffer.append(self.host.get_next_classical(receiver_id, wait=-1)) ele = buffer.pop(0) msg = ele.content self.host.empty_classical() return msg def get_next_classical_message_slow(self, receiver_id, buffer, count): buffer = buffer + self.host.get_classical(receiver_id, wait=3) msg = b"ACK" while msg == b"ACK" or type(msg) != bytes or (msg != b"FIN" and (msg.split(b':')[0] != (b"%d" % count))): if len(buffer) == 0: buffer = buffer + self.host.get_classical(receiver_id, wait=3) ele = buffer.pop(0) msg = ele.content self.host.empty_classical() return msg def bits_to_bytes(self, bits, bytes_len): if type(bits) == list: bits = "".join([str(x) for x in bits]) return long_to_bytes(int(bits, 2)).rjust(bytes_len, b'\x00') class GAMBLER(Player): def __init__(self): self.host = Host(GAMBLER_ID) self.host.add_connection(AAA_ID) self.host.delay = 1 self.host.start() self.wait_time = 1 self.secret_key = None self.secret_iv = None def exchange_key(self, host, aaa_id, qubits_n): try: msg_buff = [] self.secret_key = self.get_next_classical_message(aaa_id, msg_buff, -1) self.secret_key = self.secret_key[3:] q_i = 0 q_iv = [] while q_i < qubits_n: qubit = self.host.get_data_qubit(aaa_id, wait=self.wait_time) basis = int(self.get_input("Please give me your basis: ")) self.host.send_classical(aaa_id, b"%d:%d" % (q_i, basis), await_ack=True) msg = self.get_next_classical_message(aaa_id, msg_buff, q_i) print("%s receives from %s: %s" % (host.host_id, aaa_id, msg.decode())) sys.stdout.flush() op, angle = map(int, self.get_input('How to rotate (op, angle): ').split(",")) self.rotate(qubit, op, angle) res = qubit.measure(non_destructive=True) print("Your qubit result: %d" % res) sys.stdout.flush() q_i += 1 del qubit q_iv = base64.b64decode(self.get_input("Please tell me the q_iv (base64): ")) self.secret_iv = q_iv except Exception as e: # print(e) # sys.stdout.flush() self.host.send_classical(aaa_id, b"FIN", await_ack=True) def rotate(self, qubit, op, angle=0): if op == 0: qubit.H() if op == 1: qubit.I() if op == 2: qubit.K() if op == 3: qubit.T() if op == 4: qubit.X() if op == 5: qubit.Y() if op == 6: qubit.Z() if op == 7: qubit.rx(angle / 180 * math.pi) if op == 8: qubit.ry(angle / 180 * math.pi) if op == 9: qubit.rz(angle / 180 * math.pi) def bet(self, host, aaa_id, bet_times): try: msg_buff = [] for round in range(bet_times): qubit = self.host.get_epr(aaa_id, wait=5) msg = self.get_next_classical_message_slow(aaa_id, msg_buff, round) print("%s receives from %s: %s" % (host.host_id, aaa_id, msg.decode())) sys.stdout.flush() msg = base64.b64decode(msg.split(b":")[1]) msg = CASINO_REFEREE.decrypt(self.secret_key, base64.b64encode(self.secret_iv + msg), aaa_id) msg = base64.b64decode(msg) random.seed(self.secret_key) for _ in range(round): random.getrandbits(128) rnd_msg = long_to_bytes(random.getrandbits(128)).rjust(16, b'\x00') assert msg[:16] == rnd_msg for _ in range(40): inp = self.get_input("What dou you want to decrypt: ") if inp == "exit": break dec_msg = CASINO_REFEREE.decrypt(self.secret_key, inp, self.host.host_id) print("Your decrypted msg: %s" % dec_msg.decode()) sys.stdout.flush() op, angle = map(int, self.get_input('How to rotate (op, angle): ').split(",")) if qubit == None: self.host.send_classical(aaa_id, b"FIN", await_ack=True) return self.rotate(qubit, op, angle) res = qubit.measure() send_msg = b"%d:%d" % (round, res) ack_arrived = self.host.send_classical(aaa_id, send_msg, await_ack=True) while not ack_arrived: ack_arrived = self.host.send_classical(aaa_id, send_msg, await_ack=True) msg = self.get_next_classical_message_slow(aaa_id, msg_buff, round+bet_times) money = int(msg.split(b":")[1]) print("%s's current money is: %d" % (self.host.host_id, money)) sys.stdout.flush() del qubit self.host.reset_data_qubits(host_id=GAMBLER_ID) except Exception as e: # print(e) # sys.stdout.flush() self.host.send_classical(aaa_id, b"FIN", await_ack=True) class AAA(Player): def __init__(self): self.host = Host(AAA_ID) self.host.add_connection(GAMBLER_ID) self.host.delay = 1 self.host.start() self.wait_time = 1 self.secret_key = None self.secret_iv = None def exchange_key(self, host, gambler_id, qubits_n): try: self.secret_key = os.urandom(16) self.secret_iv = os.urandom(16) host.send_classical(gambler_id, b"%d:%s" %(-1, self.secret_key), await_ack=True) msg_buff = [] q_iv = [] self.qubits = [Qubit(self.host, q_id=id) for id in range(qubits_n)] self.basis = [random.randint(0,1) for _ in range(qubits_n)] self.keybits = [random.randint(0,1) for _ in range(qubits_n)] for q_i, qubit in enumerate(self.qubits): if self.keybits[q_i] == 1: qubit.X() self.host.send_qubit(gambler_id, qubit, await_ack=True) message = self.get_next_classical_message(gambler_id, msg_buff, q_i) if message == b"FIN": return if message == b"%d:%d" % (q_i, self.basis[q_i]): if self.basis[q_i] == 1: qubit.H() res = qubit.measure(non_destructive=True) qubit.H() else: res = qubit.measure(non_destructive=True) q_iv.append(res) msg = b"%d:0" % q_i else: msg = b"%d:1" % q_i self.host.send_classical(gambler_id, msg, await_ack=True) del qubit q_iv = self.bits_to_bytes(q_iv[:128], 16) self.secret_iv = q_iv self.host.reset_data_qubits(host_id=AAA_ID) except Exception as e: pass def bet(self, host, gambler_id, bet_times): def ry0(qubit): qubit.ry(1/3 * math.pi) def ry1(qubit): pass def ry2(qubit): qubit.ry(-1/3 * math.pi) rotate_ops = [ry0, ry1, ry2] msg_buff = [] gambler_money = 0 for round in range(bet_times): random.seed(self.secret_key) for _ in range(round): random.getrandbits(128) rnd_msg = long_to_bytes(random.getrandbits(128)).rjust(16, b'\x00') _, ack_arrived = self.host.send_epr(gambler_id, await_ack=True) while not ack_arrived: _, ack_arrived = self.host.send_epr(gambler_id, await_ack=True) qubit = self.host.get_epr(gambler_id, wait=1) r1, r2 = CASINO_REFEREE.get_position() rotate_ops[r1](qubit) res1 = qubit.measure() cipher = CASINO_REFEREE.encrypt(self.secret_key, self.secret_iv, b"%s+%d" % (rnd_msg, r2)) send_msg = b"%d:%s" % (round, cipher) ack_arrived = self.host.send_classical(gambler_id, send_msg, await_ack=True) while not ack_arrived: ack_arrived = self.host.send_classical(gambler_id, send_msg, await_ack=True) msg = self.get_next_classical_message_slow(gambler_id, msg_buff, round) if msg == b'FIN': return res2 = int(msg[-1:]) gambler_money += CASINO_REFEREE.arbitrate(r1,r2,res1,res2) send_msg = b"%d:%d" % (round+bet_times, gambler_money) ack_arrived = self.host.send_classical(gambler_id, send_msg, await_ack=True) while not ack_arrived: ack_arrived = self.host.send_classical(gambler_id, send_msg, await_ack=True) del qubit if gambler_money >= bet_times // 2: print(WIN_MSG + flag) else: print(LOSE_MSG) sys.stdout.flush()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/casino/main.py
ctfs/AzureAssassinAlliance/2022/crypto/casino/main.py
#!/usr/bin/env python3 import sys import signal import random, string, hashlib def proof_of_work(): proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)]) digest = hashlib.sha256(proof.encode()).hexdigest() print("sha256(XXXX+%s) == %s" % (proof[4:], digest)) x = input("Give me XXXX: ") if len(x)!=4 or hashlib.sha256((x+proof[4:]).encode()).hexdigest() != digest: print("Sorry~ bye~") return False print("Right!") return True def main(): from backend import bet_in_casino, exchange_key from players import AAA, GAMBLER from casino import CASINO_DESCRIPTION print(CASINO_DESCRIPTION) sys.stdout.flush() signal.alarm(300) aaa = AAA() gambler = GAMBLER() network = exchange_key(aaa, gambler, 128) if aaa.secret_iv != gambler.secret_iv: print("byebye~~") network.stop(True) return print("good job!") network = bet_in_casino(network, aaa, gambler, 256) network.stop(True) if __name__ == "__main__": if proof_of_work(): main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/casino/casino.py
ctfs/AzureAssassinAlliance/2022/crypto/casino/casino.py
CASINO_DESCRIPTION = \ "==========================================================================\n" \ "| Hey gambler! Welcome to AAA casino, here you are going to bet with me.\n" \ "| Hope you can win a lot of money.\n" \ "| If you are outstanding enough, I will give you flag.\n" \ "==========================================================================\n" \ WIN_MSG = \ "Your gambling skills have been declared to be outstanding, here is the flag: " LOSE_MSG = \ "Go ahead, you can be better."
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/casino/secret.py
ctfs/AzureAssassinAlliance/2022/crypto/casino/secret.py
flag = 'ACTF{this_is_a_local_flag-please_connect_to_the_remote_server_to_get_true_flag}'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/casino/backend.py
ctfs/AzureAssassinAlliance/2022/crypto/casino/backend.py
from qunetsim import Network def exchange_key(aaa, tbd, qubits_n): network = Network.get_instance() nodes = [aaa.host.host_id, tbd.host.host_id] network.start(nodes) network.delay = 0.0 network.add_host(aaa.host) network.add_host(tbd.host) t1 = aaa.host.run_protocol(aaa.exchange_key, (tbd.host.host_id, qubits_n*2)) t2 = tbd.host.run_protocol(tbd.exchange_key, (aaa.host.host_id, qubits_n*2)) t1.join() t2.join() return network def bet_in_casino(network, aaa, tbd, bet_times): t1 = aaa.host.run_protocol(aaa.bet, (tbd.host.host_id, bet_times)) t2 = tbd.host.run_protocol(tbd.bet, (aaa.host.host_id, bet_times)) t1.join() t2.join() return network
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/blockchain_service.py
ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/blockchain_service.py
""" A "solo" consensus ledger endorsed during bookkeeping """ from json import loads, dumps from secret import flag, alice_pub, bob_priv, bob_pub, carol_priv, carol_pub from abc import abstractmethod from ring_signature import serialize2json, deserialize4json, transaction_curve, OTRS, H as Hv, prng, Hp E, G = transaction_curve() otrs = OTRS(E, G) class MessagePusher(object): @abstractmethod def push(self, message): pass class TerminalMessagePusher(MessagePusher): def push(self, message): print(message) class RPCListener(object): @abstractmethod def on_new_request(self, listener): pass @abstractmethod def listen(self): pass class TerminalRPCListener(RPCListener): def __init__(self): super().__init__() self.listeners = [] self.reply_hook = None def on_new_request(self, listener): self.listeners.append(listener) def do_reply(self, message): if self.reply_hook is not None: self.reply_hook(message) return print(message) def handle_rpc_request(self, json): for listener in self.listeners: listener(json, lambda reply: self.do_reply(reply)) def listen(self): try: while True: json = '' while True: json += input('req> ') json = json.strip() if json.endswith('\\'): json = json[:-1] else: break self.handle_rpc_request(json) except KeyboardInterrupt: print("") exit() class BCTransaction(object): def __init__(self, txi, sig, txo): self.txi = txi self.sig = sig self.txo = txo self.coinbase = False def serialize(self): assert not self.coinbase return serialize2json(self.txi, self.sig, self.txo) @staticmethod def deserialize(json): txi, sig, txo = deserialize4json(E, json) # type coerce txi = [int(txo_id) for txo_id in txi] I, c_0, r = sig c_0 = int(c_0) r = [int(r_i) for r_i in r] I = E(int(I.xy()[0]), int(I.xy()[1])) sig = (I, c_0, r) txo = E(int(txo.xy()[0]), int(txo.xy()[1])) return BCTransaction(txi, sig, txo) @staticmethod def generate(txi, txo, priv, state_json, ring_size=3): pk_owned, txos, key_images = deserialize4json(E, state_json) pub = priv * G assert pub in pk_owned and txi in pk_owned[pub] assert txos[txi] == pub txis = [txi] + prng.sample(list(range(txi)) + list(range(txi + 1, len(txos))), min(ring_size, len(txos))-1) prng.shuffle(txis) Ks = [txos[txo_id] for txo_id in txis] sig = otrs.signature(Ks, Hv(txis, txo), priv, txis, txi) return BCTransaction(txis, sig, txo) class BCBlock(list): pass class BCState(object): def __init__(self): self.txo = [] self.key_images = set() self.pk_owned = dict() def verify_transaction(self, transaction:BCTransaction): if transaction.coinbase: return Ks = [self.txo[txo_id] for txo_id in transaction.txi] assert otrs.verify(Ks, Hv(transaction.txi, transaction.txo), transaction.sig, transaction.txi) I, _, _ = transaction.sig assert I not in self.key_images def apply_transaction(self, transaction:BCTransaction): try: self.verify_transaction(transaction) if not transaction.coinbase: I, _, _ = transaction.sig self.key_images.add(I) if transaction.txo not in self.pk_owned: self.pk_owned[transaction.txo] = [] self.pk_owned[transaction.txo].append(len(self.txo)) self.txo.append(transaction.txo) except Exception: pass class BCLedger(object): def __init__(self, state:BCState = None, transactions:list = None) -> None: self.state = state if state is not None else BCState() self.transactions = transactions if transactions is not None else [] self.listeners = [] def __append_transaction(self, transaction:BCTransaction): self.transactions.append(transaction) self.state.apply_transaction(transaction) def append_block(self, block:BCBlock): for transaction in block: self.__append_transaction(transaction) for listener in self.listeners: listener(self.state) class BCOrderService(object): @abstractmethod def insert_transaction(self, transaction:BCTransaction): pass @abstractmethod def mine_to(self, pub_key): # Theoretically, this process does not return until a token is mined. pass @abstractmethod def on_new_block(self, listener): pass class BCSoloOrderService(BCOrderService): def __init__(self): super().__init__() self.listeners = [] def insert_transaction(self, transaction:BCTransaction, mined:bool=False): # "solo" consensus :) if transaction.coinbase and not mined: # coinbase can only be generate by order service it self return new_block = BCBlock() new_block.append(transaction) for listener in self.listeners: listener(new_block) def mine_to(self, pub_key): transaction = BCTransaction(None, None, pub_key) transaction.coinbase = True self.insert_transaction(transaction, True) def on_new_block(self, listener): self.listeners.append(listener) class BCPeerService(BCLedger): def __init__(self, order:BCOrderService, state:BCState = None, transactions:list = None): super().__init__(state, transactions) self.order = order self.order.on_new_block(lambda block:self.append_block(block)) self.can_show_state = True def on_state_change(self, listener): self.listeners.append(listener) def get_state(self): if self.can_show_state: return serialize2json(self.state.pk_owned, self.state.txo, self.state.key_images) else: return "No permission" def disable_get_state(self): self.can_show_state = False class BCClientService(object): def process_rpc(self, json, replier): try: rpc = loads(json) if rpc["type"] == "new_transaction": self.order.insert_transaction(BCTransaction.deserialize(rpc["transaction"])) replier("Submitted") elif rpc["type"] == "show_state": replier(self.peer.get_state()) elif rpc["type"] == "disable_show_state": self.peer.disable_get_state() replier("Ok") else: replier("Unsupport request") except Exception: replier("Error during process your request") def __init__(self, rpc:RPCListener, order:BCOrderService, peer:BCPeerService): self.rpc = rpc self.order = order self.peer = peer rpc.on_new_request(lambda json, replier:self.process_rpc(json, replier)) class FlagService(object): def strictly_count(self, state:BCState, pub, priv): assert priv * G == pub cnt = 0 for i in state.pk_owned[pub]: I = priv * Hp(E, G, pub, i) if I not in state.key_images: cnt += 1 return cnt def check_state(self, state:BCState): if E(bob_pub) not in state.pk_owned or E(carol_pub) not in state.pk_owned: return if len(state.pk_owned[E(bob_pub)]) < 2 or len(state.pk_owned[E(carol_pub)]) < 2: return if self.strictly_count(state, E(bob_pub), bob_priv) < 1 or self.strictly_count(state, E(carol_pub), carol_priv) < 1: self.pusher.push("Your solution must be very interesting, do record it, but there are no flag here.") else: self.pusher.push("Here is your flag: %s" % flag) exit() # all things will be killed if the flag is pushed def __init__(self, peer:BCPeerService, pusher:MessagePusher): self.pusher = pusher self.peer = peer self.peer.on_state_change(lambda state:self.check_state(state)) if __name__ == '__main__': # Start a "blockchain network" :) pusher_1 = TerminalMessagePusher() rpc_1 = TerminalRPCListener() order_1 = BCSoloOrderService() peer_1 = BCPeerService(order_1) client_1 = BCClientService(rpc_1, order_1, peer_1) flag_1 = FlagService(peer_1, pusher_1) # At first, the miner carol get her token. order_1.mine_to(E(carol_pub)) # Then, Alice borrowed 1 token from Carol through Bob. def submit_to_rpc_1(type_str, transaction=None): req = dict() req['type'] = type_str if transaction is not None: req['transaction'] = transaction json = dumps(req) respond = None def hook_impl(message): nonlocal respond respond = message rpc_1.reply_hook = hook_impl rpc_1.handle_rpc_request(json) rpc_1.reply_hook = None return respond def transfer_to(txo_id, priv, pub): # transfer txo_id, priv to pub transaction = BCTransaction.generate(txo_id, pub, priv, submit_to_rpc_1("show_state")) return submit_to_rpc_1("new_transaction", transaction.serialize()) # So, Carol --1 token--> Bob transfer_to(0, carol_priv, E(bob_pub)) # and Bob --1 token--> Alice transfer_to(1, bob_priv, E(alice_pub)) # Don't let you see the state. submit_to_rpc_1("disable_show_state") # Now, it's your turn. :) rpc_1.listen()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/signed_message_verifier.py
ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/signed_message_verifier.py
from gmssl import sm2, sm3, func # gmssl==3.2.1 from binascii import a2b_hex from json import load from secret import bob_pub class SM2(sm2.CryptSM2): def __init__(self, private_key, public_key): ecc_table = { 'n': '1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED', 'p': '7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED', 'g': '2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD245A'\ '20AE19A1B8A086B4E01EDD2C7748D14C923D4D7E6D7C61B229E9C5A27ECED3D9', 'a': '2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA984914A144', 'b': '7B425ED097B425ED097B425ED097B425ED097B425ED097B4260B5E9C7710C864', } super().__init__(private_key, public_key, ecc_table) def _sm3_z(self, data): z = '0080'+'31323334353637383132333435363738' + \ self.ecc_table['a'] + self.ecc_table['b'] + self.ecc_table['g'] z = a2b_hex(z) Za = sm3.sm3_hash(func.bytes_to_list(z)) M_ = (Za + data.hex()).encode() e = sm3.sm3_hash(func.bytes_to_list(a2b_hex(M_))) return e def sign_with_sm3(self, data, random_hex_str=None): sign_data = a2b_hex(self._sm3_z(data).encode()) if random_hex_str is None: random_hex_str = func.random_hex(self.para_len) sign = self.sign(sign_data, random_hex_str) return sign def verify_with_sm3(self, sign, data): sign_data = a2b_hex(self._sm3_z(data).encode()) return self.verify(sign, sign_data) def get_bob_sign_pub(): x, y = bob_pub p = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED delta = 0X2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2451 x, y = (x + delta) % p, y return hex(x)[2:].zfill(64)+hex(y)[2:].zfill(64) if __name__ == '__main__': text, sign = load(open('signed_message_from_bob.json')) verifier = SM2(public_key=get_bob_sign_pub(), private_key=None) print('verified' if verifier.verify_with_sm3(sign, text.encode()) else 'tampered')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/ring_signature.py
ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/ring_signature.py
from sage.all import * from Crypto.Hash import keccak from Crypto.Util.number import long_to_bytes, bytes_to_long from struct import unpack from random import SystemRandom from json import loads, dumps prng = SystemRandom() def n2s(n): buf = long_to_bytes(n) return len(buf).to_bytes(8, 'big') + buf def s2n(s): length = int.from_bytes(s[:8], 'big') return bytes_to_long(s[8:8+length]), s[8+length] def serialize2bytes(*args) -> bytes: result = b'' for arg in args: if isinstance(arg, bytes): result += arg elif isinstance(arg, int): result += n2s(arg) elif arg is None: pass elif isinstance(arg, list): result += n2s(len(arg)) result += serialize2bytes(*arg) else: result += n2s(int(arg.xy()[0])) + n2s(int(arg.xy()[1])) return result def H(*args): k = keccak.new(digest_bits=256) k.update(serialize2bytes(*args)) return k.digest() def Hn(n, *args): value = int.from_bytes(H(b'H_n', *args), 'big') return value % (n - 1) + 1 def Hp(E, G, *args): value = int.from_bytes(H(b'H_p', *args), 'big') q = E.base_field().order() x = value % (q - 1) + 1 jump, iter = unpack('<QI', H(b'H_p_additional', *args)[:12]) while True: pts = E.lift_x(x, all=True) if len(pts) > 0: candidate = pts[iter % len(pts)] if G.order() * candidate == E(0): return candidate x = (x - 1 + jump) % (q - 1) + 1 class OTRS(object): def __init__(self, E, G): self.E = E self.G = G self.n = G.order() self.q = E.base_field().order() def signature(self, Ks:list, m:bytes, k:int, bind_message=None, your_bind=None): K = k * self.G assert K in Ks n = len(Ks) assert bind_message is None or your_bind is not None if bind_message is None: pi = Ks.index(K) else: pi = list(zip(Ks, bind_message)).index((K, your_bind)) I = k * Hp(self.E, self.G, K, None if bind_message is None else bind_message[pi]) alpha = prng.randint(1, self.n - 1) Li = alpha * self.G Ri = alpha * Hp(self.E, self.G, K, None if bind_message is None else bind_message[pi]) c_next = Hn(self.n, m, Li, Ri) r = [prng.randint(1, self.n - 1) for _ in range(n)] c_0 = None for i in list(range(pi + 1, n)) + list(range(0, pi)): if i == 0: c_0 = c_next Li = r[i] * self.G + c_next * Ks[i] Ri = r[i] * Hp(self.E, self.G, Ks[i], None if bind_message is None else bind_message[i]) + c_next * I c_next = Hn(self.n, m, Li, Ri) if c_0 is None: assert pi == 0 c_0 = c_next r[pi] = alpha - c_next * k return (I, c_0, r) def verify(self, Ks:list, m:bytes, signature:tuple, bind_message=None): if len(Ks) == 0: return False I, c_0, r = signature c_next = c_0 n = len(Ks) for i in range(n): Li = r[i] * self.G + c_next * Ks[i] Ri = r[i] * Hp(self.E, self.G, Ks[i], None if bind_message is None else bind_message[i]) + c_next * I c_next = Hn(self.n, m, Li, Ri) return c_next == c_0 class RangeProof(object): def __init__(self, otrs: OTRS, H=None): self.otrs = otrs self.E = otrs.E self.G = otrs.G self.n = otrs.n self.q = otrs.q if H is None: H = Hp(self.E, self.G, prng.randint(self.n * self.q)) self.H = H def generate_commitment(self, x: int, r=None): if r is None: r = prng.randint(1, self.n - 1) C = r * self.G + x * self.H return (x, r, C) def verify_commitment(self, Ct: tuple): x, r, C = Ct return r * self.G + x * self.H == C def prove(self, Ct: tuple, n: int): assert n > 0 assert self.verify_commitment(Ct) x, r, C = Ct hash_C = H(C) assert x < 2**n b = [ord(c) - 48 for c in bin(x)[2:].zfill(n)[::-1]] Cs = [self.generate_commitment(b[i] * 2**i) for i in range(n - 1)] last_r = (r - sum(r for x, r, C in Cs) % self.n + self.n) % self.n Cs.append(self.generate_commitment(b[n - 1] * 2**(n - 1), last_r)) sigs = [self.otrs.signature([C, C - 2**i * self.H], hash_C, r) for i, (x, r, C) in enumerate(Cs)] Cs = [C for x, r, C in Cs] C_sum = Cs[0] for i in range(1, n): C_sum += Cs[i] assert C_sum == C return (Cs, sigs) def verify(self, C, n: int, proof:tuple): Cs, sigs = proof if not(len(Cs) == n == len(sigs)): return False C_sum = Cs[0] for i in range(1, n): C_sum += Cs[i] if C_sum != C: return False hash_C = H(C) return all([self.otrs.verify([C, C - 2**i * self.H], hash_C, sig) for i, (C, sig) in enumerate(zip(Cs, sigs))]) def serialize2json(*args): def s2d(v): if isinstance(v, tuple): return {"type": "tuple", "value": [s2d(i) for i in v]} elif isinstance(v, list): return {"type": "list", "value": [s2d(i) for i in v]} elif isinstance(v, set): return {"type": "set", "value": [s2d(i) for i in list(v)]} elif isinstance(v, int): return {"type": "int", "value": str(v)} elif isinstance(v, Integer): return {"type": "integer", "value": str(v)} elif isinstance(v, bytes): return {"type": "bytes", "value": v.hex()} elif isinstance(v, str): return {"type": "str", "value": v} elif isinstance(v, dict): return {"type": "dict", "value": [[s2d(key), s2d(value)] for key, value in v.items()]} else: return {"type": "point", "value": [str(v.xy()[0]), str(v.xy()[1])]} return dumps(s2d(args)) def deserialize4json(E, json): def d4d(v: dict): type_str = v['type'] value = v['value'] if type_str == "tuple": return (d4d(i) for i in value) elif type_str == "list": return [d4d(i) for i in value] elif type_str == "set": return set([d4d(i) for i in value]) elif type_str == "int": return int(value) elif type_str == "integer": return Integer(int(value)) elif type_str == "bytes": return bytes.fromhex(value) elif type_str == "dict": ret = dict() for [k, v] in value: ret[d4d(k)] = d4d(v) return ret elif type_str == "point": return E(int(value[0]), int(value[1])) return d4d(loads(json)) def curve_gen(q, a, gx, gy, n): Fq = GF(q) E = EllipticCurve(Fq, a) G = E(gx, gy) G.set_order(n) return (E, G) def proof_curve(): return curve_gen(16883071526461729727845365244775250968853779238387590508529343289688406548156898561121755709582605065974415626338418885206169694955938439285172466321629894047112152673890080193271092158984773170409123807574649665886686958584517, [16883071526461729727845365244775250968853779238387590508529343289688406548156898561121755709582605065974415626338418885206169694955938439285172466321629894047112152673890080193271092158984773170409123807574649665886686958584513, 50649214579385189183536095734325752906561337715162771525588029869065219644470695683365267128747815197923246879015256655618509084867815317855517398964889682141336458021670240579813276476954319511227371422723948997660060875753551], 14210586178493131406373190825820561003702506574011169828934446821536638945014471344113633023777761432403862087346540040982532990086531969109648355583610945828488439781287611999333627004372849450097379152416521048148055212429932, 7940930756869397961969852165330305368117788150170640034809962841577789648806280962338902036326685993547448607633972933475226268575544844316990777006161391199019112160116189041944360780606412770726712110640687030917392143404191, 129934874173417083152641070462750529831810853051271596159072328195848188613591686285280068379888878197177498309746) def proof_H(E): return E(558502762260882368459100959026702189372961874916046935897584379942575091607773755509785872627683092849646763384923491591737048593593911906848644811657443277980186172014888060411213151459022266424905365693967579209745952778762, 5244497032739641374363689610162896907859634278068877212817118029249551959220656759501163866935794467197122778877280355210299933485519765003782178469195042075397340131431018419860106520716072042537547362606695008442528534605810) def transaction_curve(): return curve_gen(57896044618658097711785492504343953926634992332820282019728792003956564819949, [0, 486662, 0, 1, 0], 9, 14781619447589544791020593568409986887264606134616475288964881837755586237401, 7237005577332262213973186563042994240857116359379907606001950938285454250989)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/secret.py
ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/secret.py
# This is a sample file for secret.py. alice_priv = 0xa42d6d662afa3114ccf2678f766048faca568bb804de9e0ba17ee18e6af7565 alice_pub = (0x53f9f8c1226769b84fcf8564c2521f87849f8b993ee8fc9784f3a900d896a730, 0x489b81283080f4db6db6c1635a839b89a5eefe8442fd2bced94c39c8cb6470b5) # Every secret number in the real secret.py is replaced with 0xAAA...A. # Every secret string in the real secret.py is replaced with "ACTF{test_flag}". bob_priv = 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA bob_pub = (0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) carol_priv = 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA carol_pub = (0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) flag = "ACTF{test_flag}"
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/range_proof_verifier.py
ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/range_proof_verifier.py
from ring_signature import proof_curve, RangeProof, OTRS, deserialize4json, proof_H E, G = proof_curve() H = proof_H(E) rp = RangeProof(OTRS(E, G), H) with open("range_proof_from_carol.json", "r") as f: json = f.read() C, proof = deserialize4json(E, json) print("verfied" if rp.verify(C, 256, proof) else "FAKE PROOF!") # Note: C is a Pedersen commitment for the x-coordinate of Carol's Public key. # It generated by `rp.generate_commitment(__import__('secret').carol_pub[0])`.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/hint1/carol_range_proof_generate.py
ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/hint1/carol_range_proof_generate.py
from ring_signature import proof_curve, RangeProof, OTRS, serialize2json, proof_H E, G = proof_curve() H = proof_H(E) rp = RangeProof(OTRS(E, G), H) Ct = rp.generate_commitment(__import__('secret').carol_pub[0]) x, r, C = Ct proof = rp.prove(Ct, 256) assert rp.verify(C, 256, proof) with open("range_proof_from_carol.json", "w") as f: f.write(serialize2json(C, proof))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/hint1/bob_signed_generate.py
ctfs/AzureAssassinAlliance/2022/crypto/crypto_note/hint1/bob_signed_generate.py
from json import dump from signed_message_verifier import SM2, get_bob_sign_pub from secret import bob_priv text = 'Bob: Do you remember the 1 token I lent you? Pay off that loan, now!' signer = SM2(public_key=get_bob_sign_pub(), private_key=hex(bob_priv)[2:].zfill(64)) sign = signer.sign_with_sm3(text.encode()) dump([text, sign], open('signed_message_from_bob.json', 'w'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/crypto/impossible_RSA/server.py
ctfs/AzureAssassinAlliance/2022/crypto/impossible_RSA/server.py
from Crypto.Util.number import * from Crypto.PublicKey import RSA e = 65537 flag = b'ACTF{...}' while True: p = getPrime(1024) q = inverse(e, p) if not isPrime(q): continue n = p * q; public = RSA.construct((n, e)) with open("public.pem", "wb") as file: file.write(public.exportKey('PEM')) with open("flag", "wb") as file: file.write(long_to_bytes(pow(bytes_to_long(flag), e, n))) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AzureAssassinAlliance/2022/web/ToLeSion/src/app.py
ctfs/AzureAssassinAlliance/2022/web/ToLeSion/src/app.py
#!/usr/bin/env python # -*- coding:utf-8 - from flask import Flask, request, redirect from flask_session import Session from io import BytesIO import memcache import pycurl import random import string app = Flask(__name__) app.debug = True app.secret_key = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(56)) app.config['SESSION_TYPE'] = 'memcached' app.config['SESSION_PERMANENT'] = True app.config['SESSION_USE_SIGNER'] = False app.config['SESSION_KEY_PREFIX'] = 'actfSession:' app.config['SESSION_MEMCACHED'] = memcache.Client(['127.0.0.1:11200']) Session(app) @app.route('/') def index(): buffer=BytesIO() if request.args.get('url'): url = request.args.get('url') c = pycurl.Curl() c.setopt(c.URL, url) c.setopt(c.FTP_SKIP_PASV_IP, 0) c.setopt(c.WRITEDATA, buffer) blacklist = [c.PROTO_DICT, c.PROTO_FILE, c.PROTO_FTP, c.PROTO_GOPHER, c.PROTO_HTTPS, c.PROTO_IMAP, c.PROTO_IMAPS, c.PROTO_LDAP, c.PROTO_LDAPS, c.PROTO_POP3, c.PROTO_POP3S, c.PROTO_RTMP, c.PROTO_RTSP, c.PROTO_SCP, c.PROTO_SFTP, c.PROTO_SMB, c.PROTO_SMBS, c.PROTO_SMTP, c.PROTO_SMTPS, c.PROTO_TELNET, c.PROTO_TFTP] allowProtos = c.PROTO_ALL for proto in blacklist: allowProtos = allowProtos&~(proto) c.setopt(c.PROTOCOLS, allowProtos) c.perform() c.close() return buffer.getvalue().decode('utf-8') else: return redirect('?url=http://www.baidu.com',code=301) if __name__ == '__main__': app.run(host='0.0.0.0', debug=False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/rev/hopper/hopper.py
ctfs/WRECKCTF/2022/rev/hopper/hopper.py
#!/usr/local/bin/python import os def do_hop(state): hopper = state['hopper'] line = state['line'] hops = [ (hopper - 4, hopper >= 4), (hopper - 1, hopper % 4 != 0), (hopper + 1, hopper % 4 != 3), (hopper + 4, hopper < 12), ] hoppees = { line[hop]: hop for hop, legal in hops if legal } people = ', '.join(hoppees) print('oh no! the order of the line is wrong!') print(f'you can hop with {people}.') hoppee = input('who do you choose? ') if hoppee not in hoppees: print('can\'t hop there!') return target = hoppees[hoppee] line[hopper], line[target] = line[target], line[hopper] state['hopper'] = target def fixed(state): position = { hoppee: i for i, hoppee in enumerate(state['line']) } if position['olive'] > position['olen']: return False if position['shauna'] > position['constance']: return False if position['zane'] > position['tracie']: return False if position['loretta'] > position['chasity']: return False if position['gracie'] > position['shauna']: return False if position['tracie'] > position['louie']: return False if position['bertram'] > position['antoinette']: return False if position['antoinette'] > position['dana']: return False if position['constance'] > position['bertram']: return False if position['louie'] > position['wes']: return False if position['olen'] > position['hopper']: return False if position['wes'] > position['loretta']: return False if position['chasity'] > position['olive']: return False if position['rosemarie'] > position['gracie']: return False if position['dana'] > position['zane']: return False return True state = { 'hopper': 0, 'line': [ 'hopper', 'wes', 'gracie', 'zane', 'constance', 'rosemarie', 'shauna', 'chasity', 'louie', 'tracie', 'dana', 'olen', 'olive', 'loretta', 'bertram', 'antoinette', ], } while not fixed(state): do_hop(state) print(os.environ.get('FLAG', 'no flag provided!'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/rev/reverser/program.py
ctfs/WRECKCTF/2022/rev/reverser/program.py
#!/usr/local/bin/python import os def check_license(license): characters = set('0123456789abcdef') s = [9] for c in license: if c not in characters: return False s.append((s[-1] + int(c, 16)) % 16) target = '51c49a1a00647b037f5f3d5c878eb656' return ''.join(f'{c:x}' for c in s[1:]) == target print('welcome to reverser as a service!') license = input('please enter your license key: ') if not check_license(license): print('sorry, incorrect key!') exit() string = input('what should i reverse? ') print(f'output: {string[::-1]}') print(os.environ.get('FLAG', 'no flag given'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/crypto/baby-rsa/challenge.py
ctfs/WRECKCTF/2022/crypto/baby-rsa/challenge.py
import os from Crypto.Util.number import bytes_to_long from Crypto.Util.number import getPrime flag = os.environ.get('FLAG', 'no flag provided...') flag = bytes_to_long(flag.encode()) p = getPrime(1024) q = getPrime(1024) n = p * q e = 65537 c = pow(flag, e, n) print(f'n = {n}') print(f'p = {p}') print(f'c = {c}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false