-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathencrypt_existing.py
384 lines (335 loc) · 11.5 KB
/
encrypt_existing.py
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import argparse
import binascii
from contextlib import ExitStack
def parse_args(argv=None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"add or remove encryption from an already-tensorized file. See"
" docs/encryption.md for an explanation."
)
)
subparsers = parser.add_subparsers(
help="whether to add or remove encryption"
)
LIMITS_METAVAR = "<SENSITIVE|MODERATE|INTERACTIVE|MIN|int>"
add_parser = subparsers.add_parser(
"add", description="add encryption to an already-tensorized file"
)
add_subparsers = add_parser.add_subparsers(
help="key derivation / generation method"
)
add_pwhash_parser = add_subparsers.add_parser(
"pwhash",
description=(
"encrypt using a key generated with Argon2id key derivation"
),
)
add_pwhash_parser.set_defaults(func=add_pwhash)
add_pwhash_parser.add_argument(
"--keyfile",
type=argparse.FileType("rb"),
required=True,
help=(
"file holding data to process into an encryption key using Argon2id"
),
)
add_pwhash_parser.add_argument(
"--no-strip-trailing-newlines",
dest="strip_trailing_newlines",
action="store_false",
default=True,
help="don't strip trailing newlines from the key file",
)
add_pwhash_parser.add_argument(
"--opslimit",
metavar=LIMITS_METAVAR,
type=str,
required=True,
help=(
"Argon2id opslimit (CPU time difficulty; param from libsodium's"
" pwhash function)"
),
)
add_pwhash_parser.add_argument(
"--memlimit",
metavar=LIMITS_METAVAR,
type=str,
required=True,
help=(
"Argon2id memlimit (RAM difficulty; param from libsodium's pwhash"
" function)"
),
)
add_pwhash_parser.add_argument(
"--salt",
type=str,
help=(
"hex representation of a custom 16-byte cryptographic salt to use"
" (randomly generated otherwise)"
),
)
add_exact_key_parser = add_subparsers.add_parser(
"exact",
description="encrypt using an exact 32-byte binary key, unmodified",
)
add_exact_key_parser.set_defaults(func=add_exact_key)
add_exact_key_parser.add_argument(
"--keyfile",
type=argparse.FileType("rb"),
required=True,
help=(
"file holding exactly 32 bytes of binary data to use verbatim as an"
" encryption key"
),
)
add_random_key_parser = add_subparsers.add_parser(
"random",
description=(
"encrypt using a random 32-byte binary key, and write the key to a"
" file"
),
)
add_random_key_parser.set_defaults(func=add_random_key)
add_random_key_parser.add_argument(
"--keyfile",
type=argparse.FileType("wb"),
required=True,
help=(
"file to write 32 bytes of randomly-generated binary data used as"
" an encryption key"
),
)
remove_parser = subparsers.add_parser(
"remove",
description="remove encryption from an already-tensorized file",
)
remove_subparsers = remove_parser.add_subparsers(
help="key derivation / generation method"
)
remove_pwhash_parser = remove_subparsers.add_parser(
"pwhash",
description=(
"decrypt using a key generated with Argon2id key derivation"
),
)
remove_pwhash_parser.set_defaults(func=remove_pwhash)
remove_pwhash_parser.add_argument(
"--keyfile",
type=argparse.FileType("rb"),
required=True,
help=(
"file holding data to process into an encryption key using Argon2id"
),
)
remove_pwhash_parser.add_argument(
"--no-strip-trailing-newlines",
dest="strip_trailing_newlines",
action="store_false",
default=True,
help="don't strip trailing newlines from the key file",
)
remove_exact_key_parser = remove_subparsers.add_parser(
"exact",
description="decrypt using an exact 32-byte binary key, unmodified",
)
remove_exact_key_parser.set_defaults(func=remove_exact_key)
remove_exact_key_parser.add_argument(
"--keyfile",
type=argparse.FileType("rb"),
required=True,
help=(
"file holding exactly 32 bytes of binary data to use verbatim as an"
" encryption key"
),
)
for subparser in (
add_pwhash_parser,
add_exact_key_parser,
add_random_key_parser,
remove_pwhash_parser,
remove_exact_key_parser,
):
subparser.add_argument(
"--infile", type=str, required=True, help="source file to convert"
)
subparser.add_argument(
"--outfile",
type=str,
required=True,
help="where to write the resulting converted file",
)
subparser.add_argument(
"-q",
"--quiet",
action="store_true",
default=False,
help="show less output",
)
args = parser.parse_args(argv)
if args.infile == args.outfile:
parser.error("--infile and --outfile can't be the same")
if args.func != add_random_key:
try:
args.key = args.keyfile.read()
args.keyfile.close()
except OSError:
parser.error("Provided --keyfile path could not be read")
else:
args.key = None
exact_key_length = 32
if args.func in (add_exact_key, remove_exact_key):
if len(args.key) != exact_key_length:
parser.error(
"Invalid key length:"
f" got {len(args.key)} bytes, expected {exact_key_length} bytes"
)
elif (
args.func in (add_pwhash, remove_pwhash)
and args.strip_trailing_newlines
):
args.key = args.key.rstrip(b"\r\n")
salt_length = 16
if args.func == add_pwhash:
if args.salt is not None:
if len(args.salt) != salt_length * 2:
parser.error(
f"Invalid --salt length (should be {salt_length} bytes ="
f" {salt_length * 2} hex characters)"
)
try:
args.salt = binascii.unhexlify(args.salt)
assert len(args.salt) == salt_length
except binascii.Error:
parser.error("Invalid hexadecimal string provided for --salt")
limit_options = ("SENSITIVE", "MODERATE", "INTERACTIVE", "MIN")
args.opslimit = args.opslimit.upper()
args.memlimit = args.memlimit.upper()
try:
int(args.opslimit)
except ValueError:
if args.opslimit not in limit_options:
parser.error(
"Invalid --opslimit, expected one of "
+ ", ".join(limit_options)
+ ", or an integer"
)
try:
int(args.memlimit)
except ValueError:
if args.memlimit not in limit_options:
parser.error(
"Invalid --memlimit, expected one of "
+ ", ".join(limit_options)
+ ", or an integer"
)
return args
def get_limit(value, enumeration) -> int:
try:
return int(value)
except ValueError:
value = getattr(enumeration, value, None)
if value is not None:
return value
else:
raise ValueError(
f"Unrecognized limit: {value}, available:"
f" {', '.join(v.name for v in enumeration)}"
)
def add_pwhash(args: argparse.Namespace):
from tensorizer import EncryptionParams
opslimit = get_limit(args.opslimit, EncryptionParams.OpsLimit)
memlimit = get_limit(args.memlimit, EncryptionParams.MemLimit)
salt = args.salt
key: bytes = args.key
encryption_params = EncryptionParams.from_string(
source=key, opslimit=opslimit, memlimit=memlimit, salt=salt
)
add_encryption(encryption_params, args.infile, args.outfile, not args.quiet)
print("Salt:", binascii.hexlify(encryption_params.salt).decode("ascii"))
def add_exact_key(args: argparse.Namespace):
from tensorizer import EncryptionParams
encryption_params = EncryptionParams(key=args.key)
add_encryption(encryption_params, args.infile, args.outfile, not args.quiet)
def add_random_key(args: argparse.Namespace):
from tensorizer import EncryptionParams
encryption_params = EncryptionParams.random()
args.keyfile.write(encryption_params.key)
args.keyfile.close()
add_encryption(encryption_params, args.infile, args.outfile, not args.quiet)
def add_encryption(
encryption_params, in_file: str, out_file: str, show_progress: bool = True
):
from tensorizer import TensorDeserializer, TensorSerializer, TensorType
with ExitStack() as cleanup:
serializer = TensorSerializer(out_file, encryption=encryption_params)
cleanup.callback(serializer.close)
deserializer = TensorDeserializer(
in_file, device="cpu", lazy_load=True, verify_hash=True
)
cleanup.enter_context(deserializer)
count: int = len(deserializer.keys())
i = 1
for (
module_idx,
tensor_type,
name,
tensor,
) in deserializer.read_tensors():
if show_progress:
print(f"({i} / {count}) Encrypting {name}")
i += 1
tensor_type = TensorType(tensor_type)
serializer.write_tensor(module_idx, name, tensor_type, tensor)
# Release memory
tensor.set_()
del tensor
def remove_pwhash(args: argparse.Namespace):
from tensorizer import DecryptionParams
decryption_params = DecryptionParams.from_string(args.key)
remove_encryption(
decryption_params, args.infile, args.outfile, not args.quiet
)
def remove_exact_key(args: argparse.Namespace):
from tensorizer import DecryptionParams
decryption_params = DecryptionParams.from_key(args.key)
remove_encryption(
decryption_params, args.infile, args.outfile, not args.quiet
)
def remove_encryption(
decryption_params, in_file: str, out_file: str, show_progress: bool = True
):
from tensorizer import TensorDeserializer, TensorSerializer, TensorType
with ExitStack() as cleanup:
serializer = TensorSerializer(out_file)
cleanup.callback(serializer.close)
deserializer = TensorDeserializer(
in_file,
device="cpu",
lazy_load=True,
verify_hash=True,
encryption=decryption_params,
)
cleanup.enter_context(deserializer)
count: int = len(deserializer.keys())
i = 1
for (
module_idx,
tensor_type,
name,
tensor,
) in deserializer.read_tensors():
if show_progress:
print(f"({i} / {count}) Decrypting {name}")
i += 1
tensor_type = TensorType(tensor_type)
serializer.write_tensor(module_idx, name, tensor_type, tensor)
# Release memory
tensor.set_()
del tensor
def main(argv=None):
args = parse_args(argv)
args.func(args)
if not args.quiet:
print("Done")
if __name__ == "__main__":
main()