Last active
August 29, 2015 14:20
-
-
Save ademberbic/b910d8b73b2ff5646f0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse, os.path, string, sys | |
def parseArgs(): | |
parser = argparse.ArgumentParser( | |
description='A small, simple encrypter and decrypter.') | |
parser.add_argument('keys', nargs='+', | |
help='variable number of keys to encrypt with') | |
parser.add_argument('-i', '--infile', | |
help='file to optionally read from instead of stdin') | |
parser.add_argument('-o', '--outfile', | |
help='file to optionally write to instead of stdout') | |
parser.add_argument('-d', '--decrypt', action='store_true', | |
help='decrypt text instead of encrypting it') | |
return parser.parse_args() | |
def charToInt(char): | |
return string.ascii_letters.index(char) | |
def intToChar(index): | |
return string.ascii_letters[index % len(string.ascii_letters)] | |
def getText(infile): | |
if infile == None: | |
return sys.stdin.read() | |
else: | |
try: | |
with open(infile, 'r') as f: | |
return f.read() | |
except IOError: | |
print('error reading from file:', infile) | |
raise SystemExit | |
def putText(outfile, text): | |
if outfile == None: | |
print(text) | |
else: | |
try: | |
with open(outfile, 'w') as f: | |
f.write(text.rstrip() + '\n') | |
except IOError: | |
print('error writing to file:', infile) | |
def operate(decrypt, text, keys): | |
result = '' | |
for i, c in enumerate(text): | |
if c not in string.ascii_letters: | |
result += c | |
continue | |
index = charToInt(c) | |
for key in keys: | |
k = key[i % len(key)] | |
if decrypt: | |
index -= charToInt(k) | |
else: | |
index += charToInt(k) | |
result += intToChar(index) | |
return result | |
def main(): | |
args = parseArgs() | |
text = getText(args.infile) | |
text = operate(args.decrypt, text, args.keys) | |
putText(args.outfile, text) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment