Path: blob/master/coppersmiths_short_pad_attack.sage
117 views
# source code http://inaz2.hatenablog.com/entry/2016/01/20/022936123def short_pad_attack(c1, c2, e, n):45PRxy.<x,y> = PolynomialRing(Zmod(n))67PRx.<xn> = PolynomialRing(Zmod(n))89PRZZ.<xz,yz> = PolynomialRing(Zmod(n))101112g1 = x^e - c11314g2 = (x+y)^e - c2151617q1 = g1.change_ring(PRZZ)1819q2 = g2.change_ring(PRZZ)202122h = q2.resultant(q1)2324h = h.univariate_polynomial()2526h = h.change_ring(PRx).subs(y=xn)2728h = h.monic()293031kbits = n.nbits()//(2*e*e)3233diff = h.small_roots(X=2^kbits, beta=0.5)[0] # find root < 2^kbits with factor >= n^0.5343536return diff373839def related_message_attack(c1, c2, diff, e, n):4041PRx.<x> = PolynomialRing(Zmod(n))4243g1 = x^e - c14445g2 = (x+diff)^e - c2464748def gcd(g1, g2):4950while g2:5152g1, g2 = g2, g1 % g25354return g1.monic()555657return -gcd(g1, g2)[0]58596061if __name__ == '__main__':6263n = 1038124096894648862764750470447706092978858937201465717986545938854774571884253757860470177356914648657997512627769761742911527575060339484022236960215054708116651087074767257882962892557779146568004544517791173676052273643914833236668096505328604691763988162207078516399055003042088330224382340332642003989596465e = 3666768C1 = 93171069226345054453282791497552956124648758259437808418861936497001316100571007714441657575924792995558450218624404549685020653197703373316740619601237798767097489945475070578358267735227336714923294005575401009870189083953722133609708896081919406310819574986619506795660480642343263372422454378008703287136970C2 = 93143522343117772681525008104322171950867396472289974304663607670706389720173776746426398333565809516636341145225747389577086453484389792564558244404761784592962670560627243077828018566155065777902813678431330610967355664625880888070721419100791173624481368490824486301418716758179818667254917764001513399287172C3 = 102298788718908831383454512674839558060033746080468660252243145800572734468521296602058538109452538907204027081338987796558296639830757629468491322438048912956916198524821066676689795698612028521062296901313097979278633376983280108123961097977187251599033620058543603046291262367128490175209233898073639549204737475nbits = n.nbits()7677kbits = nbits//(2*e*e)7879print "padding lenght %d bytes " % (kbits/8)8081print "upper %d bits (of %d bits) is same" % (nbits-kbits, nbits)8283848586diff = short_pad_attack(C1, C2, e, n)8788#print "difference of two messages C1 and C2 is %d" % diff8990m = related_message_attack(C1, C2, diff, e, n)9192M1 = hex(int(m))[2:-1].decode('hex')9394M2 = hex(int(m+diff))[2:-1].decode('hex')9596print "Message of C1 is ", M19798print "Message of C2 is ", M299100101102diff = short_pad_attack(C1, C3, e, n)103104#print "difference of two messages C1 and C3 is ", diff105106M3 = hex(int(m+diff))[2:-1].decode('hex')107108print "Message of C3 is ", M3109110111print "Flag: ", M1[-6:] + M2[-6:] +M3[-6:]112113114