G
N
I
D
A
O
L

RSA题型归纳

RSA题型

n = p * q

n不大,容易被分解

在线分解大素数: http://www.factordb.com/index.php

yafu分解
p,q 相差不大

yafu-x64.exe factor(number)

共用p

不同的n之间存在非1的公因数

\[p = gcd(n1,n2) \]

代码

def FindP(num_array):
    num = len(num_array)
    result=[]
    for i in range(num-1):
        for j in range(i+1,num):
            temp = gcd(num_array[i],num_array[j])
            if(temp!=1):
                result.append((num_array[i],num_array[j],temp))

    return result

共模攻击

e1,e2已知

\[c_1=m^{e1}\ mod\ n\space\ \ \ \ \ \ \ c_2=m^{e2}\ mod\ n \]

\[gcd(e_1,e_2)=1\\ a*e_1\ +\ b*e_2\ =\ 1\ \]

\[m\ =m^{e_1*a+e_2*b}\ \ \equiv\ c_1^a*c_2^b \ mod\ \ n\ \]

payload

def sameN(e1,c1,e2,c2,n):
    if(gcd(e1,e2)!=1):
        print('e1,e2 不互素,解密失败')
        exit(0)

    r = gcdext(e1, e2)
    m1 = powmod(c1, r[1], n)
    m2 = powmod(c2, r[2], n)
    m = (m1 * m2) % n
    print(long_to_bytes(m))

    return m

\(e1=p\ ,\ e2=q\)

已知 n,c1,c2 且 \(m<n^{\frac{1}{k}}\) k为多项式的阶数

Coppersmith定理

在一个e阶的mod n多项式f(x)中(多项式环),如果有一个根小于\(n^{\frac{1}{e}}\),就可以运用一个\(O(log n)\)的算法求出这些根

推导

\[c1=m^{e1}\ mod\ n\\c2=m^{e2}\ mod\ n \\ m^{e1}\equiv m\ mod\ e1 \\ m^{e2}\equiv \ m\ mod\ e2 \\ \therefore c1=m+i{'}*e1+k*n \\ \therefore c2=m+j{'}*e2+t*n \\ \because e1=p\ \ \ e2=q \\ \therefore c1=m+i*p\ \ \ c2=m+j*q \\ \therefore c1*c2=m^{2}+(i*j*p*q)+(i*p+j*q)*m \\ \therefore m*(c1+c2)=2*m^2+(i*p+j*q)*m \\ \therefore m^2+c1*c2-m*(c1+c2)=k*n\equiv 0\ \ mod\ n \]

payload

PR.<m> = PolynomialRing(Zmod(n))
f = m^2-(c1+c2)*m+(c1*c2)
x0 = f.small_roots(X=2^400) #X 根的最大值,界限

低指数攻击

低加密指数

e很小

\[m^e=c+i*n \]

\[m\ =\ \sqrt[e]{c+i*n} \]

代码

def small_e(e, n, c):
    print(time.asctime(), "Let's waiting...")
    for k in range(200000000):
        if iroot(c + n * k, e)[1] == 1:
            print(time.asctime(), "...done!")
            m = iroot(c + n * k, e)[0]
            print(long_to_bytes(m))

            return  m

低解密指数

e相对于n很大

借助RSAwienerHacker项目

from RSAwienerHacker import hack_RSA
d = hack_RSA(e,n)

next_prime

下一个素数

p,q 很相近,可以借助yafu分解求得 p,q

#建议cmd,powershell测试存在问题
yafu-x64.exe factor(xxxxx)

gcd(e,phi)!=1

\(e\ !=\ 2^t\)

\[gcd(e,phi)=k \]

