Encrypt message using Python
Posted on | August 28, 2009 | 3 Comments
This program makes use Caeser Cipher method for encrypting and decrypting data. From Wikipedia
It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would becomeE, and so on. The method is named after Julius Caesar, who used it to communicate with his generals.
Here is the program in python.
# Caesar Cipher – Simple Substitution Cipher
MAX_KEY_SIZE = 26
def getMessage():
print ‘Enter your message:’
return raw_input()
def getMode():
while True:
print ‘Do you wish to encrypt or decrypt a message?’
mode = raw_input().lower()
if mode in ‘encrypt e decrypt d’.split():
return mode
else:
print ‘Enter either “encrypt” or “e” or “decrypt” or “d”.’
def getKey():
key = 0
while True:
print ‘Enter the key number (1-%s)’ % (MAX_KEY_SIZE)
key = int(raw_input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
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
mode = getMode()
message = getMessage()
key = getKey()
print ‘Your translated text is:’
print getTranslatedMessage(mode, message, key)
input()
You can check out the code for finding out root of a number using Newton’s method of iteration in Python. This code cipher code is from the free ebook Invent Your Own Computer Games with Python
Comments
3 Responses to “Encrypt message using Python”
Leave a Reply
August 28th, 2009 @ 12:46 pm
you can get this a little bit easier: ;]
from string import maketrans, translate, ascii_letters as al
def caesar(text, offset):
return translate(text, maketrans(al, al[offset:] + al[:offset]))
print caesar(caesar(‘foobar’, 2), -2) == ‘foobar’
hth
January 17th, 2010 @ 8:32 am
# This version handles upper- lowercase individually, and therefore correct
from string import maketrans, translate, ascii_lowercase as al, ascii_uppercase as au
def caesar(text, offset):
strCClow = translate(text, maketrans(al, al[offset:] + al[:offset]))
strCCupr = translate(strCClow, maketrans(au, au[offset:] + au[:offset]))
return strCCupr
November 8th, 2010 @ 7:01 am
shift = lambda txt,sft=1:”.join([[ch,chr((ord(ch) - ord(['A','a'][ch.islower()]) + sft)%26+ord(['A','a'][ch.islower()]))][ch.isalpha()] for ch in txt])