0

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
horeacio
  • 3
  • 4

1 Answers1

0

Add an if statement inside the loop, after the print

if n == 111111 and p == 2334897:
    break
Mohamed Yasser
  • 641
  • 7
  • 17
  • I tried this and it doesn't seem to work. The for loop still runs until it reaches the final digit in the range. My for loop has if n ==780000 and P ==1351, it should stop at point (780000, 1351) which is when n = 6, but it keeps printing the digits after it still. – horeacio May 04 '22 at 16:51
  • What do you mean stop when n == 780000 which is when n = 6? Do you have 2 different variables named n? – Mohamed Yasser May 04 '22 at 16:55
  • I have a the variable n going from range (0, 10) and have whatever n is being input in the method 'scalarmult(n,P)'. I have updated the code to show how my for loop is currently set up. – horeacio May 04 '22 at 17:05
  • Ok I think I see where the problem is now. The variable returned by scalarmult is not called n anymore, it is called i and it is a tuple (think of tuples as immutable lists). So to stop at the 6th iteration you'll need to write `i[0] == 780000 and i[1] == 1351: break` . However, you did override the equal operator for your data type. To make this equality work rewrite your __eq__ as `lambda a,b: a.int == b` . Do both of these or just simply define the integers 780000 and 1351 as Fp; like so: `i[0] == Fp(780000) and i[1] == Fp(1351): break`. The last line of the output: `6 (780000, 1351)`. – Mohamed Yasser May 04 '22 at 17:21