Thursday, February 25, 2010

Caeser Cipher

Now I have finished up the encryption chapter of this book. The entire idea behind the encryption is to shift each character of a string over by a certain amount. Whenever a character of a string exited the parameters of a-z or A-Z, you just add or subtract 26, thus "wrapping" your encryption around and back, so that letters are only encrypted into letters. This took me about 30 minutes total to create. Here is my source code:

import sys

def getMode():
    print('Do you want to encrypt decrypt, or brute force a message?')
    mode = raw_input().lower()
    if mode in 'encrypt decrypt e d brute b'.split():
        return mode
    else:
        print('You need to enter in one of the following: e, d, b')

def getMessage():
    print('Enter your message.')
    return raw_input()

def getKey():
    key = 0

    while True:
        print('Enter in a number for your key, 1-25.')
        key = int(raw_input())
        if (key >= 1 and key <= 25):
            return key

def getTranslatedMessage(key, mode, message):
    if mode[0] == 'd':
        key = -key

    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol

    return translated

def playAgain():
    print('Do you wish to continue? (yes or no)')
    return raw_input().lower().startswith('y')

Again = True

while True:
    mode = getMode()
    message = getMessage()
    if mode != 'b':
        Key = getKey()
    print('Your translated text is:')
    if mode != 'b':
        print(getTranslatedMessage(Key, mode, message))
    else:
        for key in range(1, 26 + 1):
            print(key, getTranslatedMessage(key, 'decrypt', message))
    if not playAgain():
        sys.exit



The next chapter of this book is here. This chapter goes over the Reversi game. I won't be constructing a program from this chapter as it doesn't really introduce any new concepts. The Ai for the reversi game just runs through each possible move and chooses the one that results in the most points. I will be skipping over chapter 14, and chapter 15, and heading straight into chapter 16. Chapter 16 is going over graphics and animation; I'll be starting to use the Pygame engine.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.