0% found this document useful (0 votes)
7 views

VERNAM - Python Activity

A reference python code for the Vernam Cipher school activity.

Uploaded by

jeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

VERNAM - Python Activity

A reference python code for the Vernam Cipher school activity.

Uploaded by

jeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

'''

PYTHON PROJECT: VERNAM CIPHER


'''

#The formula for encryption and decryption.


def encrypt(text, key):
result = ''
for i in range(len(text)):
character = chr((ord(text[i])-97 + ord(key[i])-97) % 26 + 97)
result = result + character
return result

def decrypt(cipher, key):


result = ''
for i in range(len(cipher)):
character = chr(((ord(cipher[i]) - 97) - (ord(key[i]) - 97) + 26) % 26 + 97)
result = result + character
return result

def main():

while True:
choice_text = """
Choose a number

1. Encrypt
2. Decrypt
3. Exit
"""

print(choice_text)

choice = input("\nEnter a number: ")

#The user input is converted into lowercase if its in upper case.


#It is also check wether or not it's an alphabet.
if choice == '1':
text = input("\nEnter the plain text: ").lower()

while not text.isalpha():


print("\nInvalid input. Please only enter letters from a-z without spaces.")
text = input("\nEnter the plain text: ").lower()

#The key must always be equal to the lenght of text.


key = input("\nEnter the key: ").lower()
while len(key) != len(text) or not key.isalpha():
print("\nInvalid input. Please only enter letters from a-z without spaces.\n\nThe key must
also be equal to the lenght of the original text.")
key = input("\nEnter the key: ").lower()

cipher_text = encrypt(text, key)


print("\nThe cipher text is:", cipher_text)

elif choice == '2':


cipher_text = input("\nEnter the cipher text: ")
while not cipher_text.isalpha():
print("\nInvalid input. Please only enter letters from a-z without spaces.")
text = input("\nEnter the plain text: ").lower()

key = input("\nEnter the key: ")


while len(key) != len(text) or not key.isalpha():
print("\nInvalid input. Please only enter letters from a-z without spaces.")
key = input("\nEnter the key: ").lower()

plain_text = decrypt(cipher_text, key)


print("\nThe original text is:", plain_text)

elif choice == '3':


print("\nExiting...")
break
else:
print("Please choose a valid number.")

main()

You might also like