Skip to content

Instantly share code, notes, and snippets.

@KitB
Last active November 12, 2016 16:14
Show Gist options
  • Save KitB/31b1b4d716dbe493befc83d4431d746b to your computer and use it in GitHub Desktop.
Save KitB/31b1b4d716dbe493befc83d4431d746b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import base64
import getpass
import math
import sys
def padpad(pad, text):
if len(text) > len(pad):
factor = int(math.ceil(float(len(text)) / len(pad)))
pad = (pad * factor)[:len(text)]
return pad
def _xor(text, pad):
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(text, pad))
def encode(plaintext, pad):
pad = padpad(pad, plaintext)
ciphertext = _xor(plaintext, pad)
return base64.encodestring(ciphertext)
def decode(ciphertext, pad):
pad = padpad(pad, ciphertext)
ciphertext = base64.decodestring(ciphertext)
plaintext = _xor(ciphertext, pad)
return plaintext
def main():
argparser = argparse.ArgumentParser()
argparser.add_argument('action', choices=['encode', 'decode'])
args = argparser.parse_args()
encoding = args.action == 'encode'
text = (raw_input if not encoding else getpass.getpass)('Enter ' + ('plaintext' if encoding else 'ciphertext') + ': ')
pad = getpass.getpass('Enter password: ')
print (encode if encoding else decode)(text, pad)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment