Skip to content

Instantly share code, notes, and snippets.

Created May 25, 2020
What would you like to do?
Encryption: Encrypt an any data with a base64-based Caesar Cipher
import argparse
import sys
import base64
# Author: Bradford Law
# Author Website:
# Description: A Caesar Cipher implementation for Python 3.x that accepts any binary data,
# get args with argparse library:
parser = argparse.ArgumentParser(description='A Caesar Cipher implementation for Python 3.x that accepts any binary data from stdin or file input.', prog='rot64')
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('-i','--input', type=argparse.FileType('r'), default=sys.stdin, help='specify an input file instead of 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
# let's build a dictionary (and its inverse) of base64 characters plus '='
base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
lup = tuple((base64chars))
# perform our rotation
def rot(string):
rotated = ""
for c in string:
cloc = lup.index(c)
rotated += lup[(cloc + args.rot)%len(lup)]
return rotated
# encode stdin or file as base64
if args.encode:
input64 = base64.standard_b64encode(
print(rot(input64.decode()), end="")
inputrot = rot(
print(base64.standard_b64decode(inputrot).decode(), end="")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment