Skip to content

Commit 47547a0

Browse files
committed
add xor.py
1 parent cf71aac commit 47547a0

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

README.md

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,16 @@
11
# python-xor-cipher
2-
File encryption with XOR-Cipher in Python
2+
File encryption with XOR-Cipher in Python.
3+
4+
## Usage
5+
6+
```
7+
$ python3 xor.py <infile> <outfile>
8+
9+
or
10+
11+
$ python3 xor.py <infile> <outfile> --key <password>
12+
```
13+
14+
* /infile/ is a file path to be encrypted.
15+
* /outfile/ is a encrypted file path.
16+
* /password/ is a encryption password.

xor.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)