2019强网杯Crypto Write Up
该部分为本科期间wp备份。
0x01 强网先锋-辅助
附件:task_cha.py
Solution
题目提供了一个python脚本:
#加密内容
flag=open("flag","rb").read()
from Crypto.Util.number import getPrime,bytes_to_long
p=getPrime(1024)
q=getPrime(1024)
e=65537
n=p*q
m=bytes_to_long(flag)
c=pow(m,e,n)
print c,e,n
p=getPrime(1024)
e=65537
n=p*q
m=bytes_to_long("1"*32)
c=pow(m,e,n)
print c,e,n
其中Output表示各个值为:
c1=2482083893746618248544426737023750400124543452082436334398504986023501710639402060949106693279462896968839029712099336235976221571564642900240827774719199533124053953157919850838214021934907480633441577316263853011232518392904983028052155862154264401108124968404098823946691811798952747194237290581323868666637357604693015079007555594974245559555518819140844020498487432684946922741232053249894575417796067090655122702306134848220257943297645461477488086804856018323986796999103385565540496534422406390355987976815450744535949785073009043007159496929187184338592859040917546122343981520508220332785862546608841127597
e=65537
n1=14967030059975114950295399874185047053736587880127990542035765201425779342430662517765063258784685868107066789475747180244711352646469776732938544641583842313791872986357504462184924075227433498631423289187988351475666785190854210389587594975456064984611990461126684301086241532915267311675164190213474245311019623654865937851653532870965423474555348239858021551589650169602439423841160698793338115204238140085738680883313433574060243600028500600824624358473403059597593891412179399165813622512901263380299561019624741488779367019389775786547292065352885007224239581776975892385364446446185642939137287519945974807727c2=3829060039572042737496679186881067950328956133163629908872348108160129550437697677150599483923925798224328175594483217938833520220087230303470138525970468915511111320396185482564783975435346354440035776909781158407636044986403819840648379609630039348895415045723208843631191252142600667607807479954194447237061080618370787672720344741413537975922184859333432197766580150534457001196765621678659952108010596273244230812327182786329760844037149719587269632133595149294067490955644893402708720284179715002149224068928828656515326446881791228638008572889331511945042911372915003805505412099102954073299010951896955362470
e=65537n2=14624662628725820618622370803948630854094687814338334827462870357582795291844925274690253604919535785934208081825425541536057550227048399837243392490762167733083030368221240764693694321150104306044125934201699430146970466657410999261630825931178731857267599750324918610790098952520113593130245010530961350592735239454337631927669542026935873535964487595433984902529960726655481696404006628917922241666148082741874033756970724357470539589848548704573091633917869387239324447730587545472564561496724882799495186768858324490838169123077051890332313671220385830444331578674338014080959653201802476516237464651809255679979
显然q=gcd(n1,n2),我们写个sage脚本:
from sage import *
n1=14967030059975114950295399874185047053736587880127990542035765201425779342430662517765063258784685868107066789475747180244711352646469776732938544641583842313791872986357504462184924075227433498631423289187988351475666785190854210389587594975456064984611990461126684301086241532915267311675164190213474245311019623654865937851653532870965423474555348239858021551589650169602439423841160698793338115204238140085738680883313433574060243600028500600824624358473403059597593891412179399165813622512901263380299561019624741488779367019389775786547292065352885007224239581776975892385364446446185642939137287519945974807727
n2=14624662628725820618622370803948630854094687814338334827462870357582795291844925274690253604919535785934208081825425541536057550227048399837243392490762167733083030368221240764693694321150104306044125934201699430146970466657410999261630825931178731857267599750324918610790098952520113593130245010530961350592735239454337631927669542026935873535964487595433984902529960726655481696404006628917922241666148082741874033756970724357470539589848548704573091633917869387239324447730587545472564561496724882799495186768858324490838169123077051890332313671220385830444331578674338014080959653201802476516237464651809255679979
c1=2482083893746618248544426737023750400124543452082436334398504986023501710639402060949106693279462896968839029712099336235976221571564642900240827774719199533124053953157919850838214021934907480633441577316263853011232518392904983028052155862154264401108124968404098823946691811798952747194237290581323868666637357604693015079007555594974245559555518819140844020498487432684946922741232053249894575417796067090655122702306134848220257943297645461477488086804856018323986796999103385565540496534422406390355987976815450744535949785073009043007159496929187184338592859040917546122343981520508220332785862546608841127597
e=65537
q=gcd(n1,n2)
p1=Integer(n1/q)
d=inverse_mod(e,(p1-1)*(q-1))
m1=power_mod(c1,d,n1)
print hex(m1).decode('hex')
flag:
flag
0x02 copperstudy
119.3.245.36 12345 请使用自己队伍的token获取flag,否则flag无效
Solution
首先我在ubuntu中打开terminal,使用以下命令:
$ nc 119.3.245.36 12345
得到如下内容:
[+]proof: skr=os.urandom(8)
[+]hashlib.sha256(skr).hexdigest()=10206d8f1c50a86b89ce8811b3cc6067a2e649f8c7ac444284ca7d22c8f025ed
[+]skr[0:5].encode('hex')=638e1ae082
[-]skr.encode('hex')=
0x0201 SHA256爆破
使用以下脚本,进行爆破:
# -*- coding: utf-8 -*-
import hashlib
def num2str(num):
h=hex(num)[2:].replace("L","")
if len(h)%2 ==0 :
return h.decode("hex")
else:
return ("0"+h).decode("hex")
def str2num(str):
return str.encode("hex")
sha=0x638e1ae082
str=num2str(sha)
print str2num(str)
for i in range(256):
for j in range(256):
for k in range(256):
tmp=str+chr(i)+chr(j)+chr(k)
if hashlib.sha256(tmp).hexdigest()=='10206d8f1c50a86b89ce8811b3cc6067a2e649f8c7ac444284ca7d22c8f025ed':
print 'yes'
print str2num(tmp)
得到如下结果:
638e1ae082266b9b
0x0202 challenge 1
输入sha爆破内容后再输入token,得到第一关内容:
+]Generating challenge 1
[+]n=0xc49f9084060b8a2474c1f7946b5a7342a731e3e9c3d255019cfef1ba076ad3498b836b92a2f4598551f81425c2656f0496081de2f650d22895236f99617e3d00db5171db1f6828434aa078893dab297341b8ef6bf8009d30d0918588520847dc65ef7784b066d44a3220c76d9346c99eddb3bcd8aeaa799ceb14b81a63f10901L
[+]e=3
[+]m=random.getrandbits(512)
[+]c=pow(m,e,n)=0x5130a8ef31a688c2173b2af2c1135b01b59a9cbb9b0373625cf0c876c0c29cb9b416d7189fdb5170482be966e996663e3cba456cde07072cd194145cb7e011340459ca1302c94a7f60e7d849fbb4762a4fe616a613a724177d9f783c326025991a1fb38eaa317c974c4d1ec0cd23b3d439e6bb85c4219a637be324e8d704e624L
[+]((m>>72)<<72)=0x96305f7878db108f857c58f15541270655e96264efbe162c4a9e99980302d2f66c528237520bee5bbe7d1853e18f58f56d70dac70df470000000000000000000L
[-]long_to_bytes(m).encode('hex')=
从题目中,我们知道明文数据是进行低72位隐藏了,只提供了高位,为Known High Bits Message Attack。根据题目Copper,猜测是Copper Smith Attack,结合Github的LLL Attack项目开源代码,写了如下sage脚本:
import time
import sys
def long_to_bytes(data):
data = str(hex(long(data)))[2:-1]
return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)])
def bytes_to_long(data):
return int(data.encode('hex'), 16)
def main():
e, N = (3L,
138073575999714129389538270467682168532356738438077530022536349026163826957988599798050633312573610479474331679250090753672032962241366326571602923845680488098362630704918772507774264079525826202642519455421991047230381725680810387887628929737362932412072473000137534131190407786472579174824033737538909833473L)
c = 0x5130a8ef31a688c2173b2af2c1135b01b59a9cbb9b0373625cf0c876c0c29cb9b416d7189fdb5170482be966e996663e3cba456cde07072cd194145cb7e011340459ca1302c94a7f60e7d849fbb4762a4fe616a613a724177d9f783c326025991a1fb38eaa317c974c4d1ec0cd23b3d439e6bb85c4219a637be324e8d704e624L
m = 0x96305f7878db108f857c58f15541270655e96264efbe162c4a9e99980302d2f66c528237520bee5bbe7d1853e18f58f56d70dac70df470000000000000000000L
P.<x> = PolynomialRing(Zmod(N), implementation='NTL')
pol = (m + x) ^ e - c
roots = pol.small_roots(epsilon=1 / 30)
print("Potential solutions:")
for root in roots:
print long_to_bytes(m + root).encode('hex')
main()
得到结果:
96305f7878db108f857c58f15541270655e96264efbe162c4a9e99980302d2f66c528237520bee5bbe7d1853e18f58f56d70dac70df4701d1b5e9ad63e129467
0x0203 challenge 2
提交第一关答案之后,进入第二关:
[+]Generating challenge 2
[+]n=0x48fe8663bb4bc4e933f157a8821ce161fc4d11bc7ddfb738edd294e86c332182681deb02b3eb3c024d831319f38a0278a9c6d8b25d5994ee6b32d5d74857891e2ff800ac2753058eb2441f1477a4ac0bb8151a5938995233265d724da460f01f6fd63d87f7a22f7d0e10dbe48d4bf20eaa8995451b5cbc81bc1ea53ee4fe669L
[+]e=65537
[+]m=random.getrandbits(512)
[+]c=pow(m,e,n)=0x30f56c13ed32d320921464552857009dca669dd89eede49f95ca04869d7886c95396de19e6c9ed4727ce35efe05e215388038ac3fecdada6a167bda6ff8bff0f75d063b9b51f0980b7bbdd2eb176d3527fc031ebbe23d21bb4b9d3a5e220c1dde930b0a9c7e0893d316c903c5f334d39a542c22813ad2d16fb343ff1db86c55L
[+]((p>>128)<<128)=0xe3662bc6ab72988ec97d83c1154e5d2a9a6d0d5bf2f5a17bad2ea8a8a3bc1df2f28aab276bbd9421752c3366d9ddbe0a00000000000000000000000000000000L
[-]long_to_bytes(m).encode('hex')=
显然,第二关是因子隐藏低128位,保留高位。为Factoring with High Bits Known。因此我根据LLL Attack提供的脚本进行修改得到如下sage脚本:
coppersmith.sage:
import time
debug = True
# 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'
a += ' '
if BB[ii, ii] >= bound:
a += '~'
print a
def coppersmith_howgrave_univariate(pol, modulus, beta, mm, tt, XX):
"""
Coppersmith revisited by Howgrave-Graham
finds a solution if:
* b|modulus, b >= modulus^beta , 0 < beta <= 1
* |x| < XX
"""
#
# init
#
dd = pol.degree()
nn = dd * mm + tt
#
# checks
#
if not 0 < beta <= 1:
raise ValueError("beta should belongs in (0, 1]")
if not pol.is_monic():
raise ArithmeticError("Polynomial must be monic.")
#
# calculate bounds and display them
#
"""
* we want to find g(x) such that ||g(xX)|| <= b^m / sqrt(n)
* we know LLL will give us a short vector v such that:
||v|| <= 2^((n - 1)/4) * det(L)^(1/n)
* we will use that vector as a coefficient vector for our g(x)
* so we want to satisfy:
2^((n - 1)/4) * det(L)^(1/n) < N^(beta*m) / sqrt(n)
so we can obtain ||v|| < N^(beta*m) / sqrt(n) <= b^m / sqrt(n)
(it's important to use N because we might not know b)
"""
if debug:
# t optimized?
print "\n# Optimized t?\n"
print "we want X^(n-1) < N^(beta*m) so that each vector is helpful"
cond1 = RR(XX^(nn-1))
print "* X^(n-1) = ", cond1
cond2 = pow(modulus, beta*mm)
print "* N^(beta*m) = ", cond2
print "* X^(n-1) < N^(beta*m) \n-> GOOD" if cond1 < cond2 else "* X^(n-1) >= N^(beta*m) \n-> NOT GOOD"
# bound for X
print "\n# X bound respected?\n"
print "we want X <= N^(((2*beta*m)/(n-1)) - ((delta*m*(m+1))/(n*(n-1)))) / 2 = M"
print "* X =", XX
cond2 = RR(modulus^(((2*beta*mm)/(nn-1)) - ((dd*mm*(mm+1))/(nn*(nn-1)))) / 2)
print "* M =", cond2
print "* X <= M \n-> GOOD" if XX <= cond2 else "* X > M \n-> NOT GOOD"
# solution possible?
print "\n# Solutions possible?\n"
detL = RR(modulus^(dd * mm * (mm + 1) / 2) * XX^(nn * (nn - 1) / 2))
print "we can find a solution if 2^((n - 1)/4) * det(L)^(1/n) < N^(beta*m) / sqrt(n)"
cond1 = RR(2^((nn - 1)/4) * detL^(1/nn))
print "* 2^((n - 1)/4) * det(L)^(1/n) = ", cond1
cond2 = RR(modulus^(beta*mm) / sqrt(nn))
print "* N^(beta*m) / sqrt(n) = ", cond2
print "* 2^((n - 1)/4) * det(L)^(1/n) < N^(beta*m) / sqrt(n) \n-> SOLUTION WILL BE FOUND" if cond1 < cond2 else "* 2^((n - 1)/4) * det(L)^(1/n) >= N^(beta*m) / sqroot(n) \n-> NO SOLUTIONS MIGHT BE FOUND (but we never know)"
# warning about X
print "\n# Note that no solutions will be found _for sure_ if you don't respect:\n* |root| < X \n* b >= modulus^beta\n"
#
# Coppersmith revisited algo for univariate
#
# change ring of pol and x
polZ = pol.change_ring(ZZ)
x = polZ.parent().gen()
# compute polynomials
gg = []
for ii in range(mm):
for jj in range(dd):
gg.append((x * XX)**jj * modulus**(mm - ii) * polZ(x * XX)**ii)
for ii in range(tt):
gg.append((x * XX)**ii * polZ(x * XX)**mm)
# construct lattice B
BB = Matrix(ZZ, nn)
for ii in range(nn):
for jj in range(ii+1):
BB[ii, jj] = gg[ii][jj]
# display basis matrix
if debug:
matrix_overview(BB, modulus^mm)
# LLL
BB = BB.LLL()
# transform shortest vector in polynomial
new_pol = 0
for ii in range(nn):
new_pol += x**ii * BB[0, ii] / XX**ii
# factor polynomial
potential_roots = new_pol.roots()
print "potential roots:", potential_roots
# test roots
roots = []
for root in potential_roots:
if root[0].is_integer():
result = polZ(ZZ(root[0]))
if gcd(modulus, result) >= modulus^beta:
roots.append(ZZ(root[0]))
#
return roots
############################################
# Test on Stereotyped Messages
##########################################
print "//////////////////////////////////"
print "// TEST 1"
print "////////////////////////////////"
# RSA gen options (for the demo)
length_N = 1024 # size of the modulus
Kbits = 200 # size of the root
e = 3
# RSA gen (for the demo)
p = next_prime(2^int(round(length_N/2)))
q = next_prime(p)
N = p*q
ZmodN = Zmod(N);
# Create problem (for the demo)
K = ZZ.random_element(0, 2^Kbits)
Kdigits = K.digits(2)
M = [0]*Kbits + [1]*(length_N-Kbits);
for i in range(len(Kdigits)):
M[i] = Kdigits[i]
M = ZZ(M, 2)
C = ZmodN(M)^e
# Problem to equation (default)
P.<x> = PolynomialRing(ZmodN) #, implementation='NTL')
pol = (2^length_N - 2^Kbits + x)^e - C
dd = pol.degree()
# Tweak those
beta = 1 # b = N
epsilon = beta / 7 # <= beta / 7
mm = ceil(beta**2 / (dd * epsilon)) # optimized value
tt = floor(dd * mm * ((1/beta) - 1)) # optimized value
XX = ceil(N**((beta**2/dd) - epsilon)) # optimized value
# Coppersmith
start_time = time.time()
roots = coppersmith_howgrave_univariate(pol, N, beta, mm, tt, XX)
# output
print "\n# Solutions"
print "we want to find:",str(K)
print "we found:", str(roots)
print("in: %s seconds " % (time.time() - start_time))
print "\n"
############################################
# Test on Factoring with High Bits Known
##########################################
print "//////////////////////////////////"
print "// TEST 2"
print "////////////////////////////////"
# RSA gen
length_N = 1024;
p = next_prime(2^int(round(length_N/2)));
q = next_prime( round(pi.n()*p) );
N = p*q;
# qbar is q + [hidden_size_random]
hidden = 200;
diff = ZZ.random_element(0, 2^hidden-1)
qbar = q + diff;
F.<x> = PolynomialRing(Zmod(N), implementation='NTL');
pol = x - qbar
dd = pol.degree()
# PLAY WITH THOSE:
beta = 0.5 # we should have q >= N^beta
epsilon = beta / 7 # <= beta/7
mm = ceil(beta**2 / (dd * epsilon)) # optimized
tt = floor(dd * mm * ((1/beta) - 1)) # optimized
XX = ceil(N**((beta**2/dd) - epsilon)) # we should have |diff| < X
# Coppersmith
start_time = time.time()
roots = coppersmith_howgrave_univariate(pol, N, beta, mm, tt, XX)
# output
print "\n# Solutions"
print "we want to find:", qbar - q
print "we found:", roots
print("in: %s seconds " % (time.time() - start_time))
解本题脚本:
load("coppersmith.sage")
N=0x48fe8663bb4bc4e933f157a8821ce161fc4d11bc7ddfb738edd294e86c332182681deb02b3eb3c024d831319f38a0278a9c6d8b25d5994ee6b32d5d74857891e2ff800ac2753058eb2441f1477a4ac0bb8151a5938995233265d724da460f01f6fd63d87f7a22f7d0e10dbe48d4bf20eaa8995451b5cbc81bc1ea53ee4fe669
ZmodN = Zmod(N)
P.<x> = PolynomialRing(ZmodN)
qbar = 0xe3662bc6ab72988ec97d83c1154e5d2a9a6d0d5bf2f5a17bad2ea8a8a3bc1df2f28aab276bbd9421752c3366d9ddbe0a00000000000000000000000000000000
f = x - qbar
beta = 0.4
dd = f.degree()
epsilon = beta / 7
mm = ceil(beta**2 / (dd * epsilon))
tt = floor(dd * mm * ((1/beta) - 1))
XX = ceil(N**((beta**2/dd) - epsilon)) + 1000000000000000000000000000000000
roots = coppersmith_howgrave_univariate(f, N, beta, mm, tt, XX)
得到结果如下:
(-53629be7161800f613107bdfe89b9dcd,1)
去符号并加上高位部分得到p:
0xe3662bc6ab72988ec97d83c1154e5d2a9a6d0d5bf2f5a17bad2ea8a8a3bc1df2f28aab276bbd9421752c3366d9ddbe0a53629be7161800f613107bdfe89b9dcd
再放入通用的RSA sage脚本中:
p=0xe3662bc6ab72988ec97d83c1154e5d2a9a6d0d5bf2f5a17bad2ea8a8a3bc1df2f28aab276bbd9421752c3366d9ddbe0a53629be7161800f613107bdfe89b9dcd
n=0x48fe8663bb4bc4e933f157a8821ce161fc4d11bc7ddfb738edd294e86c332182681deb02b3eb3c024d831319f38a0278a9c6d8b25d5994ee6b32d5d74857891e2ff800ac2753058eb2441f1477a4ac0bb8151a5938995233265d724da460f01f6fd63d87f7a22f7d0e10dbe48d4bf20eaa8995451b5cbc81bc1ea53ee4fe669
c=0x30f56c13ed32d320921464552857009dca669dd89eede49f95ca04869d7886c95396de19e6c9ed4727ce35efe05e215388038ac3fecdada6a167bda6ff8bff0f75d063b9b51f0980b7bbdd2eb176d3527fc031ebbe23d21bb4b9d3a5e220c1dde930b0a9c7e0893d316c903c5f334d39a542c22813ad2d16fb343ff1db86c55
q=Integer(n/p)
e=65537
d=inverse_mod(e,(p-1)*(q-1))
m=power_mod(c,d,n)
print hex(m)
得到结果:
4df014dcb1a99d224472318a5df5ec3a7abfcf0a758b91f85b3439286099bef44df89f777d8c902d0022b4e41e8e4d2fbe306560a41433a29c5d1d7b238e3042
0x0204 Generating challenge 3
提交第二关答案后,进入第三关。
[+]Generating challenge 3
[+]n=0x6ddee63f61f1e7a23f526feaa512641a56da9994a761b361c3643961e47e98cebd035e1f91817b2571b36417957221e26a8ff3f8e29ffa498f4c909f9d44c4cfa21a3528018118265224e8b7be2fb96f75796a5788dac8dcd3bbe8553ad39afe1d1c0467a43fb01e20c4caeed51fae2acd3f2b139c69a6b6905bc8aaab9e421bL
[+]e=3
[+]m=random.getrandbits(512)
[+]c=pow(m,e,n)=0x6a5375813a3cdd7215224122dfcbafbfe3f531159f46053a60a51b74cca1dc27f46eb2517cab8623b2880a2938d7f3bfd8855d8effee598f3c36fa20aca978cb9243ca7f82c0850e8b47544c25c5c4bfe22f086a8d0168eb724db80fdcbb6d314b3c34611d846df354dcf7f82f02f816929e06deaa8d4d3df312219e99b8d8eaL
[+]d=invmod(e,(p-1)*(q-1))
[+]d&((1<<512)-1)=0x245436307750f16960f2853d662c71ab44e7166bce8e9436a734c22a56fd769049417b95b2aa16473ca138790fd5f5c37b231749cbebd1dcb07865cc4f568cebL
[-]long_to_bytes(m).encode('hex')=
根据题目可知,其为d的高512位隐藏,且e为小指数,因此我根据ctf-wiki的提示,采取Partial Key Exposure Attack。
根据LLL Attack项目得到如下sage脚本:
def partial_p(p0, kbits, n):
PR.<x> = PolynomialRing(Zmod(n))
nbits = n.nbits()
f = 2^kbits*x + p0
f = f.monic()
roots = f.small_roots(X=2^(nbits//2-kbits), beta=0.3) # find root < 2^(nbits//2-kbits) with factor >= n^0.3
if roots:
x0 = roots[0]
p = gcd(2^kbits*x0 + p0, n)
return ZZ(p)
def find_p(d0, kbits, e, n):
X = var('X')
for k in xrange(1, e+1):
results = solve_mod([e*d0*X - k*X*(n-X+1) + k*n == X], 2^kbits)
for x in results:
p0 = ZZ(x[0])
p = partial_p(p0, kbits, n)
if p:
return p
if __name__ == '__main__':
n = 0x6ddee63f61f1e7a23f526feaa512641a56da9994a761b361c3643961e47e98cebd035e1f91817b2571b36417957221e26a8ff3f8e29ffa498f4c909f9d44c4cfa21a3528018118265224e8b7be2fb96f75796a5788dac8dcd3bbe8553ad39afe1d1c0467a43fb01e20c4caeed51fae2acd3f2b139c69a6b6905bc8aaab9e421b
e=3
d0 = 0x5436307750f16960f2853d662c71ab44e7166bce8e9436a734c22a56fd769049417b95b2aa16473ca138790fd5f5c37b231749cbebd1dcb07865cc4f568ceb
p= find_p(d0, 504, e, n)
print "found p: %d" % p
q = n//p
print inverse_mod(e, (p-1)*(q-1))
得到结果:
493f442a414befc17f8c4a9c6e0c42bc39e7110dc4ebccebd798264142ff1089d35794150baba76e4bcced650e4c1696f1b54d50971551865f88606a68d88334245436307750f16960f2853d662c71ab44e7166bce8e9436a734c22a56fd769049417b95b2aa16473ca138790fd5f5c37b231749cbebd1dcb07865cc4f568ceb
再运行以下脚本:
d=0x493f442a414befc17f8c4a9c6e0c42bc39e7110dc4ebccebd798264142ff1089d35794150baba76e4bcced650e4c1696f1b54d50971551865f88606a68d88334245436307750f16960f2853d662c71ab44e7166bce8e9436a734c22a56fd769049417b95b2aa16473ca138790fd5f5c37b231749cbebd1dcb07865cc4f568ceb
n=0x6ddee63f61f1e7a23f526feaa512641a56da9994a761b361c3643961e47e98cebd035e1f91817b2571b36417957221e26a8ff3f8e29ffa498f4c909f9d44c4cfa21a3528018118265224e8b7be2fb96f75796a5788dac8dcd3bbe8553ad39afe1d1c0467a43fb01e20c4caeed51fae2acd3f2b139c69a6b6905bc8aaab9e421b
c=0x6a5375813a3cdd7215224122dfcbafbfe3f531159f46053a60a51b74cca1dc27f46eb2517cab8623b2880a2938d7f3bfd8855d8effee598f3c36fa20aca978cb9243ca7f82c0850e8b47544c25c5c4bfe22f086a8d0168eb724db80fdcbb6d314b3c34611d846df354dcf7f82f02f816929e06deaa8d4d3df312219e99b8d8ea
m=power_mod(c,d,n)
print hex(m)
得到如下结果:
d6cfd54ae9471eea623ad47205d792f7aaa3483d5062d5747cf69a46917e6a1354dfe9e722fb0224d164de8f7235718b6f1ac2b4618a2e0f0ae88b594e688275
0x0205 challenge 4
输入第三关答案后。进入第四关:
[+]Generating challenge 4
[+]e=3
[+]m=random.getrandbits(512)
[+]n1=0x24cd001b4544bbcd8799797315f73589ff2794f6e0416d5a1bb279381080c3e66b68d3977dea86cf05cd6c4e7e20ad040f69e8c7597d5b5782f19c715d0740396f1c517b35e30e7120e7772cee73a6c1f608c1172e418290b40a22b4b8e7d4dece8a6fd32dbe929abfbef5db3b5ed733b6f8105d709113e5fb0f692e970df3b9L
[+]c1=pow(m,e,n1)=0xd5c66809308eb54dbf788b3239851fac3cec68c7873b8367c24fc376bc63ce88e94a02b8a31522aa61e1936fd805cf9c49ab35497e32f63d9587860c209752479a7832139505ecd46cc5f846b159ff92bba6a34006b025a1974b3dfe5fa9b2782e8795e34da49a894a7f2523b664dcebf718e21c0ec2bb9853a13f04977f90fL
[+]n2=0x52a24e7a47c4b03a33f67c5c837ad6fba53a593911f5ee3642c753e9d222e0b77a98e3abc56ee7cc8eeffcb62470d0d4e75b0e32a1f18041e347fdbe59a8bac5d4f3fd1a2157131bdd006c9ba914f476c23f8117cda14d754c9c30a816b404c27af9fc458d57300716d052082decca32ba4ba4ed81dee3a5f70e07ba952180f3L
[+]c2=pow(m,e,n2)=0x460c823d9612bdccbcc9912a5719a9c7562d2a6f2fd892411b4f6e46b681a35f0fe5b9e82ade4b324a7989ac01a284a2b70b1db060aee3c11199cb3a4811cc1daa5861be60fbc75a60f3f9d25b9282f68d92fe9a72cdad0c0b2b14176c050ff56c6d0781a36a4273286efeb594e7619b7663dce48da5fe2e5258e2f41f6af522L
[+]n3=0x4e8fe7c1d5e29ca415e766cee292392c85e64220a2b6902729525112db630aed0cb91d8daf182162419632154b1098c357cbd62af188ae24e3a23471b1187b5993a925792688c32df8f7e234cdda228732f23aabfed89a66a6addd79dd8245ed40e27499819ca5f584a648005485bfcdfa3188c74ee8cbc1f120c8c6db4077fL
[+]c3=pow(m,e,n3)=0x302cc39c296f6a2ffc2c512f5fcf9570ef91691644370b621be8a4828c72e2943aab3cb8cf700937638a4fc5c50f93c5290281514e1d356b3d17f19886dd6cefec8f64077257b6a987a5093046ef8b30f12db4ee91b00abf14d686f0ce2ac52c0768172952bf0fa7909f6b688eba6f0405751ff92d06f53dbc8e0e9c80c1e16L
[-]long_to_bytes(m).encode('hex')=
这其实就是个RSA的常规题,我们使用广播攻击python脚本:
# -*- coding: utf-8 -*-
from gmpy2 import invert, iroot
n1=0x24cd001b4544bbcd8799797315f73589ff2794f6e0416d5a1bb279381080c3e66b68d3977dea86cf05cd6c4e7e20ad040f69e8c7597d5b5782f19c715d0740396f1c517b35e30e7120e7772cee73a6c1f608c1172e418290b40a22b4b8e7d4dece8a6fd32dbe929abfbef5db3b5ed733b6f8105d709113e5fb0f692e970df3b9L
c1=0xd5c66809308eb54dbf788b3239851fac3cec68c7873b8367c24fc376bc63ce88e94a02b8a31522aa61e1936fd805cf9c49ab35497e32f63d9587860c209752479a7832139505ecd46cc5f846b159ff92bba6a34006b025a1974b3dfe5fa9b2782e8795e34da49a894a7f2523b664dcebf718e21c0ec2bb9853a13f04977f90fL
n2=0x52a24e7a47c4b03a33f67c5c837ad6fba53a593911f5ee3642c753e9d222e0b77a98e3abc56ee7cc8eeffcb62470d0d4e75b0e32a1f18041e347fdbe59a8bac5d4f3fd1a2157131bdd006c9ba914f476c23f8117cda14d754c9c30a816b404c27af9fc458d57300716d052082decca32ba4ba4ed81dee3a5f70e07ba952180f3L
c2=0x460c823d9612bdccbcc9912a5719a9c7562d2a6f2fd892411b4f6e46b681a35f0fe5b9e82ade4b324a7989ac01a284a2b70b1db060aee3c11199cb3a4811cc1daa5861be60fbc75a60f3f9d25b9282f68d92fe9a72cdad0c0b2b14176c050ff56c6d0781a36a4273286efeb594e7619b7663dce48da5fe2e5258e2f41f6af522L
n3=0x4e8fe7c1d5e29ca415e766cee292392c85e64220a2b6902729525112db630aed0cb91d8daf182162419632154b1098c357cbd62af188ae24e3a23471b1187b5993a925792688c32df8f7e234cdda228732f23aabfed89a66a6addd79dd8245ed40e27499819ca5f584a648005485bfcdfa3188c74ee8cbc1f120c8c6db4077fL
c3=0x302cc39c296f6a2ffc2c512f5fcf9570ef91691644370b621be8a4828c72e2943aab3cb8cf700937638a4fc5c50f93c5290281514e1d356b3d17f19886dd6cefec8f64077257b6a987a5093046ef8b30f12db4ee91b00abf14d686f0ce2ac52c0768172952bf0fa7909f6b688eba6f0405751ff92d06f53dbc8e0e9c80c1e16L
def broadcast(n1, n2 ,n3, c1, c2, c3):
n = [n1, n2, n3]
C = [c1, c2, c3]
N = 1
for i in n:
N *= i
Ni = []
for i in n:
Ni.append(N / i)
T = []
for i in xrange(3):
T.append(long(invert(Ni[i], n[i])))
X = 0
for i in xrange(3):
X += C[i] * Ni[i] * T[i]
m3 = X % N
m = iroot(m3, 3)
print hex(m)
return m[0]
m = broadcast(n1, n2, n3, c1, c2, c3)
得到结果:
0x399a618680da0812770e2e170cbbf9b8931d28b6d09faf89ad991178f599773c85a521e0f7d680683e9b0acd49dd4880f94bfa8fd2f2183ce84d1f65e8ae77b2
0x0206 challenge 5
去掉’0x'提交第四关答案后,进入第五关:
[+]Generating challenge 5
[+]n=0xa8d818c48c9a0a6c357d0e984531e0022da329fb6ff3f7e88648c2a0c01105eb41568c65882ee6227a23be7d27e3bed373b2d5b3d501714b6599e558c6f2cf7979306a85851912a58809c8a17da628793f62f893980726cf8835498ee5c0971c28960dad787c9a2b66687c9dc0f2b04a9936f2f3faf4038f3e532bd14c94e45L
[+]e=3
[+]m=random.getrandbits(512)
[+]c=pow(m,e,n)=0x4d440a1898f7d7e045b642153a9e43f14984f007b004cf2c041e563e7f49a035be1714729d54245ee49a4b2e7dea914f2eb3a1001ef7b812600b202ceaafc68e032a6d776392c25c346be4f38c5f1bbca0198faaaf5b2fd71bdb572ed855769b93b561bb97fa1b0d29d3e92663ef10d72e1ec175cb28b83114e0c69987e7a57L
[+]x=pow(m+1,e,n)=0x599287e72b4d639660f2b043c7f2a02a2f5d79ea5dd879f9b807e7fee60daedf2fc7303982ad717d3d0dd7f2ac821ea23d92b6204a1fb00d2616624ec79585600cc1ec4fa1572e2cd3cf367a849847bd04f667c56abbbbb32c1483cd9752f3b238d49fe298458b1d73f25104aa71aa1885e1a6d03e493dfa306a600986129f1L
[-]long_to_bytes(m).encode('hex')=
观察题目可以发现其中x=m+1,因此c2=(m+1)^e(mod n)。所以我们使用Coppersmith’s short-pad attack。参考LLL Attack,写如下sage脚本:
import gmpy2
from multiprocessing import Pool
from sage import *
n=7410398672722560790720195412993401264250509259159121796105267350180792373741542838871415199312173522565800560072992630537837754575150779598757210443323110194081932598317471346260969558920484459540182060007666127267727370086413280170139438680692829458488474163691892725501753042365356969290040607501093260869
c1=3391117201298737057930540144945344428964022685919328151081524910648485956998260143718374633761605827390670459959954533507239233704395789188855263526521980072778578103812123336770577337012297107553213154136185232528190261015718609645002472607986620587252457499667375357182558033603037327222069324423221901911
c2=3931241791319386441778385253836507249501525504922352393088733793325042043440257573258587153505776429990625550245746936343312940887074614924524203070012027115039334484614642261330909633837449408107886450303660255939009719402032831065068202114996826521021869947571695518377740372718347442283076616148872145393
e=3
# If two messages differ only by a known fixed difference between the two messages
# and are RSA encrypted under the same RSA modulus N
# then it is possible to recover both of them.
# Inputs are modulus, known difference, ciphertext 1, ciphertext2.
# Ciphertext 1 corresponds to smaller of the two plaintexts. (The one without the fixed difference added to it)
def franklinReiter(n,e,r,c1,c2):
R.<X> = Zmod(n)[]
f1 = X^e - c1
f2 = (X + r)^e - c2
# coefficient 0 = -m, which is what we wanted!
return Integer(n-(compositeModulusGCD(f1,f2)).coefficients()[0])
# GCD is not implemented for rings over composite modulus in Sage
# so we do our own implementation. Its the exact same as standard GCD, but with
# the polynomials monic representation
def compositeModulusGCD(a, b):
if(b == 0):
return a.monic()
else:
return compositeModulusGCD(b, a % b)
def CoppersmithShortPadAttack(e,n,C1,C2,eps=1/30):
"""
Coppersmith's Shortpad attack!
Figured out from: https://en.wikipedia.org/wiki/Coppersmith's_attack#Coppersmith.E2.80.99s_short-pad_attack
"""
import binascii
P.<x,y> = PolynomialRing(ZZ)
ZmodN = Zmod(n)
g1 = x^e - C1
g2 = (x+y)^e - C2
res = g1.resultant(g2)
P.<y> = PolynomialRing(ZmodN)
# Convert Multivariate Polynomial Ring to Univariate Polynomial Ring
rres = 0
for i in range(len(res.coefficients())):
rres += res.coefficients()[i]*(y^(res.exponents()[i][1]))
diff = rres.small_roots(epsilon=eps)
recoveredM1 = franklinReiter(n,e,diff[0],C1,C2)
print(recoveredM1)
print("Message is the following hex, but potentially missing some zeroes in the binary from the right end")
print(hex(recoveredM1))
print("Message is one of:")
for i in range(8):
msg = hex(Integer(recoveredM1*pow(2,i)))
if(len(msg)%2 == 1):
msg = '0' + msg
if(msg[:2]=='0x'):
msg = msg[:2]
print(msg)
def testCoppersmithShortPadAttack(eps=1/25):
from Crypto.PublicKey import RSA
import random
import math
import binascii
M = "flag{This_Msg_Is_2_1337}"
M = int(binascii.hexlify(M),16)
e = 3
nBitSize = 8192
key = RSA.generate(nBitSize)
#Give a bit of room, otherwhise the epsilon has to be tiny, and small roots will take forever
m = int(math.floor(nBitSize/(e*e))) - 400
assert (m < nBitSize - len(bin(M)[2:]))
r1 = random.randint(1,pow(2,m))
r2 = random.randint(r1,pow(2,m))
M1 = pow(2,m)*M + r1
M2 = pow(2,m)*M + r2
C1 = Integer(pow(M1,e,key.n))
C2 = Integer(pow(M2,e,key.n))
CoppersmithShortPadAttack(e,key.n,C1,C2,eps)
def testFranklinReiter():
p = random_prime(2^512)
q = random_prime(2^512)
n = p * q # 1024-bit modulus
e = 11
m = randint(0, n) # some message we want to recover
r = randint(0, n) # random padding
c1 = pow(m + 0, e, n)
c2 = pow(m + r, e, n)
print(m)
recoveredM = franklinReiter(n,e,r,c1,c2)
print(recoveredM)
assert recoveredM==m
print("They are equal!")
return True
CoppersmithShortPadAttack(e,n,c1,c2,1/60)
得到结果如下:
8760945220017073665638348940266356548841380706814597480982275482598344209034723012775263071671942280702671665704277225206032165364597583632095275298578540
Message is the following hex, but potentially missing some zeroes in the binary from the right end
a7469bb3a6c378a3cb77c91ddec75b568189732a64b18b9d607e2296914306c40de880ed81cd10ecb09c4186196e2aacb80e323fdf676ac4ba4c06e6a03be06c
0x0207 chellange 6
提交第五关答案,进入第六关:
[+]Generating challenge 6
[+]n=0xbadd260d14ea665b62e7d2e634f20a6382ac369cd44017305b69cf3a2694667ee651acded7085e0757d169b090f29f3f86fec255746674ffa8a6a3e1c9e1861003eb39f82cf74d84cc18e345f60865f998b33fc182a1a4ffa71f5ae48a1b5cb4c5f154b0997dc9b001e441815ce59c6c825f064fdca678858758dc2cebbc4d27L
[+]d=random.getrandbits(1024*0.270)
[+]e=invmod(d,phin)
[+]hex(e)=0x11722b54dd6f3ad9ce81da6f6ecb0acaf2cbc3885841d08b32abc0672d1a7293f9856db8f9407dc05f6f373a2d9246752a7cc7b1b6923f1827adfaeefc811e6e5989cce9f00897cfc1fc57987cce4862b5343bc8e91ddf2bd9e23aea9316a69f28f407cfe324d546a7dde13eb0bd052f694aefe8ec0f5298800277dbab4a33bbL
[+]m=random.getrandbits(512)
[+]c=pow(m,e,n)=0xe3505f41ec936cf6bd8ae344bfec85746dc7d87a5943b3a7136482dd7b980f68f52c887585d1c7ca099310c4da2f70d4d5345d3641428797030177da6cc0d41e7b28d0abce694157c611697df8d0add3d900c00f778ac3428f341f47ecc4d868c6c5de0724b0c3403296d84f26736aa66f7905d498fa1862ca59e97f8f866cL
[-]long_to_bytes(m).encode('hex')=
观察题目中d=random.getrandbits(1024*0.270)。
其中0.270与CopperSmith相关攻击中的beta相像。因此我采用Boneh and Durfee attack。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 = 0xbadd260d14ea665b62e7d2e634f20a6382ac369cd44017305b69cf3a2694667ee651acded7085e0757d169b090f29f3f86fec255746674ffa8a6a3e1c9e1861003eb39f82cf74d84cc18e345f60865f998b33fc182a1a4ffa71f5ae48a1b5cb4c5f154b0997dc9b001e441815ce59c6c825f064fdca678858758dc2cebbc4d27
# the public exponent
e = 0x11722b54dd6f3ad9ce81da6f6ecb0acaf2cbc3885841d08b32abc0672d1a7293f9856db8f9407dc05f6f373a2d9246752a7cc7b1b6923f1827adfaeefc811e6e5989cce9f00897cfc1fc57987cce4862b5343bc8e91ddf2bd9e23aea9316a69f28f407cfe324d546a7dde13eb0bd052f694aefe8ec0f5298800277dbab4a33bb
# the hypothesis on the private exponent (the theoretical maximum is 0.292)
delta = 0.27 # 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()
得到结果:
private key found: 776765455081795377117377680209510234887230129318575063382634593357724998207571
根据结果使用sage按照前面关卡的脚本常规求解m,得到m的结果为:
6b3bb0cdc72a7f2ce89902e19db0fb2c0514c76874b2ca4113b86e6dc128d44cc859283db4ca8b0b5d9ee35032aec8cc8bb96e8c11547915fc9ef05aa2d72b28
0x0208 flag
提交第六关答案后,得到flag:
flag
0x03 randomStudy
题目文件被我删了,现在服务器关了233
solution
这个题目比赛的时候没做出来,但是其关键就是把握住随机数种子。第一个是python的时钟同步获取随机数,第二个是java的Random包的伪随机数生成的算法攻击,第三个用工具randattack就行。第二个的伪随机数是利用线性同余算法生成。
其中java部分的random中next()描述为:
protected int next(int bits)
Generates the next pseudorandom number. Subclasses should override this, as this is used by all other methods.The general contract of next is that it returns an int value and if the argument bits is between 1 and 32 (inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be 0 or 1. The method next is implemented by class Random by atomically updating the seed to
(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1) and returning (int)(seed >>> (48 - bits)).
This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.2.1.
其中nextint()为:
public int nextInt() {
return next(32);
}
因此我们第二个只需要爆破其低16位就行。参考白帽100安全攻防实验室的脚本:
/*test.java*/
import java.io.PrintStream;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class test
{
public static long nextSeed(long seed){
return ((seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)) ;
}//java中Random的nextSeed伪随机数产生函数
public static int getNextInt(long seed, long bits ){
return (int)(seed >>> (48 - bits));
}//预测随机数
public static void main(String[] paramArrayOfString)
{
long t1 = Long.parseLong(paramArrayOfString[0]);
long t2 = Long.parseLong(paramArrayOfString[1]);
for(int i=0; i< 0x10000; i++){
if( t2 == getNextInt(nextSeed((t1 << 16) + i), 32)){//进行爆破
// System.out.println("find:");
// System.out.println(getNextInt(nextSeed((t1 << 16) + i), 32));
System.out.println(getNextInt(nextSeed(nextSeed((t1 << 16) + i)),32));
}
}
}
}
本题整个脚本:
import hashlib
import random
import time
import subprocess
from randcrack import RandCrack
from pwn import *
def proof(skr, skr_sha256):
for c1 in range(0x100):
for c2 in range(0x100):
for c3 in range(0x100):
shr = skr + chr(c1)+ chr(c2)+ chr(c3)
# print hashlib.sha256(shr).hexdigest()
if hashlib.sha256(shr).hexdigest() == skr_sha256.strip().lower():
print shr.encode("hex")
return shr.encode("hex")
def one(p, t):
random.seed(t)
randintdata = str(random.randint(0,2**64))
print "Try: ", randintdata
p.sendline(randintdata)
i = -10
time_num = 1
data = p.recvline()
print data
while "fail" in data:
time_num += 1
random.seed(t + i)
for x in range(time_num):
randintdata = str(random.randint(0,2**64))
print "Try: ", randintdata
p.sendline(randintdata)
i += 1
data = p.recvline()
if i == 8:
print "attack fail!"
exit()
def second(p, x1, x2):
x1 = x1.strip()
x2 = x2.strip()
print x1,x2
o = subprocess.check_output(["/usr/lib/jdk-12.0.1/bin/java, "test", x1, x2])
while len(o.split('\n')) == 1:
p.sendline("1")
p.recv()
print p.recvuntil("[-]")
data1 = p.recvuntil("\n").strip()
p.recvuntil("[-]")
data2 = p.recvuntil("\n").strip()
o = subprocess.check_output(["/usr/lib/jdk-12.0.1/bin/java", "test", data1, data2])
print "output:", o.split('\n')
p.sendline(o.split('\n')[0])
p.recv()
def third(p):
rc = RandCrack()
for i in range(624):
p.sendline("1")
oneline = p.recvline()
print i, int(oneline[10:-1])
this_num = int(oneline[10:-1])
rc.submit(this_num)
p.recvuntil('[-]')
this_num = rc.predict_randrange(0, 4294967295)
p.sendline(str(this_num))
print p.recv()
print p.recv()
print p.recv()
def attack():
p = remote("119.3.245.36", 23456)
p.recvuntil("hexdigest()=")
skr_sha256 = p.recvuntil("\n")
p.recvuntil("('hex')=")
shr5 = p.recvuntil("\n").strip().decode("hex")
p.recv()
p.sendline(proof(shr5, skr_sha256))
p.recv()
p.sendline("afd05b92f1c5fcabb0bf81dc9ffa21c1")
p.recv()
p.recv()
one(p, int(time.time()))
# print p.recvuntil("[-]")
print p.recvuntil("[-]")
data1 = p.recvuntil("\n")
p.recvuntil("[-]")
data2 = p.recvuntil("\n")
second(p, data1, data2)
print p.recv()
p.recv()
third(p)
attack()

浙公网安备 33010602011771号