SoFunction
Updated on 2024-11-13

Python implementation of the ElGamal encryption algorithm sample code

In cryptography, ElGamal encryption algorithm is an asymmetric encryption algorithm based on Diffie-Herman key exchange. It was proposed by Tahir Gemal in 1985.The ElGamal algorithm is applied in many cryptographic systems such as GnuPG and PGP.

The ElGamal encryption algorithm can be defined on any cyclic group G. Its security depends on the discrete logarithmic puzzle on G.

Implement the ElGamal encryption algorithm using Python to complete the encryption and decryption process, using a 125-bit number (1000 bits) for the plaintext.

The code is as follows:

import random
from math import pow
a = (2, 10) # Generate a random constant a less than p

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 = (pow(10, 20), q)
  while gcd(q, key) != 1:
    key = (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) # Getting 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'        # Total 125 digits, 1000bit
  print("Explicit text :", msg)
  p = (pow(10, 20), pow(10, 50))# Get the large prime q
  r = (2, p)# Got 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("Decrypted Post-text :", dmsg);

if __name__ == '__main__':
  main()

summarize

To this article on the implementation of Python ElGamal encryption algorithm sample code is introduced to this article, more related python ElGamal encryption algorithm content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!