07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

236 Chapter 8 ■ Cryptographic Applications and PKI

■■

Bob publishes F, h = g a , q, and g as his public key and retains a as his

private key.

■■

Alice encrypts data using Bob’s public key:

■■

Alice selects an element k from cyclic group F such that gcd(k, q) = 1.

■■

Then she computes p = g k and s = h k = g ak .

■■

She multiplies s with M.

■■

Then she sends (p, M*s) = (g k , M*s).

■■

Bob decrypts the message:

■■

Bob calculates s′ = p a = g ak .

■■

He divides M*s by s′ to obtain M as s = s′.

The following Python code will help you gain an understanding of these

steps. You should notice many of the functions you have already learned about,

but if you need a refresher, see Chapter 4.

# Chapter 8 - ElGamal encryption

import random

from math import pow

a = random.randint(2, 10)

# Compute the GCD

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

# Compute the power

def power(a, b, c):

x = 1

y = a

while b > 0:

if b % 2 == 0:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!