Skip to content

Instantly share code, notes, and snippets.

@dadatuputi
Last active May 25, 2020 17:59
Show Gist options
  • Save dadatuputi/1a79ea2ea273b47db30fc4caef5cc128 to your computer and use it in GitHub Desktop.
Save dadatuputi/1a79ea2ea273b47db30fc4caef5cc128 to your computer and use it in GitHub Desktop.
Encryption: Encrypt an ASCII [a-zA-Z0-9] string with a Caeser Cipher (ROT-N) encryption
import argparse
import sys
# Author: Bradford Law
# Author Website: https://bradford.la
# Description: A simple rot13 implementation for Python 3.x
# get args with argparse library:
# https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser(description='A simple rot13 implementation in Python.', prog='rot13')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-e','--encode', action='store_true', help='encode stdin')
group.add_argument('-d','--decode', action='store_true', help='decode stdin')
parser.add_argument('rot', type=int, metavar='ROT', default=13, nargs='?', help='provide rotational offset (default: %(default)s)')
args = parser.parse_args()
# if we are decoding, we simply reverse the rot
if (args.decode):
args.rot *= -1
# parse stdin and apply rot to each character
input = sys.stdin.read()
parseflag = False
for c in input:
charnumber = ord(c)
# check for A-Z, A=65, Z=90
if charnumber >= 65 and charnumber <= 90:
charnumber -= 65
print(chr((charnumber + args.rot)%26 + 65), end="")
# check for a-z, a=97, z=122
elif charnumber >= 97 and charnumber <= 122:
charnumber -= 97
print(chr((charnumber + args.rot)%26 + 97), end="")
else:
print(c, end="")
parseflag = True
# warn user if characters couldn't be encrypted
if parseflag:
sys.stderr.write("Some characters could not be encrypted.\n\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment