0

I am looking for a reduced way of this code. I had to do the division separately because of the multiplicative inverse condition.

"""This code calculates the multiplication Elliptic curves over Zp"""
#Initial values for testing 

yq = 3
yp = 3
xq = 8
xp = 8
a = 1
p = 11

#Calculate the Euclid greatest common divisor
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

#Calculate the multiplicate inverse
def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('Mod inverse does not exist')
    else:
        return x % m

#veces = Number of times for the multiplication

veces = 7
print(f"The next results are the multiplication of {veces}*({xp},{yp})")
z = 1
while z <= (veces - 1):
    if xp == xq and yp == yq:
        numerador = (3 * pow(xp, 2) + a) % p
        denominador = ((2 * yp) % p)
        inver = modinv(denominador, p)
        landa = (inver * numerador) % p

    else:
        numerador = (yq - yp) % p
        denominador = (xq - xp) % p
        inver = modinv(denominador, p)
        landa = (inver * numerador) % p

    xr = (pow(landa, 2) - xp - xq) % p
    yr = (landa * (xp - xr) - yp) % p
    z += 1
    xp, yp = xr, yr

print(f"The result is ({xp},{yp})")

#Any way to simplify this code? I had to do the division separately but I think we can a reducted code for the division.

Franco
  • 11
  • 3
  • 1
    Simplify? You can just use `pow(a, -1, n)` to compute the inverse of `a` mod `n` for python >= 3.8, that's a simplification. The real problem is your iterative algorithm for computing `n*G` takes n steps, far too slow for use in real world problems. You need to use a double-and-add method, which is essentially the same as [binary exponentiation](https://en.wikipedia.org/wiki/Exponentiation_by_squaring) where 'squaring' is replaced by point doubling and 'multiplication' is replaced by point addition. – President James K. Polk Apr 23 '22 at 16:19
  • Thank you, James, I didn't know that pow can be used for computing the inverse. Also, I will need to check the binary exponentiation way to calculate n*G. Thanks for the advice. – Franco Apr 24 '22 at 04:37
  • @PresidentJamesK.Polk this is a useful answer, albeit posted as a comment. Would you please turn the comment into an answer so it won't be lost and you can take the credit? – Yennefer Apr 24 '22 at 20:31

0 Answers0