2021-07-01

今天介个特殊的日子里,我的脑子里的知识仍是一片贫瘠,吓得我赶紧做了做赵总给的三道传说中的签到题,充实一下自己,记录一下在这个伟大日子里做的签到题吧。

题一:MT1993([GKCTF 2021]Random改)

一、题目描述

import random
from hashlib import md5

def get_mask():
    file = open("random.txt", "w")
    for i in range(104):
        file.write(str(random.getrandbits(32))+"\n")
        file.write(str(random.getrandbits(64))+"\n")
        file.write(str(random.getrandbits(96))+"\n")
    file.close()

get_mask()
flag = md5(str(random.getrandbits(32)).encode()).hexdigest()
print(flag) #求佛赖哥

给了104*3个随机数,让我求下一个随机数???

二、解题思路

要(yào)求 flag,就是整一手随机数
瞅了瞅 random.getrandbits()
不由地想到了伪随机,然后就傻不拉几地尝试了随机数种子,企图爆破暴力破解。
经过脚本的不懈努力,我果断放弃了脚本,把目光转向了在这里插入图片描述
当看到文件夹名为“MT19937”。
我便开始了苦苦的各种搜索,最后无意间看见了神奇的东西。
在这里插入图片描述

啊哈,没错,一个神奇而又牛逼的模块(居然能够预测随机数amazing啊),果断买它(不是)!安装模块!pip install mersenne-twister-predictor

三、小小的脚本啊

有了工具,再看看怎么使用它。
根据上图描述是这样的:

import random
from mt19937predictor import MT19937Predictor
predictor = MT19937Predictor ()
for _ in range ( 624 ):
    x = random . getrandbits ( 32 )
    predictor . setrandbits ( x , 32 )
assert random . getrandbits ( 32 ) == predict

其中 predictor . setrandbits ( x , 32 ) 是将已有的随机数填入,从而后面预测随机数。
然后我们根据我们题目的需要改改脚本:

import random
from mt19937predictor import MT19937Predictor
predictor = MT19937Predictor()
file = open("random.txt", "r")
for _ in range(104):
    x=file.readline().strip('\n')
    predictor.setrandbits(int(x), 32)
    x = file.readline().strip('\n')
    predictor.setrandbits(int(x), 64)
    x = file.readline().strip('\n')
    predictor.setrandbits(int(x), 96)
a=predictor.getrandbits(32)
file.close()
flag = md5(str(a).encode()).hexdigest()
print(flag)

最后得到结果噢噢噢噢哦哦哦
d771adebf5cd53e479254d6f877f46b3”即为佛赖哥

四、小小的总结

运气好,找着了~
运气好,蒙对了~(凑字数)

题二:boneh_durfee

一、题目描述

from Crypto.Util.number import bytes_to_long, long_to_bytes, getPrime
from gmpy2 import invert

flag = b"novaCTF{******}"
m = bytes_to_long(flag)
p = getPrime(512)
q = getPrime(512)
n = p*q
d = getPrime(260)
phi = (p-1)*(q-1)
e = invert(d, phi)
c = pow(m, e, n)
print(e)
print(n)
print(c)
# e=  28366532045084591636437544767374939012961757129620507106907154467035496029282857415182567552270978206397793889819857945701555381457862312304572366567535998525153574576210520634959025982966194022680398054500011866734299857844098161391787585786609289654556120958843118695788794035767689727287572845453232286487
# n = 116619053095181844867756588238123176803022888638090603550604610234584486986893904698844566541567093613495764007369858037838298617868152946508912345019503344911355228396374219771717648337137214599383155473846763062399405332170035904047911459812639096963243997609662442560069465026848168759806881590989694374289
# c = 5550387375810892705924800464945980988431639193797468627845836397962361427321133854633770242318969576163563079147919098794998899335191281861385800469677049957403290859349688725585260874592933564793273307183923684839207469443101629472424936878786558261355723914033881683475668259544365455286750343306090149047

二、解题思路

又是一个起起伏伏的“签到题”。
在这里插入图片描述
一眼瞅见了好大的指数e,开心的要死,这不就是那亲切的Wiener攻击嘛。可惜,直接报错
在这里插入图片描述

社会很单纯,复杂的是人

回头直接打开了我的宝典秘籍(大佬的博客),企图寻找点思路。我看到了Coppersmith攻击(已知明文高位攻击,部分m),我心花怒放。
它告诉我了

flag = b"novaCTF{******}"

这不就有部分m嘛。虽然没有已知明文高位,但是我可以创造已知明文高位的嘛。

