Classical Attacks on a Variant of the RSA Cryptosystem论文的赛题利用
1089607995167011 发表于 江苏 CTF 202浏览 · 2024-10-18 11:14

题目

import random
from Crypto.Util.number import *
from password import password
password1 = bytes_to_long(password[0:10])
password2 = bytes_to_long(password[10:15])
password3 = bytes_to_long(password[15:])
q1 = getPrime(80)
a,b,c = [random.randrange(1,q1-1) for _ in "_yi_gei_woli_giaogiao"][:3]
def add(P,Q):
    if P[0] != Q[0] and P[1] != Q[1]:
        t = ((Q[1]-P[1]) * inverse(Q[0]-P[0],q1)) %q1
    else:
        t = ((3*c*P[0]*P[0]+a) * inverse(2*b*P[1],q1))%q1

    x3 = b*inverse(c,q1)*t*t - P[0] - Q[0]
    y3 = t*(P[0] - x3) - P[1]
    return (x3%q1, y3%q1)

def mul(t, A, B=0):
    if not t: return B
    return mul(t//2, add(A,A), B if not t&1 else add(B,A) if B else A)

G = (543964449142803087188784, 288605946000947449279542)
Ps = []
ms = [random.randrange(1,q1-1) for _ in "giaoli_wo_ki_gay_giao"[:4]] + [password1]
for m in ms:
    P = mul(m,G)
    Ps.append(P)
print(f'Ps = {Ps}')
#Ps = [(260275824641779979588305, 726300335217221063663551), (263184922060743661751480, 611614193933496916037740), (582822220331206509336492, 481246655450613023120881), (372364178450359878096924, 693486907224438901452705), (227415654827717701646056, 348607835248429842358207)]

def get_good_prime(bit_length):
    while True:
        a = random.getrandbits(bit_length//2)
        b = random.getrandbits(bit_length//2)

        if b % 3 == 0:
            continue

        p = a ** 2 + 3 * b ** 2
        if p.bit_length() == bit_length and p % 3 == 1 and isPrime(p):
            return p

def addtion(P, Q, mod):
    m, n = P
    p, q = Q

    if p is None:
        return P
    if m is None:
        return Q

    if n is None and q is None:
        x = m * p % mod
        y = (m + p) % mod
        return (x, y)

    if n is None and q is not None:
        m, n, p, q = p, q, m, n

    if q is None:
        if (n + p) % mod != 0:
            x = (m * p + 2) * inverse(n + p, mod) % mod
            y = (m + n * p) * inverse(n + p, mod) % mod
            return (x, y)
        elif (m - n ** 2) % mod != 0:
            x = (m * p + 2) * inverse(m - n ** 2, mod) % mod
            return (x, None)
        else:
            return (None, None)
    else:
        if (m + p + n * q) % mod != 0:
            x = (m * p + (n + q) * 2) * inverse(m + p + n * q, mod) % mod
            y = (n * p + m * q + 2) * inverse(m + p + n * q, mod) % mod
            return (x, y)
        elif (n * p + m * q + 2) % mod != 0:
            x = (m * p + (n + q) * 2) * inverse(n * p + m * q + r, mod) % mod
            return (x, None)
        else:
            return (None, None)

def good_power(P, a, mod):
    res = (None, None)
    t = P
    while a > 0:
        if a & 1:
            res = addtion(res, t, mod)
        t = addtion(t, t, mod)
        a >>= 1
    return res

p = get_good_prime(512)
q = get_good_prime(512)
n = p * q

phi =(p**2 + p + 1) * (q **2 + q + 1)

d = getPrime(250)
e = inverse(d, phi)
m = (password2,password3)
c = good_power(m, e, n)

print(f"c = {c}")
print(f"n = {n}")
print(f"e = {e}")
#c = (85422492752594163973525590153185181637578599526748527548916818661479717263661942043798519054634085790883203742143922909753155434484575316617409323425452920098106836753343255561397020191055166143284978002585043504528894342913998542611098251874319443218091798571063752406953498370967948413185742430124774364502, 76360473484928457783902531276059575220337561977824728338226901050505962483334908329971039234703811585714576796248193194224345311394246955572476959264834718452867915059519112273971322043676881006521735191342236986562040370170197311513561834788296920114495955011761008433746711656717672295490499621868087698727)
#n = 132719529494169666440015361510648436961564899266678472070578908438683877891624167098238871100680873610907493030493888543311583489467977492321159269370993104122316666862684984291699054526052448281045072084505401048771540969410719257800557252293084614152823911423359393963461618267528202871491263273689330662483
#e = 11129124355754297663162018546827275323752484161275828202691755264373860584802812666274619573801591775394317054892274391559877638968525372552912822620960106630890646377568381371715175233391190130896052686700941699773696737503798559366444705210907918989156659958714227911553806284829827584317491856812837076773878027948902531976851782851828778907966453369256525240545004196650478844079204128934633946462554325449608508882698599949761290061856624339283077816678434588316049724978427174141375678236660470842166757271021085154473717712706728832602385344078603418705101145889874790221291898011811923959932221790456898299847

这道题分为两部分

第一部分password1

groebner基求q

G = (543964449142803087188784, 288605946000947449279542)
Ps = [(260275824641779979588305, 726300335217221063663551), (263184922060743661751480, 611614193933496916037740), (582822220331206509336492, 481246655450613023120881), (372364178450359878096924, 693486907224438901452705), (227415654827717701646056, 348607835248429842358207)]
v = ([G] + Ps)

C1,C2,C3,C4,C5,C6 = v
P.<a,b,c>=PolynomialRing(ZZ)
f1 = a*C1[0]^3 + b*C1[0] + c - C1[1]^2
f2 = a*C2[0]^3 + b*C2[0] + c - C2[1]^2
f3 = a*C3[0]^3 + b*C3[0] + c - C3[1]^2
f4 = a*C4[0]^3 + b*C4[0] + c - C4[1]^2
f5 = a*C5[0]^3 + b*C5[0] + c - C5[1]^2
f6 = a*C6[0]^3 + b*C6[0] + c - C6[1]^2
F = [f1,f2,f3,f4,f5,f6]
Ideal = Ideal(F)
I = Ideal.groebner_basis()
print(I)
#[a + 226820338772807027243218, b + 773167489336543856487958, c + 758871032836012559341025, 813190268037982043592049]

求参数

q=813190268037982043592049
a,b,c = -226820338772807027243218%q,-773167489336543856487958%q,-758871032836012559341025%q
print(a,b,c)
#a,b,c = (586369929265175016348831 , 40022778701438187104091 , 54319235201969484251024)

对x轴向缩放,转换成标准方程

#令x = kx ,k^3 = a 求k
P.<x> = PolynomialRing(GF(q))  
f = x^3 - a 
print(f.roots())
#[(475621888743226821656636, 1),(232592821046908396945406, 1),(104975558247846824990007, 1)]
k=104975558247846824990007

#y^2 = (kx)^3 + A*kx + B 
A = b*pow(k,-1,q) 
B = c
x = G[0]*k%q
y = G[1]

#点G,m*G缩放后放入方程
E = EllipticCurve(GF(q), [A, B])
P = E(G[0]*k%q,G[1])
Q = E(Ps[-1][0]*k%q, Ps[-1][1])

求password1

#求私钥
m = discrete_log(Q, P, operation='+') 
long_to_bytes(int(m))

#估计这个G是曲线某个循环子群的生成元,阶是order的某个因子
E.order() 
v = E.order()//2
for i in range(100):
    print(long_to_bytes(m+i*v))# ylcTf_e_or

第二部分

分解n

#sage
'''
1,素数结构 p = a^2 + 3* b^2 ,p%3 == 1
2,phi的结构phi = (p^2+p+1)*(q^2+q+1)
3,给出N,e,c 
论文:https://eprint.iacr.org/2021/1160.pdf 
'''
import time


"""
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


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 = 132719529494169666440015361510648436961564899266678472070578908438683877891624167098238871100680873610907493030493888543311583489467977492321159269370993104122316666862684984291699054526052448281045072084505401048771540969410719257800557252293084614152823911423359393963461618267528202871491263273689330662483
e = 11129124355754297663162018546827275323752484161275828202691755264373860584802812666274619573801591775394317054892274391559877638968525372552912822620960106630890646377568381371715175233391190130896052686700941699773696737503798559366444705210907918989156659958714227911553806284829827584317491856812837076773878027948902531976851782851828778907966453369256525240545004196650478844079204128934633946462554325449608508882698599949761290061856624339283077816678434588316049724978427174141375678236660470842166757271021085154473717712706728832602385344078603418705101145889874790221291898011811923959932221790456898299847 

X = 1 << 469
Y = 2 * inthroot(Integer(2 * N), 2)

res = attack(N, e, 4, 2, X, Y)
print(res) # gives k and p + q, the rest is easy
#(1125163666703694333973117091455705469002316083331723899087174704496395614550, 23040813046255534346226676736106869543317554704215464262468424340899871881209898389248327260469621610693207195451361474904828350833031775951884213769667324)

b, c = res[1], N
Dsqrt =  inthroot(Integer(b^2-4*c),2)
p, q = (b + Dsqrt) // 2, (b - Dsqrt) // 2
assert p * q == N
print(p,q)

解password2和3

from gmpy2 import *
from Crypto.Util.number import *
p,q=11535800156719048931347276045879377428643243582810776040089157673637898260385736466169737110946935313493516144396403906845807153884435472856105926366322231, 11505012889536485414879400690227492114674311121404688222379266667261973620824161923078590149522686297199691051054957568059021196948596303095778287403345093
def addtion(P, Q, mod):
    m, n = P
    p, q = Q

    if p is None:
        return P
    if m is None:
        return Q

    if n is None and q is None:
        x = m * p % mod
        y = (m + p) % mod
        return (x, y)

    if n is None and q is not None:
        m, n, p, q = p, q, m, n

    if q is None:
        if (n + p) % mod != 0:
            x = (m * p + 2) * inverse(n + p, mod) % mod
            y = (m + n * p) * inverse(n + p, mod) % mod
            return (x, y)
        elif (m - n ** 2) % mod != 0:
            x = (m * p + 2) * inverse(m - n ** 2, mod) % mod
            return (x, None)
        else:
            return (None, None)
    else:
        if (m + p + n * q) % mod != 0:
            x = (m * p + (n + q) * 2) * inverse(m + p + n * q, mod) % mod
            y = (n * p + m * q + 2) * inverse(m + p + n * q, mod) % mod
            return (x, y)
        elif (n * p + m * q + 2) % mod != 0:
            x = (m * p + (n + q) * 2) * inverse(n * p + m * q + r, mod) % mod
            return (x, None)
        else:
            return (None, None)

def good_power(P, a, mod):
    res = (None, None)
    t = P
    while a > 0:
        if a & 1:
            res = addtion(res, t, mod)
        t = addtion(t, t, mod)
        a >>= 1
    return res
N = 132719529494169666440015361510648436961564899266678472070578908438683877891624167098238871100680873610907493030493888543311583489467977492321159269370993104122316666862684984291699054526052448281045072084505401048771540969410719257800557252293084614152823911423359393963461618267528202871491263273689330662483
e = 11129124355754297663162018546827275323752484161275828202691755264373860584802812666274619573801591775394317054892274391559877638968525372552912822620960106630890646377568381371715175233391190130896052686700941699773696737503798559366444705210907918989156659958714227911553806284829827584317491856812837076773878027948902531976851782851828778907966453369256525240545004196650478844079204128934633946462554325449608508882698599949761290061856624339283077816678434588316049724978427174141375678236660470842166757271021085154473717712706728832602385344078603418705101145889874790221291898011811923959932221790456898299847
c=(85422492752594163973525590153185181637578599526748527548916818661479717263661942043798519054634085790883203742143922909753155434484575316617409323425452920098106836753343255561397020191055166143284978002585043504528894342913998542611098251874319443218091798571063752406953498370967948413185742430124774364502, 76360473484928457783902531276059575220337561977824728338226901050505962483334908329971039234703811585714576796248193194224345311394246955572476959264834718452867915059519112273971322043676881006521735191342236986562040370170197311513561834788296920114495955011761008433746711656717672295490499621868087698727)
phi = (p**2 + p + 1)*(q**2 + q + 1)
d = invert(mpz(e),mpz(phi))
m = good_power(c,d,N)
print(m)
pas2=409403877231
pas3=10673380708147344593726104065762264760478541144788135806
print(long_to_bytes(pas2))#_R_go
print(long_to_bytes(pas3))#oooood_game_114514giao~
#或者
flag = b''.join([long_to_bytes(v)[:24] for v in m])
print(flag)

e约等于n^2可以用连分数来解

#sage
c = (85422492752594163973525590153185181637578599526748527548916818661479717263661942043798519054634085790883203742143922909753155434484575316617409323425452920098106836753343255561397020191055166143284978002585043504528894342913998542611098251874319443218091798571063752406953498370967948413185742430124774364502, 76360473484928457783902531276059575220337561977824728338226901050505962483334908329971039234703811585714576796248193194224345311394246955572476959264834718452867915059519112273971322043676881006521735191342236986562040370170197311513561834788296920114495955011761008433746711656717672295490499621868087698727)
n = 132719529494169666440015361510648436961564899266678472070578908438683877891624167098238871100680873610907493030493888543311583489467977492321159269370993104122316666862684984291699054526052448281045072084505401048771540969410719257800557252293084614152823911423359393963461618267528202871491263273689330662483
e = 11129124355754297663162018546827275323752484161275828202691755264373860584802812666274619573801591775394317054892274391559877638968525372552912822620960106630890646377568381371715175233391190130896052686700941699773696737503798559366444705210907918989156659958714227911553806284829827584317491856812837076773878027948902531976851782851828778907966453369256525240545004196650478844079204128934633946462554325449608508882698599949761290061856624339283077816678434588316049724978427174141375678236660470842166757271021085154473717712706728832602385344078603418705101145889874790221291898011811923959932221790456898299847
n=n**2
cc=continued_fraction(e/n)
for i in range(1000):
    k=cc.numerator(i)
    d=cc.denominator(i)
    if k==0:
        continue
    if (e*d-1)%k==0   and k!=1:
        print(k)
        print(d)

#python
import sympy
from Crypto.Util.number import *
c = (85422492752594163973525590153185181637578599526748527548916818661479717263661942043798519054634085790883203742143922909753155434484575316617409323425452920098106836753343255561397020191055166143284978002585043504528894342913998542611098251874319443218091798571063752406953498370967948413185742430124774364502, 76360473484928457783902531276059575220337561977824728338226901050505962483334908329971039234703811585714576796248193194224345311394246955572476959264834718452867915059519112273971322043676881006521735191342236986562040370170197311513561834788296920114495955011761008433746711656717672295490499621868087698727)

k=1125163666703694333973117091455705469002316083331723899087174704496395614550
d=1780837823989905992221702038979719520909263329669933329426659150044417751533
p,q=sympy.symbols('p q')
n = 132719529494169666440015361510648436961564899266678472070578908438683877891624167098238871100680873610907493030493888543311583489467977492321159269370993104122316666862684984291699054526052448281045072084505401048771540969410719257800557252293084614152823911423359393963461618267528202871491263273689330662483
e = 11129124355754297663162018546827275323752484161275828202691755264373860584802812666274619573801591775394317054892274391559877638968525372552912822620960106630890646377568381371715175233391190130896052686700941699773696737503798559366444705210907918989156659958714227911553806284829827584317491856812837076773878027948902531976851782851828778907966453369256525240545004196650478844079204128934633946462554325449608508882698599949761290061856624339283077816678434588316049724978427174141375678236660470842166757271021085154473717712706728832602385344078603418705101145889874790221291898011811923959932221790456898299847
phi=(e*d-1)//k
d=inverse(e,phi)
#主要是解phi,p,q用不到

def addtion(P, Q, mod):
    m, n = P
    p, q = Q

    if p is None:
        return P
    if m is None:
        return Q

    if n is None and q is None:
        x = m * p % mod
        y = (m + p) % mod
        return (x, y)

    if n is None and q is not None:
        m, n, p, q = p, q, m, n

    if q is None:
        if (n + p) % mod != 0:
            x = (m * p + 2) * inverse(n + p, mod) % mod
            y = (m + n * p) * inverse(n + p, mod) % mod
            return (x, y)
        elif (m - n ** 2) % mod != 0:
            x = (m * p + 2) * inverse(m - n ** 2, mod) % mod
            return (x, None)
        else:
            return (None, None)
    else:
        if (m + p + n * q) % mod != 0:
            x = (m * p + (n + q) * 2) * inverse(m + p + n * q, mod) % mod
            y = (n * p + m * q + 2) * inverse(m + p + n * q, mod) % mod
            return (x, y)
        elif (n * p + m * q + 2) % mod != 0:
            x = (m * p + (n + q) * 2) * inverse(n * p + m * q + r, mod) % mod
            return (x, None)
        else:
            return (None, None)

def good_power(P, a, mod):
    res = (None, None)
    t = P
    while a > 0:
        if a & 1:
            res = addtion(res, t, mod)
        t = addtion(t, t, mod)
        a >>= 1
    return res
print(good_power(c,d,n))

f1=p*q-n
f2=(p**2 + p + 1) * (q **2 + q + 1)-phi
ret=sympy.solve([f1,f2],[p,q])
p=ret[0][0]
q=ret[0][1]
print(n%p)
print(n%q)

ylcTf_e_or_R_gooooood_game_114514giao~

0 条评论
某人
表情
可输入 255