密码学 ElGamal密码代码实现

2020-07-31 14:20 更新
## Python program to illustrate ElGamal encryption   

    
import random    
from math import pow  

    
a = random.randint(2, 10)   

    
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, q, h, g):   

    
    en_msg = []   

    
    k = gen_key(q)# Private key for sender   
    s = power(h, k, q)   
    p = power(g, k, q)   

        
    for i in range(0, len(msg)):   
        en_msg.append(msg[i])   

    
    print("g^k used : ", p)   
    print("g^ak used : ", s)   
    for i in range(0, len(en_msg)):   
        en_msg[i] = s * ord(en_msg[i])   

    
    return en_msg, p   

    
def decrypt(en_msg, p, key, q):   

    
    dr_msg = []   
    h = power(p, key, q)   
    for i in range(0, len(en_msg)):   
        dr_msg.append(chr(int(en_msg[i]/h)))   

            
    return dr_msg   

    
## Driver code   
def main():   

    
    msg = 'helloguy'  
    print("Original Message :", msg)   

    
    q = random.randint(pow(10, 20), pow(10, 50))
    print("q:", q)   
    g = random.randint(2, q)   

       
    key = gen_key(q)# Private key for receiver   
    h = power(g, key, q)   
    print("g used : ", g)   
    print("g^a used : ", h)   

    
    en_msg, p = encrypt(msg, q, h, g)   
    dr_msg = decrypt(en_msg, p, key, q)   
    dmsg = ''.join(dr_msg)   
    print("Decrypted Message :", dmsg);   

    

    
if __name__ == '__main__':   
    main()

例子

对字符串“helloguy”加解密,

选取素数p=  1720347315796860882893253997740506679416619311894,

本原元素g= 1619469759846056197692072529100606730345659831487。 选取私钥X在区间[0,p)上,记录下私钥用于解密,私钥X= 138117328773995332098931395444374625529082560169。

生成公钥Y= 1085927808083585821031952923889844962165735398071。

密文为  1638173386820408824650250307486222200401511760847。

将密文用私钥解密得    helloguy。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号