Skip to content

Instantly share code, notes, and snippets.

@CleverProgrammer
Created October 13, 2016 20:25
Show Gist options
  • Save CleverProgrammer/5b6b89e6a52ce23b9bda572f6816477b to your computer and use it in GitHub Desktop.
Save CleverProgrammer/5b6b89e6a52ce23b9bda572f6816477b to your computer and use it in GitHub Desktop.
"""
Author: Rafeh Qazi
Program: Encryption and Decryption
Resource: http://www.practicalcryptography.com/ciphers/caesar-cipher/
"""
# Use whatever key as long as it is consistent.
KEY = 17
def read_file(file_name):
"""Read a file and return a list of lines."""
with open(file_name, 'r') as f:
return f.readlines()
def caesar_cipher(letter, key=12):
"""Letter in the first 256 ascii is shifted 'key' positions. Default key is 12."""
# mod 256 to create a world of [0,255] integers.
return (ord(letter) + key) % 256
def caesar_encryption(file_name, key=12):
file_stuff = read_file(file_name)
print(file_stuff)
gibberish = [caesar_cipher(char) for elem in file_stuff for char in elem]
print(gibberish)
def caesar_decryption(encrypted_letter, key=12):
"""Used to reverse the destruction caused by caesar_encryption. Default key is 12."""
return chr((encrypted_letter - key) % 256)
# decrypt(encrypt(x)) should give you back x.
assert caesar_decryption(caesar_cipher('e', 20), 20) == 'e'
if __name__ == '__main__':
caesar_encryption('scratch_1.txt')
print('------')
encrypted_message = []
for letter in 'bananas':
encrypted_message.append(caesar_cipher(letter, KEY))
print(encrypted_message)
decrypted_message = []
for encrypted_letter in encrypted_message:
decrypted_message.append(caesar_decryption(encrypted_letter, KEY))
print(''.join(decrypted_message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment