Skip to content

Instantly share code, notes, and snippets.

@dadatuputi
Created May 25, 2020 17:59
Show Gist options
  • Save dadatuputi/35452973d00f464bfcef52302556ff76 to your computer and use it in GitHub Desktop.
Save dadatuputi/35452973d00f464bfcef52302556ff76 to your computer and use it in GitHub Desktop.
Encryption: Encrypt an any data with a base64-based Caesar Cipher
import argparse
import sys
import base64
# Author: Bradford Law
# Author Website: https://bradford.la
# Description: A Caesar Cipher implementation for Python 3.x that accepts any binary data,
# get args with argparse library:
# https://docs.python.org/3/library/argparse.html
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(args.input.read().encode())
print(rot(input64.decode()), end="")
else:
inputrot = rot(args.input.read())
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