caesar cipher implementation in python code example
Example 1: python caesar cipher
plaintext = input("Please enter your plaintext: ")
shift = input("Please enter your key: ")
alphabet = "abcdefghijklmnopqrstuvwxyz"
ciphertext = ""
while isinstance(int(shift), int) == False:
shift = input("Please enter your key (integers only!): ")
shift = int(shift)
new_ind = 0
for i in plaintext:
if i.lower() in alphabet:
new_ind = alphabet.index(i) + shift
ciphertext += alphabet[new_ind % 26]
else:
ciphertext += i
print("The ciphertext is: " + ciphertext)
Example 2: caesar cipher python
def cc_encrypt(msg: str,key: int) -> str:
encrypted_msg = ''
try:
for char in msg:
encrypted_msg += str(chr(ord(char)+int(key)))
except:
print(Exception)
pass
return encrypted_msg
def cc_decrypt(msg: str,key: int) -> str:
decrypted_msg = ''
try:
for char in msg:
decrypted_msg += chr(ord(char)-int(key))
except:
print(Exception)
pass
return decrypted_msg
message = 'Hello World!'
key = 9
print(f'Caesar Cipher:\nEncrypted: {cc_encrypt(message,key)}\nDecrypted: {cc_decrypt(cc_encrypt(message,key),key)}')