from encryption_algorithm import Euclid
import random
class ECC:
def __init__(self, coe: list, p: int, G: list):
self.coe = coe
self.p = p
self.G = G
# Ordinary addition
def add(self, a: list ,b: list)-> list:
euc = Euclid.euclid()
a_x, a_y = a[0], a[1]
b_x, b_y = b[0], b[1]
# The two abscissa are not equal
if(a_x!=b_x):
#print(p, b_x-a_x)
c = (b_y - a_y) * euc.get_valid_X_Y(self.p, (b_x-a_x)%self.p, ret_String=False)[1]
c %= p
# The two abscissa are equal , But the vertical coordinate is not the opposite number
elif((a_y+b_y)%p!=0):
c = (3 * a_x**2 + self.coe[0]) * euc.get_valid_X_Y(self.p, (2*a_y)%self.p, ret_String=False)[1]
c %= self.p
# The abscissa is equal , When the vertical coordinate is the opposite number , Can't calculate
else:
return None
x = (c**2 - a_x - b_x) % self.p
y = (c*(a_x - x) - a_y) % self.p
return [x, y]
# Number multiplication
def mul(self, n: int, T: list)-> list:
res = T
while(n>1):
res = self.add(res, T)
if(res==None):
print(" The abscissa is equal , The vertical coordinate is the opposite number , Not to be counted !!!")
return None
n -= 1
return res
if __name__=='__main__':
# Elliptic curve parameters
coe = [1, 1]
p = 23
# Cyclic group selection
n = 27
G = [0, 1]
# Key generation
dh_ecc = ECC(coe, p, G)
n_a = 5
n_b = 11
# Public key generation
mul_a = dh_ecc.mul(n_a,G)
mul_b = dh_ecc.mul(n_b,G)
# Shared key calculation
Share_a = dh_ecc.mul(n_a,mul_b)
Share_b = dh_ecc.mul(n_b,mul_a)
print(' user a Calculated shared key : {}'.format(Share_a))
print(' user b Calculated shared key : {}'.format(Share_b))