Last active
January 1, 2016 17:39
-
-
Save marcoscastro/8178171 to your computer and use it in GitHub Desktop.
Implementation of Caesar Cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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