#Sage Coppersmith攻击(已知明文高位攻击,部分m)
n = 
e = 
c = 
mbar = 
kbits = 
beta = 1
nbits = n.nbits()
print("upper {} bits of {} bits is given".format(nbits - kbits, nbits))
PR.<x> = PolynomialRing(Zmod(n))
f = (mbar + x)^e - c
x0 = f.small_roots(X=2^kbits, beta=1)[0]  # find root < 2^kbits with factor = n
print("m:", mbar + x0)

当我填入数据,脚本一跑,发现它老报错(后来知道ee太大大大大大了),老桑心咯
之后,经赵总提醒:大e除了Winner攻击,还有其他的攻击。
接着翻阅“ 宝典秘籍”,看到有在这里插入图片描述
看到了这里,好家伙~
Boneh和Durffe攻击,又想到了赵总以前讲的一道题目中的解题脚本,直接拿过来抄抄在这里插入图片描述

三、解题脚本:

直接上脚本:

#Sage
import time

############################################
# Config
##########################################

"""
Setting debug to true will display more informations
about the lattice, the bounds, the vectors...
"""
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


"""
Returns:
* 0,0   if it fails
* -1,-1 if `strict=true`, and determinant doesn't bound
* x0,y0 the solutions of `pol`
"""


def boneh_durfee(pol, modulus, mm, tt, XX, YY):
    """
    Boneh and Durfee revisited by Herrmann and May

    finds a solution if:
    * d < N^delta
    * |x| < e^delta
    * |y| < e^0.5
    whenever delta < 1 - sqrt(2)/2 ~ 0.292
    """

    # substitution (Herrman and May)
    PR.<u,x,y>=PolynomialRing(ZZ)
    Q = PR.quotient(x * y + 1 - u)  # u = xy + 1
    polZ = Q(pol).lift()

    UU = XX * YY + 1

    # x-shifts
    gg = []
    for kk in range(mm + 1):
        for ii in range(mm - kk + 1):
            xshift = x ^ ii * modulus ^ (mm - kk) * polZ(u, x, y) ^ kk
            gg.append(xshift)
    gg.sort()

    # x-shifts list of monomials
    monomials = []
    for polynomial in gg:
        for monomial in polynomial.monomials():
            if monomial not in monomials:
                monomials.append(monomial)
    monomials.sort()

    # y-shifts (selected by Herrman and May)
    for jj in range(1, tt + 1):
        for kk in range(floor(mm / tt) * jj, mm + 1):
            yshift = y ^ jj * polZ(u, x, y) ^ kk * modulus ^ (mm - kk)
            yshift = Q(yshift).lift()
            gg.append(yshift)  # substitution

    # y-shifts list of monomials
    for jj in range(1, tt + 1):
        for kk in range(floor(mm / tt) * jj, mm + 1):
            monomials.append(u ^ kk * y ^ jj)

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

    # Prototype to reduce the lattice
    if helpful_only:
        # automatically remove
        BB = remove_unhelpful(BB, monomials, modulus ^ mm, 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 ^ mm)

    # check if determinant is correctly bounded
    det = BB.det()
    bound = modulus ^ (mm * 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 ^ mm)

    # 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.<w,z>=PolynomialRing(ZZ)
            pol1 = pol2 = 0
            for jj in range(nn):
                pol1 += monomials[jj](w * z + 1, w, z) * BB[pol1_idx, jj] / monomials[jj](UU, XX, YY)
                pol2 += monomials[jj](w * z + 1, w, z) * BB[pol2_idx, jj] / monomials[jj](UU, XX, YY)

            # 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 example():
    ############################################
    # How To Use This Script
    ##########################################

    #
    # The problem to solve (edit the following values)
    #

    # the modulus
    N = 116619053095181844867756588238123176803022888638090603550604610234584486986893904698844566541567093613495764007369858037838298617868152946508912345019503344911355228396374219771717648337137214599383155473846763062399405332170035904047911459812639096963243997609662442560069465026848168759806881590989694374289
    # the public exponent
    e = 28366532045084591636437544767374939012961757129620507106907154467035496029282857415182567552270978206397793889819857945701555381457862312304572366567535998525153574576210520634959025982966194022680398054500011866734299857844098161391787585786609289654556120958843118695788794035767689727287572845453232286487

    # the hypothesis on the private exponent (the theoretical maximum is 0.292)
    delta = .292  # this means that d < N^delta

    #
    # Lattice (tweak those values)
    #

    # you should tweak this (after a first run), (e.g. increment it until a solution is found)
    m = 4  # size of the lattice (bigger the better/slower)

    # you need to be a lattice master to tweak these
    t = int((1 - 2 * delta) * m)  # optimization from Herrmann and May
    X = 2 * floor(N ^ delta)  # this _might_ be too much
    Y = floor(N ^ (1 / 2))  # correct if p, q are ~ same size

    #
    # Don't touch anything below
    #

    # Problem put in equation
    P.<x,y>=PolynomialRing(ZZ)
    A = int((N + 1) / 2)
    pol = 1 + x * (A + y)

    #
    # Find the solutions!
    #

    # Checking bounds
    if debug:
        print("=== checking values ===")
        print("* delta:", delta)
        print("* delta < 0.292", delta < 0.292)
        print("* size of e:", int(log(e) / log(2)))
        print("* size of N:", int(log(N) / log(2)))
        print("* m:", m, ", t:", t)

    # boneh_durfee
    if debug:
        print("=== running algorithm ===")
        start_time = time.time()

    solx, soly = boneh_durfee(pol, e, m, t, X, Y)

    # found a solution?
    if solx > 0:
        print("=== solution found ===")
        if False:
            print("x:", solx)
            print("y:", soly)

        d = int(pol(solx, soly) / e)
        print("private key found:", d)
    else:
        print("=== no solution was found ===")

    if debug:
        print("=== %s seconds ===" % (time.time() - start_time))


