Skip to content

Instantly share code, notes, and snippets.

Last active May 25, 2020
What would you like to do?
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:
# Description: A simple rot13 implementation for Python 3.x
# get args with argparse library:
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 =
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="")
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