UPPERCASE_INDEX = 65 LOWERCASE_INDEX = 97 ALPHABET_LENGTH = 26 def encrypt(plaintext, shift): '''encrypt a string using the caesar cipher''' characters = list(plaintext) for i in range(len(characters)): if characters[i].isalpha(): oldChar = ord(characters[i]) if oldChar < LOWERCASE_INDEX: oldChar -= UPPERCASE_INDEX shiftedChar = oldChar + shift if shiftedChar >= 0: newChar = ( shiftedChar % ALPHABET_LENGTH ) + UPPERCASE_INDEX else: newChar = shiftedChar + ALPHABET_LENGTH * -(shiftedChar // ALPHABET_LENGTH) + UPPERCASE_INDEX else: oldChar -= LOWERCASE_INDEX shiftedChar = oldChar + shift if shiftedChar >= 0: newChar = ( shiftedChar % ALPHABET_LENGTH ) + LOWERCASE_INDEX else: newChar = shiftedChar + ALPHABET_LENGTH * -(shiftedChar // ALPHABET_LENGTH) + LOWERCASE_INDEX characters[i] = chr(newChar) return ''.join(characters) def decrypt(ciphertext, shift): '''decrypt a string using the caesar cipher''' characters = list(ciphertext) for i in range(len(characters)): if characters[i].isalpha(): oldChar = ord(characters[i]) if oldChar < LOWERCASE_INDEX: oldChar -= UPPERCASE_INDEX shiftedChar = oldChar - shift if shiftedChar >= 0: newChar = ( shiftedChar % ALPHABET_LENGTH ) + UPPERCASE_INDEX else: newChar = shiftedChar + ALPHABET_LENGTH * -(shiftedChar // ALPHABET_LENGTH) + UPPERCASE_INDEX else: oldChar -= LOWERCASE_INDEX shiftedChar = oldChar - shift if shiftedChar >= 0: newChar = ( shiftedChar % ALPHABET_LENGTH ) + LOWERCASE_INDEX else: newChar = shiftedChar + ALPHABET_LENGTH * -(shiftedChar // ALPHABET_LENGTH) + LOWERCASE_INDEX characters[i] = chr(newChar) return ''.join(characters)