if __name__ == "__main__":
    example()

在这里插入图片描述
解得d:1604729467840738070847003596064117868379286998792964612314423127886316878631207
之后已知c,d,n求m

import Crypto.Util.number
n = 116619053095181844867756588238123176803022888638090603550604610234584486986893904698844566541567093613495764007369858037838298617868152946508912345019503344911355228396374219771717648337137214599383155473846763062399405332170035904047911459812639096963243997609662442560069465026848168759806881590989694374289
c = 5550387375810892705924800464945980988431639193797468627845836397962361427321133854633770242318969576163563079147919098794998899335191281861385800469677049957403290859349688725585260874592933564793273307183923684839207469443101629472424936878786558261355723914033881683475668259544365455286750343306090149047
d = 1604729467840738070847003596064117868379286998792964612314423127886316878631207
m=pow(c,d,n)
print(long_to_bytes(m))#b"novaCTF{d0n't_J0_kn0wn_b0n3h_durf33}"

四、小总结

两种e非常大的攻击中,要注意e,d和N三者的关系。
d < (1/3) N1/4​ ,则可选择Winner攻击
(1/3) N1/4​ < d < N0.292,则可选择 Boneh和Durffe攻击
​另外在试错的过程中,进一步了解了Coppersmith攻击(已知明文高位攻击,部分m),针不戳呢~

题三:Pohlig-hellman([WDB2020]you raise me up改)

一、题目描述

from Crypto.Util.number import *
import random

flag = b"novaCTF{******}"
n = 2 ** 1024
e = bytes_to_long(flag)
m = 0b101010101010101010100101001010101010010101001010111
c = pow(m, e, n)
print(m)
print(c)

# m = 1501199137581655
# c = 66833442412465837593411329882154519317338634354813852217147677313497719741502965349598626224700154836780839167770562034307746877775924269074354587364763439201631983852896392052544055458196432140978886498016995260963282787641046569867110159856825184627818917769177045102578369482845631041962774517107346776951

二、解题思路及脚本

跟据题目描述和文件名“Pohlig-hellman”(主要),可得此题是关于离散对数的问题。网上是搜索相关知识,大多讲的是用大步小步算法(BSGS),解a ≡ b x (mod p) 求x(其中p为素数)的问题。
但看此题,我的n=2**1024,并不是素数,不能用这种方法求解。之后在这里看到在这里插入图片描述
提到了

N是一个很小质数的某次方

在这里插入图片描述
一心只看见了下面的代码框,无视了上面的说明(血亏)

R = GF(11251)

这是定义有限域,在这里“11251”相对来说很小,能够支持。不过当我换成“2^1024”时,直接崩溃(太大啦)。
再后来,山穷水尽之时,瞄了一眼组员的代码,我瞬间就悟了。
关键在于discrete_log()这个函数,这玩意能直接解出来(tql)。
在这里插入图片描述
直接解出:e=14060055189555570071429719171094874816393997350768871510764851230938904613114745283102796669
转换一下得出flag:

import Crypto.Util.number
print(Crypto.Util.number.long_to_bytes(14060055189555570071429719171094874816393997350768871510764851230938904613114745283102796669))
#b'novaCTF{th1s_1s_h0w_D1scr3t3_l0g_w0rk}'

三、小小小总结

掌握了一内内的离散对数问题。
看了天选之人赵总博客,真是清晰明了啊
赵总 yyds~

大的小总结

短学期的第一天,过得充实哇~
完成和记录了每日三题,第一次写博客还是很开森(就是嫌麻烦,啊哈哈哈~)
此外,还做了几道水题(不太想做记录,嘿,就是懒~)

总的学习了predictor.setrandbits ( )函数、e很大时,满足的攻击条件和discrete_log()函数。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mxx307

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值