Very Simple Caesar Cipher (Python)

During a recent CTF I needed to decrypt a page encrypted with a Caesar Cipher. I didn’t know the what the ROT was and I was struggling to find an easy yet useful one around so I wrote this one.

Feel free to borrow it, steal it, claim it as your own or do whatever with it.

norsec0de

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python
###############################
#                             #
#  Very Simple Caesar Cipher  #
#        by norsec0de         #
#                             #
#          caesar.py          #
#                             #
###############################
import sys
# Encrypt Plain Text
def caesar(plainText, key=0):
    cipherText = ""
    for c in plainText:
        if c.isalpha():
            if c.isupper():
                caps = True
            else:
                caps = False
            alphabet = ord(c.lower()) + key
            if alphabet > ord('z'):
                alphabet -= 26
            letter = chr(alphabet)
            if caps is True:
                letter = letter.upper()
            cipherText += letter
        else:
            cipherText += c
    return cipherText
# Brute force all 26 possibilities.
def guess_caesar(plainText):
    print 'Showing all combinations for text ' + plainText
    key = 1
    for c in range(0,26):
        cipherText = caesar(plainText, key)
        print 'Key ' + str(key) + ' => ' + cipherText
        key += 1
# Main Program
# Usage
if len(sys.argv) == 1:
    print '\nCaesar Cypher Tool'
    print '\n Usage: ' + sys.argv[0] + ' (options) <text> <rot key>'
    print '\t encrypt         => \"Text to encrypt\" <key>'
    print '\t decrypt         => -d \"Text to decrypt\" <key>'
    print '\t decrypt file    => -f <filename> <key>'
    print '\t brute force     => -b \"Cyphertext\" \n'
# Brute force
elif sys.argv[1] == '-b':
    plainText = sys.argv[2]
    cipherText = guess_caesar(plainText)
    print cipherText
# Decode a string
elif sys.argv[1] == '-d':
    plainText = sys.argv[2]
    key = int(sys.argv[3])
    cipherText = caesar(plainText, key)
    print cipherText
# Decode a File
elif sys.argv[1] == '-f':
    infile = sys.argv[2]
    key = int(sys.argv[3])
    with open(infile, "r") as f:
        while True:
            line = f.readline()
            if not line:
                break
            print caesar(line, key)
# Encode a String
else:
    plainText = str(sys.argv[1])
    key = int(sys.argv[2])
    cipherText = caesar(plainText, key)
    print '\nEncrypting \"' + plainText + '\" with ROT' + str(key) + " => " + c
Bookmark the permalink.

Leave a Reply