Skip to content

Instantly share code, notes, and snippets.

@eaorak
Created October 30, 2012 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eaorak/3981229 to your computer and use it in GitHub Desktop.
Save eaorak/3981229 to your computer and use it in GitHub Desktop.
Python - Caesar Cipher
#!/usr/bin/python3
# Caesar Cipher
LEN,UP_MIN,LOW_MIN = 26,65,97
def getchar(ch, key, enc):
if not ch.isalpha():
return ch
key = key if enc else -key
(min,max) = (UP_MIN, UP_MIN+LEN) if ch.isupper() else (LOW_MIN, LOW_MIN+LEN)
idx = ord(ch) + key
mul = 1 if idx < min else (-1 if idx > max else 0)
return chr(idx + mul * LEN)
def encdec(message, key, enc):
result=[]
for i in message:
result.append(getchar(i,key,enc))
return ''.join(result)
print('Enter the message : ', end='')
message,key=input(),0
while not (key > 0 and key < LEN):
print('Enter key [1-26] : ', end='')
key=int(input())
encMsg = encdec(message, key, True)
print('Encrypted message : %s' % encMsg)
decMsg = encdec(encMsg, key, False)
print('Decrypted message : %s' % decMsg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment