Skip to content

Instantly share code, notes, and snippets.

@Marva82
Created June 8, 2018 21:11
Show Gist options
  • Save Marva82/7e8f6a301a81d3f8edd90401ecc08c1b to your computer and use it in GitHub Desktop.
Save Marva82/7e8f6a301a81d3f8edd90401ecc08c1b to your computer and use it in GitHub Desktop.
Caesar Cipher - Cryptography in Python
#Simple Ceasar Cipher - Cryptography
class CaesarCipher:
#Class for doing ecryption and decryption using Ceasar cipher
def __init__(self,shifter):
#Costruct cipher using integer shift of alphabet
encoderList = [None] * 26
decoderList = [None] * 26
for i in range(26):
encoderList[i] = chr((i + shifter)%26 + ord('A'))
decoderList[i] = chr((i - shifter)%26 + ord('A'))
self.forward = ''.join(encoderList) #stores as string
self.backward = ''.join(decoderList) #since fixed
def encryptMessage(self, message):
# Returns string representation of encripted message
return self.transformMessage(message, self.forward)
def decryptMessage(self, secret):
# Return decrypted message given encrypted secret
return self.transformMessage(secret, self.backward)
def transformMessage(self, original, code):
# Utility to perform transformation based on given code string
msg = list(original)
for i in range(len(msg)):
if msg[i].isupper():
j = ord(msg[i]) - ord('A') # index from 0 to 25
msg[i] = code[j]
return ''.join(msg)
cipher = CaesarCipher(5)
message = "TYPING AN ENCRYPTED MESSAGE"
codedMessage = cipher.encryptMessage(message)
print('Secret: ',codedMessage)
answerKey = cipher.decryptMessage(codedMessage)
print('Message: ',answerKey)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment