-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesar.py
executable file
·62 lines (54 loc) · 2.07 KB
/
caesar.py
1
2
3
4
5
6
7
8
9
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
#!/usr/bin/env python
import utils
from string import ascii_uppercase
import sys
from optparse import OptionParser
import cryptutils
class Caesar(object):
def __init__(self,key):
key = key[0].lower()
self.key = key
def decrypt(self,ciphertext):
key = self.key
ciphertext = cryptutils.convertInput(ciphertext,['upper','nospaces','charonly'])
plaintext = []
for i in range(0,len(ciphertext)):
ch = ciphertext[i]
plaintext.append(cryptutils.rotateChar(ch,key,direction='backward'))
return ''.join(plaintext)
def encrypt(self,message):
key = self.key
message = cryptutils.convertInput(message,['upper','nospaces','charonly'])
outmessage = []
for i in range(0,len(message)):
ch = message[i]
outmessage.append(cryptutils.rotateChar(ch,key))
return ''.join(outmessage)
if __name__ == '__main__':
usage = "usage: %prog [options] cipher or plaintext"
parser = OptionParser(usage=usage)
parser.add_option("-e", "--encrypt", dest="doEncrypt", action="store_true",
help="Encrypt plaintext", default=False)
parser.add_option("-d", "--decrypt", dest="doDecrypt", action="store_true",
help="Decrypt ciphertext", default=False)
parser.add_option("-k", "--key", dest="key",
help="Encryption/decryption key (shortened to one character)", metavar="KEY")
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
(options, args) = parser.parse_args()
if options.key is None:
print 'Single character key is required!'
sys.exit(1)
if not options.doEncrypt and not options.doDecrypt:
print 'Must choose encryption or decryption!'
sys.exit(1)
if options.doEncrypt and options.doDecrypt:
print 'Must choose encryption OR decryption!'
sys.exit(1)
text = ' '.join(args)
c = Caesar(options.key)
if options.doEncrypt:
print c.encrypt(text)
if options.doDecrypt:
print c.decrypt(text)