-2

I have a working script (Powered by Python 2.7) :

import sys

a=0
b=7
p=0xB12D

x2=0x38F

if (len(sys.argv)>1):
    x1=int(sys.argv[1])
if (len(sys.argv)>2):
    x2=int(sys.argv[2])
if (len(sys.argv)>3):
    p=int(sys.argv[3])
if (len(sys.argv)>4):
    a=int(sys.argv[4])
if (len(sys.argv)>5):
    b=int(sys.argv[5])


def modular_sqrt(a, p):
    """ Find a quadratic residue (mod p) of 'a'. p
        must be an odd prime.

        Solve the congruence of the form:
            x^2 = a (mod p)
        And returns x. Note that p - x is also a root.

        0 is returned is no square root exists for
        these a and p.

        The Tonelli-Shanks algorithm is used (except
        for some simple cases in which the solution
        is known from an identity). This algorithm
        runs in polynomial time (unless the
        generalized Riemann hypothesis is false).
    """
    # Simple cases
    #

    if legendre_symbol(a, p) != 1:
        return 0
    elif a == 0:
        return 0
    elif p == 2:
        return p
    elif p % 4 == 3:
        return pow(a, (p + 1) / 4, p)

    # Partition p-1 to s * 2^e for an odd s (i.e.
    # reduce all the powers of 2 from p-1)
    #
    s = p - 1
    e = 0
    while s % 2 == 0:
        s /= 2
        e += 1

    # Find some 'n' with a legendre symbol n|p = -1.
    # Shouldn't take long.
    #
    n = 2
    while legendre_symbol(n, p) != -1:
        n += 1

    x = pow(a, (s + 1) / 2, p)
    b = pow(a, s, p)
    g = pow(n, s, p)
    r = e

    while True:
        t = b
        m = 0
        for m in xrange(r):
            if t == 1:
                break
            t = pow(t, 2, p)

        if m == 0:
            return x

        gs = pow(g, 2 ** (r - m - 1), p)
        g = (gs * gs) % p
        x = (x * gs) % p
        b = (b * g) % p
        r = m


def legendre_symbol(a, p):
    """ Compute the Legendre symbol a|p using
        Euler's criterion. p is a prime, a is
        relatively prime to p (if p divides
        a, then a|p = 0)


        Returns 1 if a has a square root modulo
        p, -1 otherwise.
    """
    ls = pow(a, (p - 1) / 2, p)
    return -1 if ls == p - 1 else ls

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        print ("x")
    else:
       return x % m

def hexint(i): return int(i,0)

print "a=",a
print "b=",b
print "p=",p

print "x-point=",x2


# Read numbers from file and put them in an array
with open("List.txt","r") as f:
#   arrX1 = list(map(int,f.readlines()))
    arrX1 = list(map(hexint,f.readlines()))
f.close()

# Open the result file to write to
f = open('Result.txt', 'w')

# Now get x1 for each item in the list of numbers from the file
# then do the calculations
# and write the result

for x1 in arrX1:
    z=(x1**3 + a*x1 +b) % p
    y1=modular_sqrt(z, p)

    z=(x2**3 + a*x2 +b) % p
    y2=modular_sqrt(z, p)

    print "\nP1\t(%d,%d)" % (x1,y1)
    print "P2\t(%d,%d)" % (x2,y2)

    s=((-y2)-y1)* modinv(x2-x1,p) 

    x3=(s**2-x2-x1) % p

    y3=((s*(x2-x3)+y2)) % p

    result =  "\nQ(%d\n,%d)" % (x3,y3)
    f.write(result)

f.close()

But errors occur in this script due to a negative value during processing. (That is, when performing calculations using the "s =" formula, the value becomes negative and the script stops.)

Here is the error:

Traceback (most recent call last):
  File "E: \ 005.py", line 148, in <module>
    s = ((- y2) -y1) * modinv (x2-x1, p)
TypeError: unsupported operand type (s) for *: 'long' and 'NoneType'
>>>

I need my script not to stop, but to write only the correct result to the file: "Result.txt". And what was not correctly ignored and continued to work! Is it possible to ignore this stop?

That is, if an error occurs, do not stop the process and execute other sequential commands? I am not very strong in the Python language and cannot fix the script so that the function skips this error.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Rozwrcd
  • 11
  • 3
  • This answer your question: [Python code to ignore errors](https://stackoverflow.com/questions/31563418/python-code-to-ignore-errors) – Jongware Feb 10 '20 at 11:15
  • 2
    to ignore error you have `try/except` but you should rather check why you get `None` from `modinv` and correct it. Or use `if/else` to check value from `modinv` and skip other calculations. `result = modinv(x2-x1, p)` `if result is not None: s = ...` – furas Feb 10 '20 at 11:16
  • @furas Please tell me what needs to be fixed in the code itself? – Rozwrcd Feb 10 '20 at 11:19
  • 1
    Exception handling is a very basic Python feature. Are you aware of it? What problems did you encounter trying to use it? – MisterMiyagi Feb 10 '20 at 12:05

1 Answers1

0

If you expect that function can return wrong value - None - then you should get it separtelly and use if/else to skip it

value = modinv(x2-x1, p) 

if value is not None:
    s = (-y2-y1) * value

    x3 = (s**2-x2-x1) % p

    y3 = (s*(x2-x3)+y2) % p

    result = "\nQ(%d\n,%d)" % (x3, y3)
    f.write(result)
else:
    print('TypeError for:', x2, x1, p)
    #f.write("\nNo Result")

Eventually you can use try/except to catch this error

try:
    s = (-y2-y1) * modinv(x2-x1, p) 

    x3 = (s**2-x2-x1) % p

    y3 = (s*(x2-x3)+y2) % p

    result = "\nQ(%d\n,%d)" % (x3, y3)
    f.write(result)
except TypeError:
    print('TypeError for:', x2, x1, p)
    #f.write("\nNo Result")
furas
  • 134,197
  • 12
  • 106
  • 148
  • With this function, now the result is not written to the file: "Result.txt" – Rozwrcd Feb 10 '20 at 11:39
  • if `value` is `None` then it can't calculate `x3`, `y3` - so there is nothing to write. You can always add `f.write('no result')` to `else:` or to `except` – furas Feb 10 '20 at 11:55
  • BTW: if you want to skip negative value then you should rather check `g < 0` instead of `g != 1`. You may get `None` when `g > 1` and it is not negative value. – furas Feb 10 '20 at 12:00
  • What needs to be changed I did not understand? How if / else to skip it? – Rozwrcd Feb 10 '20 at 12:15
  • now in answer you have example how to use `if/else` and `try/except`. It is basic knowledge - I don't know how to write it simpler. Maybe your problem is in different place - maybe your calculations are incorrect and it always gives `g != 1` so it always return `None` and it can't calculate `s` and later `x3`, `y3` and there is nothing to write in file. Maybe your `modinv` should return `1` instead of `None` and then you can calculate `s = (-y2-y1) * 1` and write `x3`, `y3` in file. – furas Feb 10 '20 at 12:20
  • How can all this be fixed? I have enclosed all the script code: https://pastebin.com/0YhGGZTk List: https://pastebin.com/dBjajJaF Help fix the code ! – Rozwrcd Feb 10 '20 at 12:42
  • use `if/else` or `try/except` to resolve problem with error. If you have other problem then create new question on new page. – furas Feb 10 '20 at 12:49
  • when I run code then second `g` (and next) is `-1`. Use `print(g)` to see it. Are you sure it shouldn't be `return x` instead of `print("x")` ? – furas Feb 10 '20 at 12:57