Last active
November 20, 2017 01:01
-
-
Save k4kfh/775f1c4497f98d63b3207aed987c16dd to your computer and use it in GitHub Desktop.
Simple Python Caesar cipher decrypting/encrypting library
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
# Just a simple Caesar cipher library | |
# Define a list of the alphabet | |
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] | |
def decryptCharacter(char, rotation): | |
# Find where in the alphabet our letter is (for example A would be index 0) | |
indexOriginal = alphabet.index(char) | |
# Now we take the index of the original letter and add our key, and this will be the index of the new letter | |
indexNew = indexOriginal - rotation | |
# This is just in case we're dealing with Z or something else where the index would go over 25. It makes the list basically loop infinitely | |
if (indexNew > 25): | |
indexNew = indexNew - 26 | |
# Now that we've done all that, we return the element from the alphabet list that's at our new index we just found | |
return alphabet[indexNew] | |
def decryptString(string, rotation): | |
output = "" | |
for letter in string: | |
# Ignore spaces | |
if (letter == " "): | |
output = output + " " | |
# Call the decryptCharacter function for this letter and add the decrypted letter to the end of our output string | |
else: | |
output = output + decryptCharacter(letter, rotation) | |
# We're done, return the output string we just put together | |
return output | |
def encryptString(string, rotation): | |
output = "" | |
for letter in string: | |
if (letter == " "): | |
output = output + " " | |
else: | |
output = output + encryptCharacter(letter, rotation) | |
return output | |
def encryptCharacter(char, rotation): | |
indexOriginal = alphabet.index(char) | |
indexNew = indexOriginal + rotation | |
if (indexNew > 25): | |
indexNew = indexNew - 26 | |
return alphabet[indexNew] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment