[cryptoverse CTF 2023] crypto部分

没打,完事作作题.

Warmup 1

Decode the following ciphertext: GmvfHt8Kvq16282R6ej3o4A9Pp6MsN.

Remember: CyberChef is your friend. Another great cipher decoding tool is Ciphey.

热身一下就凉,问了别人,用ciphey说是能自动解,但是安装报错

rot13+base58 这个没有自动的怎么猜

Warmup 2 

This cipher is invented by French cryptographer Felix Delastelle at the end of the 19th century.

Ciphertext: SCCGDSNFTXCOJPETGMDNG Hint: CTFISGODABEHJKLMNPQRUVWXY

搜了一下是四方密码,但怎么也解不对,后来看WP,中文的网上对这个人讲得不太细,在那一段时间他作了双密码,三密码,四方密码,这个是双密码,把密码对应行列排5个一段上下对应再排

SCCGDSNFTXCOJPETGMDNG
key1: CTFISGODABEHJKLMNPQRUVWXY
  12345
1 CTFIS
2 GODAB
3 EHJKL
4 MNPQR
5 UVWXY

密文编码,5个一组排两行
511111212315421312541122334331122141234221

51111  15421 11223 12214 2
12123  31254 34331 12342 1
上下对应还原
cvctf  funbi fidde codin g
cvctf{funbifiddecoding}

Warmup 3

外国比赛都整上中文了

女川弓彳己廾川 马己 马大川 口川彳己广巛 川巛飞马飞己广 己辶 彳巾山彐马己宀川巾口川 彳马辶. 弓艹口马 山川艹巾, 马川艹廾 廾艹彐弓川 屮艹彳己广 辶巾己廾 彳艹广艹巛艹 女己广 马大川 彳己廾彐川马飞马飞己广 屮山 口己弓宀飞广寸 艹弓弓 彳大艹弓弓川广寸川口. 飞辶 山己门 门广巛川巾口马己己巛 马大川 艹屮己宀川 彳大飞广川口川, 大川巾川 飞口 马大川 辶弓艹寸: 彳宀彳马辶{飞广口川彳门巾川彳大广彳飞彐大川巾}. 口门屮廾飞马 马大川 辶弓艹寸 飞广 弓己女川巾 彳艹口川.

先转成ABCD,再到quipquip上查词频

ABCDEFB GE GHB IBDEJK BKLGLEJ EM DNOPGERBNIB DGM. CSIG OBSN, GBSF FSPCB TSDEJ MNEF DSJSKS AEJ GHB DEFPBGLGLEJ TO IECRLJU SCC DHSCCBJUBI. LM OEV VJKBNIGEEK GHB STERB DHLJBIB, HBNB LI GHB MCSU: DRDGM{LJIBDVNBDHJDLPHBN}. IVTFLG GHB MCSU LJ CEABN DSIB

WELCOME TO THE SECOND EDITION OF CRYPTOVERSE CTF. LAST YEAR, TEAM MAPLE BACON FROM CANADA WON THE COMPETITION BY SOLVING ALL CHALLENGES. IF YOU UNDERSTOOD THE ABOVE CHINESE, HERE IS THE FLAG: CVCTF{INSECURECHNCIPHER}. SUBMIT THE FLAG IN LOWER CASE

cvctf{insecurechncipher}

 

Baby AES

可以爆破的AES加密,密钥只有两字节未知,感觉比热身简单多了

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from secret import flag

KEY_LEN = 2
BS = 16
key = pad(open("/dev/urandom","rb").read(KEY_LEN), BS)
iv =  open("/dev/urandom","rb").read(BS)

cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(flag, 16))

print(f"iv = {iv.hex()}")
print(f"ct = {ct.hex()}")

# Output:
# iv = 1df49bc50bc2432bd336b4609f2104f7
# ct = a40c6502436e3a21dd63c1553e4816967a75dfc0c7b90328f00af93f0094ed62
iv = bytes.fromhex('1df49bc50bc2432bd336b4609f2104f7')
ct = bytes.fromhex('a40c6502436e3a21dd63c1553e4816967a75dfc0c7b90328f00af93f0094ed62')
for i in range(256):
    for j in range(256):
        key = pad(bytes([i,j]), BS)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        flag = cipher.decrypt(ct)
        if not any([1 for v in flag if v>0x80]):
            print(flag)

#cvctf{b4by_AES_s1mpL3} 

LFSR Explorer

非常小的LFSR,但是也不能直接爆破,加密分两段,前边一个后边一个,可以用矩阵快速幂