\[k*e'=\ e \]

\[m^e=m^{k*e'}=(m^k)^{e'} \ \ mod \ \ n \]

\[flag = \sqrt[k]{m^k} \]

# k = gcd(e,phi)  
# e' = e//k

1️⃣直接开方

求出的m'开k次方   (仅适用于k较小,例如k=2)

2️⃣CRT

[De1CTF2019]babyrsa

通过模因子,CRT,转化为 e为较小偶数

3️⃣e为phi的因子

[NCTF2019]easyRSA e=4919 嫖的脚本,改写为python3版本

# 破解时间较长
def e_phi(e,c,p,q,flag_prefix):
    '''
    flag_prefix = b'buuctf' 二进制字符串
    '''
    n = p*q
    c_p = powmod(c,(1+3307*(p-1)//e)//e,p)
    print("find one")
    C1=solution(p,c_p)
    print("find all")
    c_q = powmod(c,(1+(2649*(q-1)//e))//e,q)
    print("find another")
    C2=solution(q,c_q)
    print("find all")
    a = invert(p,q)
    b = invert(q,p)
    #x = (b*q*c_p+a*p*c_q)%n
    flag=0
    for i in C1:
        for j in C2:
            flag+=1
            if flag%1000000 == 0:
                print(flag)
            x = (b*q*i+a*p*j)%n
            if(flag_prefix in n2s(x)):
                print(n2s(x))

                
def n2s(x):
    try:
        try:
            # flag = hex(x)[2:].decode("hex")
            flag = long_to_bytes(x)
        except:
            # flag = hex(x)[2:-1].decode("hex")
            flag = long_to_bytes(x)
    except:
        flag=''
    return flag


def onemod(p,r):
    t=p-2
    while powmod(t,(p-1)//r,p)==1: t-=1
    return powmod(t,(p-1)//r,p)


def solution(p,root):
    g=onemod(p,0x1337)
    may=[]
    for i in range(0x1337):
        if i%100 == 0:
            print(i)
        may.append(root*pow(g,i,p)%p)
    return may

\(e \ =\ 2^t\)

且e比较小(e = 256)

payload

m = sympy.nthroot_mod(c,e,n,all_roots=True)
for i in m:
    print(long_to_bytes(i))

或者 sage

#多项式环求解
e = 256
n=107316975771284342108362954945096489708900302633734520943905283655283318535709
c = 19384002358725759679198917686763310349050988223627625096050800369760484237557
R.<x>=Zmod(n)[]
f = x^e-c
f.roots()

dp,dq,p,q

# 已知dp,dq,p,q,c
dp = d%(p-1)
dq = d%(q-1)

\[m = m_1\ +\ (((m_2-m_1)*q^{-1})\ mod\ p)*q\ \ \ \ mod \ \ n \]

paylaod

def dpdq(dp,dq,p,q,c):
    n = p*q
    m1 = powmod(c,dq,q)
    m2 = powmod(c,dp,p)
    qi = invert(q,p)
    m = (m1+(((m2-m1)*qi)%p)*q)%n

    return long_to_bytes(m)

dp泄露

# 已知 dp,e,n,c

\[dp*e = (k_2*(q-1)-k_1)*(p-1)+1 \]

\[p = (dp*e-1)//i\ +1 \]

i只需(1,e)即可

payload

def dpLeak(dp,e,n,c):
    for i in range(1,e):
        p = (dp*e-1)//i+1
        if(n%p==0):
            q = n//p
            phi = (p-1)*(q-1)
            d = invert(e,phi)
            m = powmod(c,d,n)
            print(long_to_bytes(m))

            return m

广播攻击

//给了一堆 (n,c)对, n不同且素数,e已知  且满足(n,c)对的数目>=e

中国剩余定理

\[\begin{cases} x \ \equiv\ b_1\ \mod\ m_1\\ x \ \equiv\ b_2\ \mod\ m_2\\ x \ \equiv\ b_3\ \mod\ m_3\\ ...\\ x \ \equiv\ b_n\ \mod\ m_n\\ \end{cases} \]

payload

def CRT(m,b):
    '''
    m: n   list
    b: c   list
    '''
    M = 1
    for i in m:
        M*=i
    sum = 0
    for i in range(len(m)):
        mi = M//m[i]
        miphi=invert(mi,m[i])
        sum+=miphi*mi*b[i]
    sum = sum%M

    return sum    # return x

CRT求解得到 \(x\), 因为 \(m<n_i\), 所以 \(x<M\)所以 \(m^e=x\)

所以 \(m=\sqrt[e]x\)

payload

x = CRT(n,c)
m = iroot(x,e)[0]
print(long_to_bytes(m))

已知低位攻击

已知d的低位

知道d的低位,低位约为n的位数的1/4就可以恢复d

payload

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 range(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 = 
    e = 
    # 仅需d的低位,高位不计入
    d = 
    
    nbits = n.nbits()
    kbits = d.nbits()
    d0 = d & (2^kbits-1)
    print("lower %d bits (of %d bits) is given" % (kbits, nbits))

    p = find_p(d0, kbits, e, n)
    print("p = %d" % p)
    q = n//p
    # print("d0 = %d" % d)
    print("d = %d" % inverse_mod(e, (p-1)*(q-1)))

已知高位攻击

已知m的高位,存在小值根

payload

e = 
n = 
c = 
#暂时的m,不准确的低位也算入
m_b = 
#小值根的位数
kbits=400

PR.<x> = PolynomialRing(Zmod(n))
f = (x + m_b)^e-c
#求得的小值根
x0 = f.small_roots(X=2^kbits, beta=1)[0]
#相加即为m
m = m_b + int(x0)
print('[-]x is ' + hex(int(x0)))
print('[-]m is: ' + str(m))
print('[-]hex(m) is: ' + '{:x}'.format(m))

明文高位相同

m1,m2高位相同

payload

def short_pad_attack(c1, c2, e, n):
    PRxy.<x,y> = PolynomialRing(Zmod(n))
    PRx.<xn> = PolynomialRing(Zmod(n))
    PRZZ.<xz,yz> = PolynomialRing(Zmod(n))

    g1 = x^e - c1
    g2 = (x+y)^e - c2

    q1 = g1.change_ring(PRZZ)
    q2 = g2.change_ring(PRZZ)

    h = q2.resultant(q1)
    h = h.univariate_polynomial()
    h = h.change_ring(PRx).subs(y=xn)
    h = h.monic()

    kbits = n.nbits()//(2*e*e)
    diff = h.small_roots(X=2^kbits, beta=0.5)[0]  # find root < 2^kbits with factor >= n^0.5

    return diff

def related_message_attack(c1, c2, diff, e, n):
    PRx.<x> = PolynomialRing(Zmod(n))
    g1 = x^e - c1
    g2 = (x+diff)^e - c2

    def gcd(g1, g2):
        while g2:
            g1, g2 = g2, g1 % g2
        return g1.monic()

    return -gcd(g1, g2)[0]


if __name__ == '__main__':
    n = 
    e = 
    c1=
    c2=


    diff = short_pad_attack(c1, c2, e, n)
    print("difference of two messages is %d" % diff)

    #print m1
    m1 = related_message_attack(c1, c2, diff, e, n)
    print('m1 =',m1)
    #print m2
    print('m2 =',m1 + diff)
    print('diff =',diff)

已知p的高位

已知p的高位数为p的总位数的约1/2即可

payload

from sage.all import *

n = 0x639386F4941D1511D89A9D19DC4731188D3F4D2D04623FB26F5A85BB3A54747BCBADCDBD8E4A75747DB4072A90F62DCA08F11AC276D7588042BEFA504DCD87CD3B0810F1CB28168A53F9196CDAF9FD1D12DCD4C375EB68B67A8EFCCEC605C57C736943170FEF177175F696A0F6123B993E56FFBF1B62435F728A0BAC018D0113
#已知的p的高位,低位不计入
p = 0x635c3782d43a73d70465979599f65622c7b4242a2d623459337100000000004973c619000
#p的总位数
pbits = 512

for i in range(0,5000):
  p4 = p
  p4 = p4 + int(hex(i),16)
  kbits = pbits - p4.nbits()  #未知需要爆破的比特位数
  p4 = p4 << kbits 
  PR.<x> = PolynomialRing(Zmod(n))
  f = x + p4
  roots = f.small_roots(X=2^kbits, beta=0.4) #进行爆破

  #print roots
  if roots:        #爆破成功,求根
    p = p4+int(roots[0])
    print('p =',p)
    break

e,d,n

已知 e*d,n 求出 p,q

def exd2pq(t, n):
    '''
    根据 e*d,n 求出 p,q
    t = e*d
    '''
    k = t - 1
    while True:
        g = random.randint(2, n-1)
        t = k
        while True:
            if t % 2 != 0:
                break
            t //= 2
            x = pow(g, t, n)
            if x > 1 and gcd(x-1, n) > 1:
                p = gcd(x-1, n)
                print('find it')
                return (p, n//p)
def solvepq(phi,n):
    p = Int('p')
    q = Int('q')
    s = Solver()
    try:
        s.add((p-1)*(q-1) == phi)
        s.add(p * q == n)
        s.check()
        p,q = s.model()
        print(s.model())
        return p,q
    except:
        return 0


def ed2pq(e, d, n):
    '''
    根据 e,d,n 求出 p,q
    '''
    t = e * d - 1
    bit_num = t.bit_length() - n.bit_length()
    possible = []
    mc=[]
    for i in range(pow(2,bit_num-1), pow(2, bit_num + 1)):
        if (t % i == 0):
            possible.append(t // i)
            mc.append(i)
    # print(len(possible))
    for i in possible:
        r = solvepq(int(i), n)
        if(r!=0):
            break

dp,p,b,e,c

已知 \(dp,p,b,e,c\)

\(n = p^b*q\)

payload

def dpp(c,e,dp,p,b):
    mp0 = powmod(c,dp-1,p)
    mp = powmod(c,dp,p)
    for i in range(1,b-2):
        x = (c-pow(mp,e))%(pow(p,i+1))
        y = x * mp0 * (invert(e,p))%(pow(p,i+1))
        mp = mp+y
    print(long_to_bytes(mp))

攻击条件

使用同一公钥对两个具有某种线性关系的消息 M1 与 M2 进行加密

\[M_2=\frac{b}{a}\frac{C_1+2a^3C_2-b^3}{C_1-a^3C_2+2b^3} \]

payload

def getmessage(a, b, c1, c2, n):
    b3 = powmod(b, 3, n)
    part1 = b * (c1 + 2 * c2 * a**3 - b3) % n
    part2 = a * (c1 - c2 * a**3 + 2 * b3) % n
    part2 = invert(part2, n)
    return part1 * part2 % n


def related_Message(a, b, c1, c2, n, offset):
    '''
    M1 = a*M2 + b
    offset : M2 = M + offset
    '''
    message = getmessage(a, b, c1, c2, n) - offset
    print(long_to_bytes(message))
    return message

Boneh Durfee

比RSAwienerHacker攻击更强,可以解决\(d<n^{0.292}\)的问题

sage payload

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)
    #
	# 修改此处 N,e,c 以及 delta 即可
    # the modulus
    N = 0xbadd260d14ea665b62e7d2e634f20a6382ac369cd44017305b69cf3a2694667ee651acded7085e0757d169b090f29f3f86fec255746674ffa8a6a3e1c9e1861003eb39f82cf74d84cc18e345f60865f998b33fc182a1a4ffa71f5ae48a1b5cb4c5f154b0997dc9b001e441815ce59c6c825f064fdca678858758dc2cebbc4d27
    # the public exponent
    e = 0x11722b54dd6f3ad9ce81da6f6ecb0acaf2cbc3885841d08b32abc0672d1a7293f9856db8f9407dc05f6f373a2d9246752a7cc7b1b6923f1827adfaeefc811e6e5989cce9f00897cfc1fc57987cce4862b5343bc8e91ddf2bd9e23aea9316a69f28f407cfe324d546a7dde13eb0bd052f694aefe8ec0f5298800277dbab4a33bb
    # the cipher
    c = 0xe3505f41ec936cf6bd8ae344bfec85746dc7d87a5943b3a7136482dd7b980f68f52c887585d1c7ca099310c4da2f70d4d5345d3641428797030177da6cc0d41e7b28d0abce694157c611697df8d0add3d900c00f778ac3428f341f47ecc4d868c6c5de0724b0c3403296d84f26736aa66f7905d498fa1862ca59e97f8f866c
    
    # the hypothesis on the private exponent (the theoretical maximum is 0.292)
    delta = .28  # 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)
        m = pow(c, d, N)
        print('[-]d is ' + str(d))
        print('[-]m is: ' + str(m))
        print('[-]hex(m) is: ' + '{:x}'.format(int(m)))
        #print('[-]str(m) is: ' + '{:x}'.format(int(m)).decode('hex'))
        #print('plian is ',long_to_bytes(m))
    else:
        print("[!]no solution was found!")
        print('[!]All Done!')

    if debug:
        print("[!]Timer: %s s" % (time.time() - start_time))
        print('[!]All Done!')


if __name__ == "__main__":
    example()
posted @ 2021-12-28 17:26  buersec  阅读(988)  评论(0)    收藏  举报