import random
def random_primes() -> int:
while (True):
flag = False
x = random.randint(0, 100)
if ((x - 3) % 4 == 0):
for i in range(2, x - 1):
n = True
if x % i == 0:
n = False
break
if n != False:
flag = True
if flag == True:
return x
def multimod(a,k,n):
ans = 1
while(k != 0):
if k % 2:
ans = (ans % n) * (a % n) % n
a = (a % n) * (a % n) % n
k = k // 2
return ans
def primary_root(n) -> int:
k = (n - 1) // 2
for i in range(2, n - 1):
if multimod(i, k, n) != 1:
return i
def eulur(x,n,p) -> int:
result = pow(x,n,p)
return result
def Ciphertext_1(g,p,Ha): #求密文
k = 9
m = 10
print("k = {},m = {}".format(k,m))
u = pow(g,k,p)
v = (pow(Ha,k) * m) % p
return u,v
def Ciphertext_2(g,p,Ha): #求密文
k = random.randint(1,p-1)
m = random.randint(1,p)
print("k = {},m = {}".format(k,m))
u = pow(g,k,p)
v = (pow(Ha,k) * m) % p
return u,v
def mod_inverse(a, n): #求逆元
t, new_t = 0, 1
r, new_r = n, a
while new_r != 0:
quotient = r // new_r
t, new_t = new_t, t - quotient * new_t
r, new_r = new_r, r - quotient * new_r
if r > 1:
raise ValueError("a在模n意义下没有逆元")
if t < 0:
t = t + n
return t
def Plaintext(u,v,Xa,p) -> int:
k = pow(u,Xa) % p
k_inverse = mod_inverse(k,p)
M = (v * k_inverse) % p
return M
def num_1():
u, v = Ciphertext_1(2, 13, 7)
print("密钥生成:p = {},g = {},Ha = {}".format(13, 2, 7))
print("加密:收到p = {},g = {},Ha = {},取k = {},m = {},计算出密文({},{})".format(13, 2, 7, 9, 10, u, v))
print("解密:p = {},收到密文(u,v) = ({},{}),解得明文m = {}".format(13, u, v, Plaintext(u, v, 11, 13)))
def num_2():
p = random_primes() #素数生成
g = primary_root(p) #求解原根
Xa = random.randint(1,p-1)
Ha = eulur(g,Xa,p)
u,v = Ciphertext_2(g,p,Ha)
print("密钥生成:p = {},g = {},Ha = {}".format(p,g,Ha))
print("加密:收到p = {},g = {},Ha = {},计算出密文({},{})".format(p,g,Ha,u,v))
print("解密:p = {},收到密文(u,v) = ({},{}),解得明文m = {}".format(p,u,v,Plaintext(u,v,Xa,p)))
if __name__ == '__main__':
print("欢迎来到Xiaoyu的ElGamal加密算法!!!")
print("请输入您的选择: 1___以Word文档的案例运行,2___以随机数生成运行")
num = int(input())
if num == 1:
num_1()
elif num == 2:
num_2()
ElGamal公钥实现
最新推荐文章于 2024-10-30 16:52:22 发布