-
Notifications
You must be signed in to change notification settings - Fork 2
/
compile_conf_encrypt
executable file
·100 lines (86 loc) · 2.9 KB
/
compile_conf_encrypt
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
#!/usr/bin/env python
import argparse
import sys
import os.path
from Crypto.Cipher import AES
from Crypto import Random
import base64
from compile_conf_rsa import CRSA
try:
import readline
except ImportError:
pass
# Ugly hack for 2to3 compatibility
try:
input = raw_input
except NameError:
pass
class CAES:
@staticmethod
def create_key(filename):
randoms = Random.new().read(32)
encoded = base64.standard_b64encode(randoms)
key = encoded[:32]
open(filename, 'w').write(key)
return key
@staticmethod
def encrypt(key_value, data):
iv = Random.new().read(AES.block_size)
encryptor = AES.new(key_value.encode(), AES.MODE_CFB, iv)
return iv + encryptor.encrypt(data)
@staticmethod
def format_value(encrypted):
return '{~#%s}\n' % base64.standard_b64encode(encrypted).decode('ascii')
def load_key(filename):
return open(filename).read().strip()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Encrypt placeholder value for compile_conf')
parser_cipher = parser.add_mutually_exclusive_group(required=True)
parser_cipher.add_argument(
'--aes',
help='use symetric cipher AES',
action='store_true')
parser_cipher.add_argument(
'--rsa',
help='use asymetric cipher RSA',
action='store_true')
parser.add_argument(
'-c',
'--create',
help='create random key if file with key not exists',
action='store_true')
parser.add_argument('-k', '--key', help='file with key', required=True)
parser.add_argument(
'-n',
'--check-only',
help='it only checks if the key is present, it does not ask for the value to be encrypted.',
action='store_true')
args = parser.parse_args()
cipher = CAES if args.aes else CRSA
if not os.path.isfile(args.key):
if args.create:
key_value = cipher.create_key(args.key)
sys.stderr.write('New key written in to %s.\n' % args.key)
else:
sys.stderr.write(
'File with key "%s" not exists, try use param --create to generate new random key.\n' %
args.key)
sys.exit(1)
else:
key_value = load_key(args.key)
sys.stderr.write('Key loaded from %s.\n' % args.key)
if not args.check_only:
sys.stderr.write('Value to encrypt: ')
data = input()
if '"' in data:
sys.stderr.write(
"Value to encrypt can't contain char \" (quotation mark) !\n")
sys.exit(2)
if "'" in data:
sys.stderr.write(
"Value to encrypt can't contain char ' (apostrophe) !\n")
sys.exit(2)
encrypted = cipher.encrypt(key_value, data.encode('utf8'))
sys.stderr.write('Encrypted value: ')
sys.stdout.write(cipher.format_value(encrypted))