maroph icon

caesar.py

maroph | PRO | 12/02/19 05:25:34 PM UTC | 0 ⭐ | 400 👁️ | Never ⏰ | []
Python |

1.84 KB

|

None

|

0 👍

/

0 👎

import random
 
def encrypt(plaintext, offset):
    ciphertext = ''
    for char in plaintext:
        if not char.isalpha():
            ciphertext += char
            continue
        if char.isupper():
            ciphertext += chr((ord(char) + offset - 65) % 26 + 65)
        else:
            ciphertext += chr((ord(char) + offset - 97) % 26 + 97)
    return ciphertext
 
def decrypt(ciphertext, offset):
    plaintext = ''
    for char in ciphertext:
        if not char.isalpha():
            plaintext += char
            continue
        if char.isupper():
            plaintext += chr((ord(char) - offset - 65) % 26 + 65)
        else:
            plaintext += chr((ord(char) - offset - 97) % 26 + 97)
    return plaintext
 
 
while True:
    resp = input("Do you want to (e)ncode or (d)ecode? [e/d]:")
    if resp not in ["e", "d"]:
        continue
    break
 
mode_encrypt = True
if resp == "d":
    mode_encrypt = False
 
while True:
    resp = input("Do you want to use a random key? [y/n]:")
    if resp not in ["y", "n"]:
        continue
    break
 
if resp == "y":
    key = random.randrange(1,25)
    print('random key value :', key)
else:
    while True:
        try:
            key = int(input("What key would you like to use? Enter a number between 1 and 25:"))
        except:
            print('input is not an integer')
            continue
        if key < 1 or key > 25:
            print("Invalid key")
            continue
        break
 
if mode_encrypt:
    plaintext = input("Enter your plaintext:")
    print('plaintext  :', plaintext)
    ciphertext = encrypt(plaintext, key)
    print('ciphertext :', ciphertext)
else:
    ciphertext = input("Enter your ciphertext:")
    print('ciphertext :', ciphertext)
    plaintext = decrypt(ciphertext, key)
    print('plaintext  :', plaintext)

Comments