Skip to content

Instantly share code, notes, and snippets.

@protortyp
Created October 12, 2019 16:27
Show Gist options
  • Save protortyp/fec84ed2ab768a30c23639c8f80810b1 to your computer and use it in GitHub Desktop.
Save protortyp/fec84ed2ab768a30c23639c8f80810b1 to your computer and use it in GitHub Desktop.
Caesar Cipher in Python
#!/usr/bin/python
import sys
import optparse
dic = {
"a": ord("a") - 97,
"b": ord("b") - 97,
"c": ord("c") - 97,
"d": ord("d") - 97,
"e": ord("e") - 97,
"f": ord("f") - 97,
"g": ord("g") - 97,
"h": ord("h") - 97,
"i": ord("i") - 97,
"j": ord("j") - 97,
"k": ord("k") - 97,
"l": ord("l") - 97,
"m": ord("m") - 97,
"n": ord("n") - 97,
"o": ord("o") - 97,
"p": ord("p") - 97,
"q": ord("q") - 97,
"r": ord("r") - 97,
"s": ord("s") - 97,
"t": ord("t") - 97,
"u": ord("u") - 97,
"v": ord("v") - 97,
"w": ord("w") - 97,
"x": ord("x") - 97,
"y": ord("y") - 97,
"z": ord("z") - 97
}
def getIdx(string: str, k: int) -> list:
idx = []
for ch in string:
if ch in dic:
idx.append((dic[ch] + k) % 26)
return idx
def encrypt(plain: str, k: int) -> str:
cipher = ""
cIdx = getIdx(plain, k)
for i in cIdx:
cipher += chr(i + 97)
return cipher
def decrypt(cipher: str, k: int) -> str:
cIdx = getIdx(cipher, -k)
plain = ""
for i in cIdx:
plain += chr(i + 97)
return plain
if __name__ == "__main__":
parser = optparse.OptionParser("\n\t./caesar.py -e \"HELLO WORLD\" -k 3\n\t./caesar.py -d \"KHOORZRUOG\" -k 3")
parser.add_option("-e", "--encrypt", dest="plain", type="string", help="encrypt mode")
parser.add_option("-d", "--decrypt", dest="cipher", type="string", help="decrypt mode")
parser.add_option("-k", dest="k", type="int", help="shift value")
options, args = parser.parse_args()
if(options.k == None or (options.cipher == None and options.plain == None)):
print(parser.usage)
sys.exit(1)
k = options.k
plain = options.plain
cipher = options.cipher
if(plain != None):
cipher = encrypt(plain.lower(), k)
print(cipher.upper())
else:
plain = decrypt(cipher.lower(), k)
print(plain.upper())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment