Python实现ElGamal加密算法的示例代码

作者:出门左拐是海 时间:2023-05-23 15:25:58 

在密码学中,ElGamal加密算法是一个基于迪菲-赫尔曼密钥交换的非对称加密算法。它在1985年由塔希尔·盖莫尔提出。GnuPG和PGP等很多密码学系统中都应用到了ElGamal算法。

ElGamal加密算法可以定义在任何循环群G上。它的安全性取决于G上的离散对数难题。

使用Python实现ElGamal加密算法,完成加密解密过程,明文使用的是125位数字(1000比特)。

代码如下:


import random
from math import pow
a = random.randint(2, 10) #产生小于p的随机常数a

def gcd(a, b):
 if a < b:
   return gcd(b, a)
 elif a % b == 0:
   return b;
 else:
   return gcd(b, a % b)
 # Generating large random numbers

def gen_key(q):
 key = random.randint(pow(10, 20), q)
 while gcd(q, key) != 1:
   key = random.randint(pow(10, 20), q)
 return key

# Modular exponentiation
def power(a, b, c):
 x = 1
 y = a
 while b > 0:
   if b % 2 == 0:
     x = (x * y) % c;
   y = (y * y) % c
   b = int(b / 2)
 return x % c

# Asymmetric encryption
def encrypt(msg, p, h, r):
 en_msg = []
 b = gen_key(p) # 得b
 K = power(h, b, p)#K=(Sa)^b mod p
 C1 = power(r, b, p) #C1=Sb=r^b mod p
 for i in range(0, len(msg)):
   en_msg.append(msg[i])
 print("C1 : ", C1)
 # print("(Sa)^b mod p used : ", K)
 for i in range(0, len(en_msg)):
   en_msg[i] = K * ord(en_msg[i])
 print("C2 : ", en_msg)
 return en_msg, C1

def decrypt(C2, C1, a, p):
 dr_msg = []
 h = power(C1, a, p)
 for i in range(0, len(C2)):
   dr_msg.append(chr(int(C2[i] / h)))
 return dr_msg

# Driver code
def main():
 msg = '01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234'        # 共125位数字,1000bit
 print("明文 :", msg)
 p = random.randint(pow(10, 20), pow(10, 50))# 获得大素数q
 r = random.randint(2, p)#得r
 a = gen_key(p) # Private key for receiver
 h = power(r, a, p)
 C2, C1 = encrypt(msg, p, h, r)
 dr_msg = decrypt(C2, C1, a, p)
 dmsg = ''.join(dr_msg)
 print("解密后文 :", dmsg);

if __name__ == '__main__':
 main()

来源:https://blog.csdn.net/I_canjnu/article/details/106807142

标签:python,ElGamal,加密算法
0
投稿

猜你喜欢

  • Python实现的扫码工具居然这么好用!

    2022-12-13 19:54:03
  • Python OpenCV实现3种滤镜效果实例

    2021-06-04 10:20:27
  • 如何用OpenCV -python3实现视频物体追踪

    2022-04-02 23:15:58
  • Python2包含中文报错的解决方法

    2021-09-12 20:51:24
  • python使用cookielib库示例分享

    2022-09-22 13:53:37
  • php隐藏IP地址后两位显示为星号的方法

    2023-08-16 13:05:17
  • pandas中DataFrame重置索引的几种方法

    2023-06-10 00:26:45
  • python环境中的概念conda中与环境相关指令操作

    2021-01-09 19:40:55
  • golang之log rotate详解

    2024-02-03 10:54:45
  • 详解python之多进程和进程池(Processing库)

    2022-07-18 23:23:58
  • python机器学习算法与数据降维分析详解

    2023-09-20 19:40:27
  • 一文详解Python中的Map,Filter和Reduce函数

    2022-03-02 07:51:28
  • SQL语句分组获取记录的第一条数据的方法

    2012-08-21 10:58:39
  • MySQL中where 1=1方法的使用及改进

    2024-01-17 22:00:59
  • 网页设计中HTML常范的五个错误

    2008-04-22 18:14:00
  • 自定义404错误页面实现自动跳转

    2007-12-10 18:25:00
  • Mysql InnoDB的锁定机制实例详解

    2024-01-23 17:32:27
  • 百度地图API之本地搜索与范围搜索

    2023-08-23 17:24:38
  • SQL 2005 sa islock用户不能正常登录的现象

    2008-12-05 15:49:00
  • python中 _、__、__xx__()区别及使用场景

    2021-07-28 06:10:48
  • asp之家 网络编程 m.aspxhome.com