from Crypto.Util.number import *
from secret import flag

assert flag.startswith("cvctf{")
assert flag.endswith("}")

flag = flag[6:-1].encode()
assert len(flag) == 8

def explore(state, mask):
    curr = (state << 1) & 0xffffffff
    i = state & mask & 0xffffffff
    last = 0
    while i != 0:
        last ^= (i & 1)
        i >>= 1
    curr ^= last
    return (curr, last)

states = [bytes_to_long(flag[4:]), bytes_to_long(flag[:4])]
mask = 0b10000100010010001000100000010101

output = []
for i in range(8):
    tmp = 0
    for j in range(8):
        (states[i // 4], out) = explore(states[i // 4], mask)
        tmp = (tmp << 1) ^ out
    output.append(tmp)

with open("output.txt", "wb") as f:
    f.write(bytes(output))

构造LFSR矩阵

\begin{bmatrix} & & ... & & m \\ 1 & & ... & & a\\ & 1 & ... & & s\\ & & ... & & \\ & & & 1 & k \end{bmatrix}

mask = 0b10000100010010001000100000010101

#前4字节用states[1]后4用states[0]
c = open('output.txt','rb').read()
print(c.hex())
c = bytes.fromhex('d5e4b7c792248e32')
c1 = c[:4]
c2 = c[4:]


M = matrix(GF(2),32)
for i in range(1,32):
    M[i,i-1]= 1

mask = '10000100010010001000100000010101'
for i in range(32):
    M[i,-1] = int(mask[i])

A = M^32 
c1 = bytes_to_long(c1)
c1 = bin(c1)[2:].zfill(32)
c1 = [int(v) for v in c1]
c1 = vector(GF(2),c1)
x = A.solve_left(c1)
t = ''.join([str(i) for i in x])
long_to_bytes(int(t,2))
#_job
c1 = bytes_to_long(c2)
c1 = bin(c1)[2:].zfill(32)
c1 = [int(v) for v in c1]
c1 = vector(GF(2),c1)
x = A.solve_left(c1)
t = ''.join([str(i) for i in x])
long_to_bytes(int(t,2))
#G@@d
#cvctf{G@@d_job}

Knapsack vs. Backpack

背包问题和背包加密,

前边是10次背包问题,按W作体积P作价值,在不超容易的情况下求最大就能满足大于未值(最大值一定不小于随机值)

后边是个背包加密,用到格基规约,但可能没弄好,会卡壳,幸运的时候一次过.不幸运需要几次.

from Crypto.Util.number import *
from math import gcd
from secret import flag
import random

NBITS = 32

print("=== Knapsack vs. Backpack ===")

class Knapsack:
    def __init__(self, nbits):
        W, P = [], []
        for _ in range(nbits):
            W.append(random.randint(1, 10))
            P.append(random.randint(1, 100))
        
        self.W, self.P = W, P

    def fill(self, nbits):
        r = getRandomNBitInteger(nbits)
        pt = [int(i) for i in bin(r)[2:].zfill(nbits)]
        self.A = sum([x * y for x, y in zip(pt, self.W)])
        self.B = sum([x * y for x, y in zip(pt, self.P)])

try:
    for _ in range(10):
        challenge1 = Knapsack(NBITS*4)
        challenge1.fill(NBITS*4)
        print(challenge1.W)
        print(challenge1.P)
        print(f"Knapsack Capacity: {challenge1.A}")

        inp = list(map(int, input("Items: ").strip().split()))
        for i in inp:
            if i < 0 or i >= len(challenge1.W):
                print("Nope.")
                exit(1)
        if len(inp) != len(set(inp)):
            print("Nope.")
            exit(1)
        weight = sum([challenge1.W[i] for i in inp])
        profit = sum([challenge1.P[i] for i in inp])
        if weight <= challenge1.A and profit >= challenge1.B:
            print("Correct!")
        else:
            print("Nope.")
            exit(1)
except:
    exit(1)

print(flag[:len(flag)//2])

class Backpack:
    def __init__(self, nbits):
        r = [42]
        for _ in range(nbits - 1):
            r.append(random.randint(2*r[-1], 4*r[-1]))
        
        B = random.randint(3*r[-1] + 1, 4*r[-1])
        A = random.randint(2*r[-1] + 1, B - 1)
        while gcd(A, B) != 1:
            A = random.randint(2*r[-1] + 1, B - 1)

        self.M = [A * _ % B for _ in r]

    def fill(self, inp):
        return sum([x * y for x, y in zip(inp, self.M)])

try:
    for _ in range(10):
        challenge2 = Backpack(NBITS)
        r = getRandomNBitInteger(NBITS)
        pt = [int(i) for i in bin(r)[2:].zfill(NBITS)]
        ct = challenge2.fill(pt)
        print(challenge2.M)
        print(f"In your Knapsack: {ct}")

        inp = int(input("Secret: ").strip())
        if inp == r:
            print("Correct!")
        else:
            print("Nope.")
            exit(1)
except:
    exit(1)

print(flag[len(flag)//2:])

Fractional Flag

分解问题,刚好前几天比赛有一题用到NovelSystem加密,phi是(p^2+p+1)*(q^2+q+1)在d小于N^0.5给出e的情况下分解n

这个题给了2,3,6三种情况,但仅3的情况有模板.就拿3的情况来解.

from Crypto.Util.number import getPrime, inverse, bytes_to_long
from secret import flag

assert len(flag) == 99
assert flag.startswith(b"cvctf{") and flag.endswith(b"}")

class MyRSA:
    def __init__(self, n = 2, nbits = 512):
        self.p = getPrime(nbits)
        self.q = getPrime(nbits)
        self.N = self.p * self.q
        self.d = getPrime(nbits//2 - 1)
        self.my_phi = self.gen_phi(n)
        self.e = inverse(self.d, self.my_phi)

    def gen_phi(self, n):
        return sum([self.p**i for i in range(n)]) * sum([self.q**i for i in range(n)])

    def encrypt(self, m):
        print("I am not going to encrypt anything...")
        return m

    def get_public(self):
        print(f"N = {self.N}")
        print(f"e = {self.e}\n")
    
    def get_private(self):
        # print(f"d = {self.d}")
        return self.d

NPARTS = 3
fractions = [bytes_to_long(flag[len(flag)//NPARTS*i:len(flag)//NPARTS*(i+1)]) for i in range(NPARTS)]

print("[+] Here are my public keys:")
ns = [2, 3, 6]
rsas = [MyRSA(n) for n in ns]
private_exponents = [rsa.get_private() for rsa in rsas]

for rsa in rsas:
    rsa.get_public()

print("[+] Here are my flag fractions:")
for i in range(NPARTS):
    f = sum(fractions[j] * private_exponents[i]**(NPARTS-1-j) for j in range(NPARTS))
    print(f"[!] Fraction {i+1}: {f}")
debug = True

"""
Setting strict to true will stop the algorithm (and
return (-1, -1)) if we don't have a correct 
upperbound on the determinant. Note that this 
doesn't necesseraly mean that no solutions 
will be found since the theoretical upperbound is
usualy far away from actual results. That is why
you should probably use `strict = False`
"""
strict = False

"""
This is experimental, but has provided remarkable results
so far. It tries to reduce the lattice as much as it can
while keeping its efficiency. I see no reason not to use
this option, but if things don't work, you should try
disabling it
"""
helpful_only = True
dimension_min = 7  # stop removing if lattice reaches that dimension


############################################
# Functions
##########################################

# display stats on helpful vectors
def helpful_vectors(BB, modulus):
    nothelpful = 0
    for ii in range(BB.dimensions()[0]):
        if BB[ii, ii] >= modulus:
            nothelpful += 1

    print(nothelpful, "/", BB.dimensions()[0], " vectors are not helpful")


# display matrix picture with 0 and X
def matrix_overview(BB, bound):
    for ii in range(BB.dimensions()[0]):
        a = ('%02d ' % ii)
        for jj in range(BB.dimensions()[1]):
            a += '0' if BB[ii, jj] == 0 else 'X'
            if BB.dimensions()[0] < 60:
                a += ' '
        if BB[ii, ii] >= bound:
            a += '~'
        print(a)


# tries to remove unhelpful vectors
# we start at current = n-1 (last vector)
def remove_unhelpful(BB, monomials, bound, current):
    # end of our recursive function
    if current == -1 or BB.dimensions()[0] <= dimension_min:
        return BB

    # we start by checking from the end
    for ii in range(current, -1, -1):
        # if it is unhelpful:
        if BB[ii, ii] >= bound:
            affected_vectors = 0
            affected_vector_index = 0
            # let's check if it affects other vectors
            for jj in range(ii + 1, BB.dimensions()[0]):
                # if another vector is affected:
                # we increase the count
                if BB[jj, ii] != 0:
                    affected_vectors += 1
                    affected_vector_index = jj

            # level:0
            # if no other vectors end up affected
            # we remove it
            if affected_vectors == 0:
                print("* removing unhelpful vector", ii)
                BB = BB.delete_columns([ii])
                BB = BB.delete_rows([ii])
                monomials.pop(ii)
                BB = remove_unhelpful(BB, monomials, bound, ii - 1)
                return BB

            # level:1
            # if just one was affected we check
            # if it is affecting someone else
            elif affected_vectors == 1:
                affected_deeper = True
                for kk in range(affected_vector_index + 1, BB.dimensions()[0]):
                    # if it is affecting even one vector
                    # we give up on this one
                    if BB[kk, affected_vector_index] != 0:
                        affected_deeper = False
                # remove both it if no other vector was affected and
                # this helpful vector is not helpful enough
                # compared to our unhelpful one
                if affected_deeper and abs(bound - BB[affected_vector_index, affected_vector_index]) < abs(
                        bound - BB[ii, ii]):
                    print("* removing unhelpful vectors", ii, "and", affected_vector_index)
                    BB = BB.delete_columns([affected_vector_index, ii])
                    BB = BB.delete_rows([affected_vector_index, ii])
                    monomials.pop(affected_vector_index)
                    monomials.pop(ii)
                    BB = remove_unhelpful(BB, monomials, bound, ii - 1)
                    return BB
    # nothing happened
    return BB


def attack(N, e, m, t, X, Y):
    modulus = e

    PR.< x, y > = PolynomialRing(ZZ)
    a = N + 1
    b = N * N - N + 1
    f = x * (y * y + a * y + b) + 1

    gg = []
    for k in range(0, m + 1):
        for i in range(k, m + 1):
            for j in range(2 * k, 2 * k + 2):
                gg.append(x ^ (i - k) * y ^ (j - 2 * k) * f ^ k * e ^ (m - k))
    for k in range(0, m + 1):
        for i in range(k, k + 1):
            for j in range(2 * k + 2, 2 * i + t + 1):
                gg.append(x ^ (i - k) * y ^ (j - 2 * k) * f ^ k * e ^ (m - k))

    def order_gg(idx, gg, monomials):
        if idx == len(gg):
            return gg, monomials

        for i in range(idx, len(gg)):
            polynomial = gg[i]
            non = []
            for monomial in polynomial.monomials():
                if monomial not in monomials:
                    non.append(monomial)

            if len(non) == 1:
                new_gg = gg[:]
                new_gg[i], new_gg[idx] = new_gg[idx], new_gg[i]

                return order_gg(idx + 1, new_gg, monomials + non)

    gg, monomials = order_gg(0, gg, [])

    # construct lattice B
    nn = len(monomials)
    BB = Matrix(ZZ, nn)
    for ii in range(nn):
        BB[ii, 0] = gg[ii](0, 0)
        for jj in range(1, nn):
            if monomials[jj] in gg[ii].monomials():
                BB[ii, jj] = gg[ii].monomial_coefficient(monomials[jj]) * monomials[jj](X, Y)

    # Prototype to reduce the lattice
    if helpful_only:
        # automatically remove
        BB = remove_unhelpful(BB, monomials, modulus ^ m, nn - 1)
        # reset dimension
        nn = BB.dimensions()[0]
        if nn == 0:
            print("failure")
            return 0, 0

    # check if vectors are helpful
    if debug:
        helpful_vectors(BB, modulus ^ m)

    # check if determinant is correctly bounded
    det = BB.det()
    bound = modulus ^ (m * nn)
    if det >= bound:
        print("We do not have det < bound. Solutions might not be found.")
        print("Try with highers m and t.")
        if debug:
            diff = (log(det) - log(bound)) / log(2)
            print("size det(L) - size e^(m*n) = ", floor(diff))
        if strict:
            return -1, -1
    else:
        print("det(L) < e^(m*n) (good! If a solution exists < N^delta, it will be found)")

    # display the lattice basis
    if debug:
        matrix_overview(BB, modulus ^ m)

    # LLL
    if debug:
        print("optimizing basis of the lattice via LLL, this can take a long time")

    BB = BB.LLL()

    if debug:
        print("LLL is done!")

    # transform vector i & j -> polynomials 1 & 2
    if debug:
        print("looking for independent vectors in the lattice")
    found_polynomials = False

    for pol1_idx in range(nn - 1):
        for pol2_idx in range(pol1_idx + 1, nn):
            # for i and j, create the two polynomials
            PR.< a, b > = PolynomialRing(ZZ)
            pol1 = pol2 = 0
            for jj in range(nn):
                pol1 += monomials[jj](a, b) * BB[pol1_idx, jj] / monomials[jj](X, Y)
                pol2 += monomials[jj](a, b) * BB[pol2_idx, jj] / monomials[jj](X, Y)

            # resultant
            PR.< q > = PolynomialRing(ZZ)
            rr = pol1.resultant(pol2)

            # are these good polynomials?
            if rr.is_zero() or rr.monomials() == [1]:
                continue
            else:
                print("found them, using vectors", pol1_idx, "and", pol2_idx)
                found_polynomials = True
                break
        if found_polynomials:
            break

    if not found_polynomials:
        print("no independant vectors could be found. This should very rarely happen...")
        return 0, 0

    rr = rr(q, q)

    # solutions
    soly = rr.roots()

    if len(soly) == 0:
        print("Your prediction (delta) is too small")
        return 0, 0

    soly = soly[0][0]
    ss = pol1(q, soly)
    solx = ss.roots()[0][0]

    return solx, soly

def inthroot(a, n):
    return a.nth_root(n, truncate_mode=True)[0]

'''
n=3
phi1 = (p^2 + p + 1)(q^2 + q + 1)
f2 = m0*d1^2 + m1*d1 + m2
'''

N = 82898492840033848499679066573599199466262845944574446435099699953454086638324386416129279494828609729766998439132172194894188387716844097335523066318666261933348513791114624155336437054163128912934864480178839237943154511986161169068625070999701692457965233641625122455113801192492673037347038351956273261209
e = 4209437149177720414392052396995336370571472638739290885909782621676928212352728218779571626530884770305850882606520062302514835362331092897621059096111410844919671863579044484955054277159466422627065939698416080746679841734383574957303171143150437215717944527004524163060734647488552780385109395365103554265493136383680197786179491825415327877829363932241445886199163804911851983235568877189260370900147226881457732043676609664875472514523869518158935427849891304397052900751093562294098001282747462255107311383605819243052786444806092296448159814920695343700003324553167747140120222023780385726663202175975632841101

X = 1 << 256
Y = 2 * inthroot(Integer(2 * N), 2)
res = attack(N, e, 4, 2, X, Y)
b, c = res[1], N
Dsqrt =  inthroot(Integer(b^2-4*c),2)
p, q = (b + Dsqrt) // 2, (b - Dsqrt) // 2

p = 11115193571655981643028323108550693041153968818372992008741167962199978558269263501404542622452843466273897515259474630311844764203824460112544754903161827
q = 7458124080846154074703203775228063793095921609194518958985360092112085241527639903426152277377512681937094209982722994493765347290922190684486027516944467

在解出p,q后可以求d,然后是 enc = m0*d^{2} + m1*d + m2 看似简单,但发现m要大于d,这样直接取模就不成了,这时候需要爆破一下,毕竟比d也大不太多.

phi = (p^2 + p +1)*(q^2 + q +1)
d = inverse_mod(e, phi)

f2 = 23144924364202496361036242964551729244108242071387074122924446048219898057065538815277890013860024253422666710259842325295228086904295846675276536535237894072110755426259617054492417613772645109337095876879440959135444974146373938103

#m>d 
f4 = f2%d 
for i in range(0x200):
    m2 = f4+i*d
    tmp = long_to_bytes(m2)
    if not any([1 for v in tmp if v<0x20 or v>0x7f]):
        print(i, tmp)
        break
#127 b'15_cL053_t0_N^(n-1)_4nd_d<N^0.25}'

f3 = f2 - m2 
f3 //=d 
f3 %=d 
for i in range(0x200):
    m1 = f3+i*d
    tmp = long_to_bytes(m1)
    if not any([1 for v in tmp if v<0x20 or v>0x7f]):
        print(i, tmp)
        break
        
#290 b'pt0syst3m_c4n_b3_4tt4ck3d_wh3n_E_'
m0 = f2//d^2 - 290
print(long_to_bytes(m0))
#'cvctf{th15_fam1Ly_0f_RSA-like_cry'
#cvctf{th15_fam1Ly_0f_RSA-like_crypt0syst3m_c4n_b3_4tt4ck3d_wh3n_E_15_cL053_t0_N^(n-1)_4nd_d<N^0.25}

剩下两个题 PicoChip 1,PicoChip 2 附件下不来,回头看看网上有没有.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值