Skip to content

Instantly share code, notes, and snippets.

@marcoscastro
Last active January 1, 2016 17:39
Show Gist options
  • Save marcoscastro/8178171 to your computer and use it in GitHub Desktop.
Save marcoscastro/8178171 to your computer and use it in GitHub Desktop.
Implementation of Caesar Cipher
# implementation of caesar cipher
# key - number of rotational positions
def encrypt(text, key):
text_list = list(text)
text_encrypt = ""
for i in text_list:
# check if char is a letter
if (i >= 'a' and i <= 'z') or (i >= 'A' and i <= 'Z'):
if (i >= 'a' and i <= 'z'):
ord_c = (ord(i) - ord('a') + key) % 26
text_encrypt += chr(ord_c + ord('a'))
else:
ord_c = (ord(i) - ord('A') + key) % 26
text_encrypt += chr(ord_c + ord('A'))
else:
text_encrypt += i
return text_encrypt
def decrypt(text, key):
text_list = list(text)
text_encrypt = ""
for i in text_list:
if (i >= 'a' and i <= 'z') or (i >= 'A' and i <= 'Z'):
if (i >= 'a' and i <= 'z'):
ord_c = (ord(i) - ord('a') - key) % 26
text_encrypt += chr(ord_c + ord('a'))
else:
ord_c = (ord(i) - ord('A') - key) % 26
text_encrypt += chr(ord_c + ord('A'))
else:
text_encrypt += i
return text_encrypt
# test to entry: ABCDEFGHIJKLMNOPQRSTUVWXYZ
# shift (key): 23
# output: XYZABCDEFGHIJKLMNOPQRSTUVW
print(encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 23))
print(decrypt("XYZABCDEFGHIJKLMNOPQRSTUVW", 23))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment