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.

228 Chapter 8 ■ Cryptographic Applications and PKI

#Phi is the totient of n

phi = (p–1) * (q–1)

#Choose an integer e such that e and phi(n) are coprime

e = random.randrange(1, phi)

#Use Euclid's Algorithm to verify copprimes for e and phi(n)

g = gcd(e, phi)

while g != 1:

e = random.randrange(1, phi)

g = gcd(e, phi)

#Use Extended Euclid's Algorithm to generate the private key

d = multiplicative_inverse(e, phi)

#Return public and private keypair

#Public key is (e, n) and private key is (d, n)

return ((e, n), (d, n))

def encrypt(pk, plaintext):

key, n = pk

#Convert each letter in the plaintext to numbers based on the

character using a^b mod m

cipher = [(ord(char) ** key) % n for char in plaintext]

#Return the array of bytes

return cipher

def decrypt(pk, ciphertext):

key, n = pk

#Generate the plaintext based on the ciphertext and key using a^b

mod m

plain = [chr((char ** key) % n) for char in ciphertext]

#Return the array of bytes as a string

return ''.join(plain)

if __name__ == '__main__':

print ("Chapter 8 - Understanding RSA\n")

# First 20 prime numbers include:

# 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,

61, 67, 71

p = int(input("Enter a prime number: "))

q = int(input("Enter a second distinct prime number:"))

print ("\nGenerating your public/private keypairs . . .")

public, private = generate_keypair(p, q)

print ("\nYour public key is {} and your private key is {}\n".

format(public, private))

message = input("Enter a message to encrypt with your public key: ")

encrypted_msg = encrypt(public, message)

print ("Your encrypted message is: {}".format(''.join(map(lambda x:

str(x), encrypted_msg))))

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

Saved successfully!

Ooh no, something went wrong!