|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import sys |
| 4 | +import argparse |
| 5 | +from getpass import getpass |
| 6 | +from pathlib import Path |
| 7 | +from hashlib import sha256 |
| 8 | + |
| 9 | +def get_seed(key): |
| 10 | + return sha256(key.encode('utf-8')).digest() |
| 11 | + |
| 12 | +def parse_args(): |
| 13 | + parser = argparse.ArgumentParser(description='XOR cipher') |
| 14 | + parser.add_argument('infile', help='input file path') |
| 15 | + parser.add_argument('outfile', help='output file path') |
| 16 | + parser.add_argument('--key', help='encryption password') |
| 17 | + |
| 18 | + args = parser.parse_args() |
| 19 | + |
| 20 | + if args.key is None: |
| 21 | + key = getpass() |
| 22 | + else: |
| 23 | + key = args.key |
| 24 | + |
| 25 | + return (Path(args.infile), Path(args.outfile), key) |
| 26 | + |
| 27 | +def validate_args(infile, outfile, seed): |
| 28 | + if not infile.is_file(): |
| 29 | + sys.exit('"{}" is not a file.'.format(infile)) |
| 30 | + |
| 31 | + if infile.stat().st_size < len(seed): |
| 32 | + sys.exit('infile must be larger than {} bytes.'.format(len(seed))) |
| 33 | + |
| 34 | + if outfile.is_file(): |
| 35 | + sys.exit('"{}" is already exists.'.format(outfile)) |
| 36 | + |
| 37 | +if __name__ == '__main__': |
| 38 | + (infile, outfile, key) = parse_args() |
| 39 | + seed = get_seed(key) |
| 40 | + validate_args(infile, outfile, seed) |
| 41 | + |
| 42 | + with infile.open('rb') as f_in: |
| 43 | + with outfile.open('wb') as f_out: |
| 44 | + i = 0 |
| 45 | + while f_in.peek(): |
| 46 | + c = ord(f_in.read(1)) |
| 47 | + j = i % len(seed) |
| 48 | + b = bytes([c ^ seed[j]]) |
| 49 | + f_out.write(b) |
| 50 | + i = i + 1 |
| 51 | + |
0 commit comments