Chapter ? - Secret Code 1
- # Secret Code 1 - Simple Substitution Cipher
- MAX_KEY_SIZE = 26
- def main():
- mode = getMode()
- message = getMessage()
- key = getKey()
-
- print 'Your translated text is:'
- print getTranslatedMessage(mode, message, key)
-
- def getMode():
- mode = ''
- while (mode not in 'encrypt e decrypt d'.split()):
- print 'Do you wish to encrypt or decrypt a message?'
- mode = raw_input()
- mode = mode.lower()
- if (mode not in 'encrypt e decrypt d'.split()):
- print 'Enter either "encrypt" or "e" or "decrypt" or "d".'
- return mode
- def getMessage():
- print 'Enter your message:'
- message = raw_input()
-
- return message
- def getKey():
- key = 0
- while (not (key >= 1 and key <= MAX_KEY_SIZE)):
- print 'Enter the key number (1-%s)' % (MAX_KEY_SIZE)
- key = int(raw_input())
- return key
- def getTranslatedMessage(mode, message, key):
- if mode in 'encrypt e'.split():
- return encrypt(message, key)
- if mode in 'decrypt d'.split():
- return decrypt(message, key)
- def encrypt(message, key):
- cipherText = ''
-
- for symbol in message:
- if symbol.isalpha():
- num = ord(symbol)
-
- if symbol.isupper():
- num -= ord('A')
- elif symbol.islower():
- num -= ord('a')
-
- num += key
- num = num % 26
-
- if symbol.isupper():
- num += ord('A')
- elif symbol.islower():
- num += ord('a')
-
- cipherText += chr(num)
- else:
- cipherText += symbol
- return cipherText
- def decrypt(message, key):
- plainText = ''
-
- for symbol in message:
- if symbol.isalpha():
- num = ord(symbol)
-
- if symbol.isupper():
- num -= ord('A')
- elif symbol.islower():
- num -= ord('a')
-
- num -= key
- num = num % 26
-
- if symbol.isupper():
- num += ord('A')
- elif symbol.islower():
- num += ord('a')
-
- plainText += chr(num)
- else:
- plainText += symbol
- return plainText
- if __name__ == '__main__':
- main()
Things Covered In This Chapter: