Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
155 lines (127 loc) · 5.6 KB
/
Copy pathcli.py
File metadata and controls
155 lines (127 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import argparse
import sys
from encoding import (
base32_encoding, base32_decoding,
base64_encoding, base64_decoding,
encode_hex, decode_hex,
urlsafe_encoding, urlsafe_decoding,
encode_to_morse, decode_from_morse,
)
from encryption import (
aes_encrypt, aes_decrypt,
fernet_encrypt, fernet_decrypt,
fernet_encrypt_with_password, fernet_decrypt_with_password,
generate_fernet_key, generate_rsa_keypair,
rsa_encrypt, rsa_decrypt,
generate_key, generate_iv,
)
from hashing import (
md5_hash, sha_hash, blake2_hash,
hash_with_salt, hash_with_pepper,
)
ENCODERS = {
'32': (base32_encoding, base32_decoding),
'64': (base64_encoding, base64_decoding),
'hexa': (encode_hex, decode_hex),
'url': (urlsafe_encoding, urlsafe_decoding),
'morse': (encode_to_morse, decode_from_morse),
}
CIPHERS = ('aes', 'fernet', 'rsa')
DIGESTS = ('md5', 'sha', 'blake2', 'salt', 'pepper')
METHODS = tuple(ENCODERS) + CIPHERS + DIGESTS
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog='Crypto-toolkit',
description='Encode, encrypt, hash text, etc.',
epilog='Hope this helps! ;)',
)
parser.add_argument(
'action',
choices=['encode', 'decode', 'encrypt', 'decrypt', 'hash', 'genkey'],
help='What to do with the input text',
)
parser.add_argument('method', choices=METHODS, help='Which method to use')
parser.add_argument('text', nargs='?', default='', help='The text to process')
parser.add_argument('--key', default='', help='Raw key (Fernet) or passphrase (AES)')
parser.add_argument('--password', default='', help='Password for password-based Fernet')
parser.add_argument('--mode', default='cbc', help='AES mode: cbc, gcm or ecb')
parser.add_argument('--algo', default='sha256', help='Hash algorithm, e.g. sha256, blake2b')
parser.add_argument('--salt', default='', help='Salt as hex (generated when omitted)')
parser.add_argument('--pepper', default='', help='Secret pepper for HMAC hashing')
parser.add_argument('--public-key', default='', help='Path to an RSA public key PEM')
parser.add_argument('--private-key', default='', help='Path to an RSA private key PEM')
parser.add_argument('--length', type=int, default=32, help='Byte length for genkey')
return parser
def _read_pem(path: str, what: str) -> str:
if not path:
raise ValueError(f'{what} is required - pass --public-key / --private-key')
with open(path, 'r') as handle:
return handle.read()
def run_encoding(action: str, method: str, text: str) -> str:
encoder, decoder = ENCODERS[method]
return encoder(text) if action == 'encode' else decoder(text)
def run_encryption(action: str, method: str, text: str, args) -> str:
if method == 'aes':
if action == 'encrypt':
return aes_encrypt(text, args.key or args.password, args.mode)
return aes_decrypt(text, args.key or args.password, args.mode)
if method == 'fernet':
if args.password:
if action == 'encrypt':
return fernet_encrypt_with_password(text, args.password)
return fernet_decrypt_with_password(text, args.password)
if action == 'encrypt':
return fernet_encrypt(text, args.key)
return fernet_decrypt(text, args.key)
if action == 'encrypt':
return rsa_encrypt(text, _read_pem(args.public_key, 'Public key'))
return rsa_decrypt(text, _read_pem(args.private_key, 'Private key'))
def run_hashing(method: str, text: str, args) -> str:
if method == 'md5':
return md5_hash(text)
if method == 'sha':
return sha_hash(text, args.algo)
if method == 'blake2':
return blake2_hash(text, args.algo if args.algo.startswith('blake2') else 'blake2b', args.key)
if method == 'salt':
digest, salt = hash_with_salt(text, args.salt, args.algo)
return f'hash: {digest}\nsalt: {salt}'
return hash_with_pepper(text, args.pepper, args.algo)
def run_genkey(method: str, args) -> str:
if method == 'fernet':
return generate_fernet_key()
if method == 'rsa':
private_pem, public_pem = generate_rsa_keypair()
return f'{private_pem}\n{public_pem}'
return f'key: {generate_key(args.length)}\niv: {generate_iv()}'
def describe_error(error: Exception) -> str:
"""Some crypto errors (InvalidToken, InvalidSignature) carry no message."""
return str(error) or type(error).__name__
def main(argv=None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
if args.action == 'genkey':
print(run_genkey(args.method, args))
return 0
is_coding = args.method in ENCODERS
is_cipher = args.method in CIPHERS
is_digest = args.method in DIGESTS
if args.action in ('encode', 'decode') and not is_coding:
parser.error(f"'{args.method}' is not an encoding method")
if args.action in ('encrypt', 'decrypt') and not is_cipher:
parser.error(f"'{args.method}' is not an encryption method")
if args.action == 'hash' and not is_digest:
parser.error(f"'{args.method}' is not a hashing method")
try:
if args.action in ('encode', 'decode'):
print(run_encoding(args.action, args.method, args.text))
elif args.action in ('encrypt', 'decrypt'):
print(run_encryption(args.action, args.method, args.text, args))
else:
print(run_hashing(args.method, args.text, args))
except Exception as error:
print(f'Error: {describe_error(error)}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())