Search code examples
pythoncryptographydiscrete-mathematicselliptic-curve

Brute force attack for discrete log problem (Python)


I'm still learning Python and trying to wrap my mind around brute force attacks using for loops in Python. I made this for loop to try every number from 0 to 999999 and store it in the variable n. Instead of letting my for look run forever, I want it to stop at a specific scalarmult(n,P) value. For example, let's say I want the for loop to end when print(scalarmult(n,P)) prints, (111111,2334897).

p = 1000003
class Fp:
    def __init__(self,x):
        self.int = x % p
    def __str__(self):
        return str(self.int)
    __repr__ = __str__
Fp.__eq__ = \
    lambda a,b: a.int == b.int
Fp.__add__ = \
    lambda a,b: Fp(a.int + b.int)
Fp.__sub__ = \
    lambda a,b: Fp(a.int - b.int)
Fp.__mul__ = \
    lambda a,b: Fp(a.int * b.int)

def clockadd(P1, P2):
    x1,y1 = P1
    x2,y2 = P2
    x3 = x1*y2+y1*x2
    y3 = y1*y2-x1*x2
    return x3,y3

P = (Fp(1000),Fp(2))

def scalarmult(n,P):
    if n == 0: return (Fp(0), Fp(1))
    if n == 1: return P
    Q = scalarmult(n//2,P)
    Q = clockadd(Q,Q)
    if n % 2: Q=clockadd(P,Q)
    return Q
#(947472, 736284)
for n in range(0,10): 
    i = scalarmult(n,P)
    print(n, i) #i.e. 6 (780000, 1351)

    if n == 780000 and P == 1351: #should stop the for loop at iteration 7 which is 6 (780000, 1351)
        break

Solution

  • Add an if statement inside the loop, after the print

    if n == 111111 and p == 2334897:
        break