def generate_key(k, length):
key_list = list()
for i in range(length):
key_list.append(k[i % len(k)])
return "".join(key_list)
def encrypt(text, k, symbol_size):
ctext = list()
for i in range(len(text)):
c = chr((((ord(text[i]) - ord('a')) + (ord(k[i]) - ord('a'))) % symbol_size) + ord('a'))
ctext.append(c)
return "".join(ctext)
def decrypt(ctext, k, symbol_size):
dtext = list()
for i in range(len(ctext)):
c = chr((((ord(ctext[i]) - ord('a')) - (ord(k[i]) - ord('a')) + 26) % symbol_size) + ord('a'))
dtext.append(c)
return "".join(dtext)
SYMBOL_SIZE = 26
plaintext = input("Plaintext: ")
keyword = input("Keyword: ")
key = generate_key(keyword, len(plaintext))
print("Generated Key: ", key)
ciphertext = encrypt(plaintext, key, SYMBOL_SIZE)
print("Ciphertext: ", ciphertext)
decrypted_text = decrypt(ciphertext, key, SYMBOL_SIZE)
print("Decrypted Text: ", decrypted_text)
Here, we are first receiving the plaintext and the keyword from the user. The keyword is then extended so that the key has the same length as the plaintext.
Now, we are encrypting each letter of the plaintext with the corresponding letter of the key. As I said, each letter should be mapped to an integer before the encryption and decryption. We are converting a letter c to an integer using:
ord(c) – ord(‘a’)
And, after the encryption, the integer is mapped to a letter using:
chr(integer + ord(‘a’))
I hope this helps. However, readers who want to know more about how different cryptographic algorithms work and how they are used in various secure network protocols can refer to the book “Cryptography And Public Key Infrastructure.”










































0 Comments