1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| ''' Author: M@tr1x Date: 2020-11-06 17:15:32 LastEditTime: 2020-11-08 12:14:15 Description: Elgamal密码加解密程序 '''
import gmpy2 from Crypto.Util import number import random import sympy
class Elgamal(): def __init__(self,p_length): self.p = number.getPrime(p_length) self.x = random.randint(2,self.p-3) self.g = sympy.primitive_root(self.p) self.y = int(gmpy2.powmod(self.g,self.x,self.p))
def encrypt(self,m): """crypto function
Args: m (num): plain decimal message
Returns: y1,y2: encrypted k&m """ k = random.randint(1,self.p-2) while int(gmpy2.gcd(k,self.p-1))!=1: k = random.randint(1,self.p-2) y1 = gmpy2.powmod(self.g,k,self.p) y2 = (m%self.p)*int(gmpy2.powmod(self.y,k,self.p))%self.p y1 = int(y1)
return y1,y2
def decrypt(self,y1,y2): """decrypto function
Args: y1 (num): y2 (num):
Returns: m: plain message """ yi = int(gmpy2.invert(y1,self.p)) m = int(gmpy2.powmod(yi,self.x,self.p))*(y2%self.p)%self.p return m
if __name__ == "__main__": new_elgamal = Elgamal(50) (y1,y2) = new_elgamal.encrypt(9999999) print("y1:"+str(y1)) print("y2:"+str(y2)) m = new_elgamal.decrypt(y1,y2) print("m:"+str(m))
|