程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Cryptography experiment_ 11_ DH key exchange algorithm (based on elliptic curve Python)

編輯:Python

List of articles

  • effect
  • Code

effect

Code

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))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved