Completed
Push — master ( 55c5c2...b8d8e6 )
by John
02:41
created

zlibhash()   B

Complexity

Conditions 6

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
dl 0
loc 20
ccs 8
cts 8
cp 1
crap 6
rs 8
1
#!/usr/bin/env python3
2 4
"""This module is used to generate file hashes/checksums and PGP signatures."""
3
4 4
import zlib  # crc32/adler32
5 4
import hashlib  # all other hashes
6 4
import hmac  # escreens is a hmac, news at 11
7 4
import os  # path work
8 4
import concurrent.futures  # parallelization
9 4
import gnupg  # interface b/w Python, GPG
10 4
from bbarchivist import bbconstants  # premade stuff
11 4
from bbarchivist import exceptions  # exceptions
12 4
from bbarchivist import utilities  # cores
13 4
from bbarchivist import iniconfig  # config parsing
14
15 4
__author__ = "Thurask"
16 4
__license__ = "WTFPL v2"
17 4
__copyright__ = "Copyright 2015-2016 Thurask"
18
19
20 4
def zlibhash(filepath, method, blocksize=16 * 1024 * 1024):
21
    """
22
    Return zlib-based (i.e. CRC32/Adler32) checksum of a file.
23
24
    :param filepath: File you wish to verify.
25
    :type filepath: str
26
27
    :param method: "crc32" or "adler32".
28
    :type method: str
29
30
    :param blocksize: How much of file to read at once. Default is 16MB.
31
    :type blocksize: int
32
    """
33 4
    hashfunc = zlib.crc32 if method == "crc32" else zlib.adler32
34 4
    seed = 0 if method == "crc32" else 1
35 4
    with open(filepath, 'rb') as file:
36 4
        for chunk in iter(lambda: file.read(blocksize), b''):
37 4
            seed = hashfunc(chunk, seed)
38 4
    final = format(seed & 0xFFFFFFFF, "08x")
39 4
    return final
40
41
42 4
def hc32(filepath, blocksize=16 * 1024 * 1024):
43
    """
44
    Return CRC32 checksum of a file.
45
46
    :param filepath: File you wish to verify.
47
    :type filepath: str
48
49
    :param blocksize: How much of file to read at once. Default is 16MB.
50
    :type blocksize: int
51
    """
52 4
    return zlibhash(filepath, "crc32", blocksize)
53
54
55 4
def ha32(filepath, blocksize=16 * 1024 * 1024):
56
    """
57
    Return Adler32 checksum of a file.
58
59
    :param filepath: File you wish to verify.
60
    :type filepath: str
61
62
    :param blocksize: How much of file to read at once. Default is 16MB.
63
    :type blocksize: int
64
    """
65 4
    return zlibhash(filepath, "adler32", blocksize)
66
67
68 4
def hs1(filepath, blocksize=16 * 1024 * 1024):
69
    """
70
    Return SHA-1 hash of a file.
71
72
    :param filepath: File you wish to verify.
73
    :type filepath: str
74
75
    :param blocksize: How much of file to read at once. Default is 16MB.
76
    :type blocksize: int
77
    """
78 4
    sha1 = hashlib.sha1()
79 4
    hashfunc_reader(filepath, sha1, blocksize)
80 4
    return sha1.hexdigest()
81
82
83 4
def hs224(filepath, blocksize=16 * 1024 * 1024):
84
    """
85
    Return SHA-224 hash of a file.
86
87
    :param filepath: File you wish to verify.
88
    :type filepath: str
89
90
    :param blocksize: How much of file to read at once. Default is 16MB.
91
    :type blocksize: int
92
    """
93 4
    sha224 = hashlib.sha224()
94 4
    hashfunc_reader(filepath, sha224, blocksize)
95 4
    return sha224.hexdigest()
96
97
98 4
def hs256(filepath, blocksize=16 * 1024 * 1024):
99
    """
100
    Return SHA-256 hash of a file.
101
102
    :param filepath: File you wish to verify.
103
    :type filepath: str
104
105
    :param blocksize: How much of file to read at once. Default is 16MB.
106
    :type blocksize: int
107
    """
108 4
    sha256 = hashlib.sha256()
109 4
    hashfunc_reader(filepath, sha256, blocksize)
110 4
    return sha256.hexdigest()
111
112
113 4
def hs384(filepath, blocksize=16 * 1024 * 1024):
114
    """
115
    Return SHA-384 hash of a file.
116
117
    :param filepath: File you wish to verify.
118
    :type filepath: str
119
120
    :param blocksize: How much of file to read at once. Default is 16MB.
121
    :type blocksize: int
122
    """
123 4
    sha384 = hashlib.sha384()
124 4
    hashfunc_reader(filepath, sha384, blocksize)
125 4
    return sha384.hexdigest()
126
127
128 4
def hs512(filepath, blocksize=16 * 1024 * 1024):
129
    """
130
    Return SHA-512 hash of a file.
131
132
    :param filepath: File you wish to verify.
133
    :type filepath: str
134
135
    :param blocksize: How much of file to read at once. Default is 16MB.
136
    :type blocksize: int
137
    """
138 4
    sha512 = hashlib.sha512()
139 4
    hashfunc_reader(filepath, sha512, blocksize)
140 4
    return sha512.hexdigest()
141
142
143 4
def hs3224(filepath, blocksize=16 * 1024 * 1024):
144
    """
145
    Return SHA3-224 hash of a file.
146
147
    :param filepath: File you wish to verify.
148
    :type filepath: str
149
150
    :param blocksize: How much of file to read at once. Default is 16MB.
151
    :type blocksize: int
152
    """
153 4
    try:
154 4
        sha3224 = hashlib.sha3_224()
155 4
    except AttributeError:
156 4
        print("REQUIRES PYTHON 3.6+")
157
    else:
158
        hashfunc_reader(filepath, sha3224, blocksize)
159
        return sha3224.hexdigest()
160
161
162 4
def hs3256(filepath, blocksize=16 * 1024 * 1024):
163
    """
164
    Return SHA3-256 hash of a file.
165
166
    :param filepath: File you wish to verify.
167
    :type filepath: str
168
169
    :param blocksize: How much of file to read at once. Default is 16MB.
170
    :type blocksize: int
171
    """
172 4
    try:
173 4
        sha3256 = hashlib.sha3_256()
174 4
    except AttributeError:
175 4
        print("REQUIRES PYTHON 3.6+")
176
    else:
177
        hashfunc_reader(filepath, sha3256, blocksize)
178
        return sha3256.hexdigest()
179
180
181 4
def hs3384(filepath, blocksize=16 * 1024 * 1024):
182
    """
183
    Return SHA3-384 hash of a file.
184
185
    :param filepath: File you wish to verify.
186
    :type filepath: str
187
188
    :param blocksize: How much of file to read at once. Default is 16MB.
189
    :type blocksize: int
190
    """
191 4
    try:
192 4
        sha3384 = hashlib.sha3_384()
193 4
    except AttributeError:
194 4
        print("REQUIRES PYTHON 3.6+")
195
    else:
196
        hashfunc_reader(filepath, sha3384, blocksize)
197
        return sha3384.hexdigest()
198
199
200 4
def hs3512(filepath, blocksize=16 * 1024 * 1024):
201
    """
202
    Return SHA3-512 hash of a file.
203
204
    :param filepath: File you wish to verify.
205
    :type filepath: str
206
207
    :param blocksize: How much of file to read at once. Default is 16MB.
208
    :type blocksize: int
209
    """
210 4
    try:
211 4
        sha3512 = hashlib.sha3_512()
212 4
    except AttributeError:
213 4
        print("REQUIRES PYTHON 3.6+")
214
    else:
215
        hashfunc_reader(filepath, sha3512, blocksize)
216
        return sha3512.hexdigest()
217
218
219 4
def hm5(filepath, blocksize=16 * 1024 * 1024):
220
    """
221
    Return MD5 hash of a file.
222
223
    :param filepath: File you wish to verify.
224
    :type filepath: str
225
226
    :param blocksize: How much of file to read at once. Default is 16MB.
227
    :type blocksize: int
228
    """
229 4
    md5 = hashlib.md5()
230 4
    hashfunc_reader(filepath, md5, blocksize)
231 4
    return md5.hexdigest()
232
233
234 4
def hashfunc_reader(filepath, engine, blocksize=16 * 1024 * 1024):
235
    """
236
    Generate hash from file contents.
237
238
    :param filepath: File you wish to verify.
239
    :type filepath: str
240
241
    :param engine: Hash object to update with file contents.
242
    :type engine: _hashlib.HASH
243
244
    :param blocksize: How much of file to read at once. Default is 16MB.
245
    :type blocksize: int
246
    """
247 4
    with open(filepath, 'rb') as file:
248 4
        while True:
249 4
            data = file.read(blocksize)
250 4
            if not data:
251 4
                break
252 4
            engine.update(data)
253
254
255 4
def ssl_hash(filepath, method, blocksize=16 * 1024 * 1024):
256
    """
257
    Return SSL-library dependent hash of a file.
258
259
    :param filepath: File you wish to verify.
260
    :type filepath: str
261
262
    :param method: Method to use: algorithms in hashlib that are not guaranteed.
263
    :type method: str
264
265
    :param blocksize: How much of file to read at once. Default is 16MB.
266
    :type blocksize: int
267
    """
268 4
    try:
269 4
        engine = hashlib.new(method)
270 4
        hashfunc_reader(filepath, engine, blocksize)
271 4
        return engine.hexdigest()
272 4
    except ValueError as exc:
273 4
        msg = "{0} HASH FAILED".format(method.upper())
274 4
        exceptions.handle_exception(exc, msg, None)
275
276
277 4
def hm4(filepath, blocksize=16 * 1024 * 1024):
278
    """
279
    Return MD4 hash of a file; depends on system SSL library.
280
281
    :param filepath: File you wish to verify.
282
    :type filepath: str
283
284
    :param blocksize: How much of file to read at once. Default is 16MB.
285
    :type blocksize: int
286
    """
287 4
    return ssl_hash(filepath, "md4", blocksize)
288
289
290 4
def hr160(filepath, blocksize=16 * 1024 * 1024):
291
    """
292
    Return RIPEMD160 hash of a file; depends on system SSL library.
293
294
    :param filepath: File you wish to verify.
295
    :type filepath: str
296
297
    :param blocksize: How much of file to read at once. Default is 16MB.
298
    :type blocksize: int
299
    """
300 4
    return ssl_hash(filepath, "ripemd160", blocksize)
301
302
303 4
def hwp(filepath, blocksize=16 * 1024 * 1024):
304
    """
305
    Return Whirlpool hash of a file; depends on system SSL library.
306
307
    :param filepath: File you wish to verify.
308
    :type filepath: str
309
310
    :param blocksize: How much of file to read at once. Default is 16MB.
311
    :type blocksize: int
312
    """
313 4
    return ssl_hash(filepath, "whirlpool", blocksize)
314
315
316 4
def hs0(filepath, blocksize=16 * 1024 * 1024):
317
    """
318
    Return SHA-0 hash of a file; depends on system SSL library.
319
320
    :param filepath: File you wish to verify.
321
    :type filepath: str
322
323
    :param blocksize: How much of file to read at once. Default is 16MB.
324
    :type blocksize: int
325
    """
326 4
    return ssl_hash(filepath, "sha", blocksize)
327
328
329 4
def gpgfile(filepath, gpginst, key=None, pword=None):
330
    """
331
    Make ASCII-armored signature files with a given private key.
332
    Takes an instance of gnupg.GPG().
333
334
    :param filepath: File you wish to verify.
335
    :type filepath: str
336
337
    :param gpginst: Instance of Python GnuPG executable.
338
    :type gpginst: gnupg.GPG()
339
340
    :param key: Key ID. 0xABCDEF01
341
    :type key: str
342
343
    :param pword: Passphrase for key.
344
    :type pword: str
345
    """
346 4
    with open(filepath, "rb") as file:
347 4
        fname = file.name + ".asc"
348 4
        gpginst.sign_file(file, detach=True, keyid=key, passphrase=pword, output=fname)
349
350
351 4
def calculate_escreens(pin, app, uptime, duration=30):
352
    """
353
    Calculate key for the Engineering Screens based on input.
354
355
    :param pin: PIN to check. 8 character hexadecimal, lowercase.
356
    :type pin: str
357
358
    :param app: App version. 10.x.y.zzzz.
359
    :type app: str
360
361
    :param uptime: Uptime in ms.
362
    :type uptime: str
363
364
    :param duration: 1, 3, 6, 15, 30 (days).
365
    :type duration: str
366
    """
367
    #: Somehow, values for lifetimes for escreens.
368 4
    lifetimes = {
369
        1: "",
370
        3: "Hello my baby, hello my honey, hello my rag time gal",
371
        7: "He was a boy, and she was a girl, can I make it any more obvious?",
372
        15: "So am I, still waiting, for this world to stop hating?",
373
        30: "I love myself today, not like yesterday. "
374
    }
375 4
    lifetimes[30] += "I'm cool, I'm calm, I'm gonna be okay"
376
    #: Escreens magic HMAC secret.
377 4
    secret = 'Up the time stream without a TARDIS'
378 4
    duration = int(duration)
379 4
    if duration not in [1, 3, 6, 15, 30]:
380 4
        duration = 1
381 4
    data = pin.lower() + app + str(uptime) + lifetimes[duration]
382 4
    newhmac = hmac.new(secret.encode(), data.encode(), digestmod=hashlib.sha1)
383 4
    key = newhmac.hexdigest()[:8]
384 4
    return key.upper()
385
386
387 4
def hash_get(filename, hashfunc, workingdir, blocksize=16777216):
388
    """
389
    Generate and pretty format the hash result for a file.
390
391
    :param filename: File to hash.
392
    :type filename: str
393
394
    :param hashfunc: Hash function to use.
395
    :type hashfunc: function
396
397
    :param workingdir: Working directory.
398
    :type workingdir: str
399
400
    :param blocksize: Block size. Default is 16MB.
401
    :type blocksize: int
402
    """
403 4
    result = hashfunc(os.path.join(workingdir, filename), blocksize)
404 4
    return "{0} {1}\n".format(result.upper(), os.path.basename(filename))
405
406
407 4
def base_hash(hashtype, source, workingdir, block, hashfunc, target, kwargs=None):
408
    """
409
    Generic hash function; get hash, write to file.
410
411
    :param hashtype: Hash type.
412
    :type hashtype: str
413
414
    :param source: File to be hashed; foobar.ext
415
    :type source: str
416
417
    :param workingdir: Path containing files you wish to verify.
418
    :type workingdir: str
419
420
    :param block: Blocksize, in bytes.
421
    :type block: int
422
423
    :param target: File to write to.
424
    :type target: file
425
426
    :param kwargs: Values. Refer to `:func:verifier_config_loader`.
427
    :type kwargs: dict
428
    """
429 4
    if kwargs[hashtype]:
430 4
        hash_generic = [hashtype.upper()]
431 4
        hash_generic.append(hash_get(source, hashfunc, workingdir, block))
432 4
        target.write("\n".join(hash_generic))
433
434
435 4
def hash_writer(source, dest, workingdir, kwargs=None):
436
    """
437
    Write per-file hashes.
438
439
    :param source: File to be hashed; foobar.ext
440
    :type source: str
441
442
    :param dest: Destination file; foobar.ext.cksum
443
    :type dest: str
444
445
    :param workingdir: Path containing files you wish to verify.
446
    :type workingdir: str
447
448
    :param kwargs: Values. Refer to `:func:verifier_config_loader`.
449
    :type kwargs: dict
450
    """
451 4
    block = int(kwargs['blocksize'])
452 4
    with open(dest, 'w') as target:
453 4
        base_hash("adler32", source, workingdir, block, ha32, target, kwargs)
454 4
        base_hash("crc32", source, workingdir, block, hc32, target, kwargs)
455 4
        base_hash("md4", source, workingdir, block, hm4, target, kwargs)
456 4
        base_hash("md5", source, workingdir, block, hm5, target, kwargs)
457 4
        base_hash("sha0", source, workingdir, block, hs0, target, kwargs)
458 4
        base_hash("sha1", source, workingdir, block, hs1, target, kwargs)
459 4
        base_hash("sha224", source, workingdir, block, hs224, target, kwargs)
460 4
        base_hash("sha256", source, workingdir, block, hs256, target, kwargs)
461 4
        base_hash("sha384", source, workingdir, block, hs384, target, kwargs)
462 4
        base_hash("sha512", source, workingdir, block, hs512, target, kwargs)
463 4
        base_hash("ripemd160", source, workingdir, block, hr160, target, kwargs)
464 4
        base_hash("whirlpool", source, workingdir, block, hwp, target, kwargs)
465 4
        base_hash("sha3224", source, workingdir, block, hs3224, target, kwargs)
466 4
        base_hash("sha3256", source, workingdir, block, hs3256, target, kwargs)
467 4
        base_hash("sha3384", source, workingdir, block, hs3384, target, kwargs)
468 4
        base_hash("sha3512", source, workingdir, block, hs3512, target, kwargs)
469
470
471 4
def filefilter(file, workingdir, extras=()):
472
    """
473
    Check if file in folder is a folder, or if it's got a forbidden extension.
474
475
    :param file: File to be hashed.
476
    :type file: str
477
478
    :param workingdir: Path containing files you wish to verify.
479
    :type workingdir: str
480
481
    :param extras: Tuple of extra extensions.
482
    :type extras: tuple
483
    """
484 4
    return not (os.path.isdir(os.path.join(workingdir, file)) or file.endswith(bbconstants.SUPPS + extras))
485
486
487 4
def prep_verifier(ldir, selective=False):
488
    """
489
    Prepare files for verifier function.
490
491
    :param ldir: Path containing files you wish to verify.
492
    :type ldir: str
493
494
    :param selective: Filtering filenames/extensions. Default is false.
495
    :type selective: bool
496
    """
497 4
    exts = (".txt",) if selective else ()
498 4
    fxs = [os.path.join(ldir, afx) for afx in os.listdir(ldir) if filefilter(afx, ldir, exts)]
499 4
    return fxs
500
501
502 4
def verifier(ldir, kwargs=None, selective=False):
503
    """
504
    For all files in a directory, perform various hash/checksum functions.
505
    Take dict to define hashes, write output to a/individual .cksum file(s).
506
507
    :param ldir: Path containing files you wish to verify.
508
    :type ldir: str
509
510
    :param kwargs: Values. Refer to `:func:verifier_config_loader`.
511
    :type kwargs: dict
512
513
    :param selective: Filtering filenames/extensions. Default is false.
514
    :type selective: bool
515
    """
516 4
    kwargs = verifier_config_loader() if kwargs is None else kwargs
517 4
    fxs = prep_verifier(ldir, selective)
518 4
    with concurrent.futures.ThreadPoolExecutor(max_workers=utilities.workers(fxs)) as xec:
519 4
        for file in fxs:
520 4
            verifier_individual(xec, ldir, file, kwargs)
521
522
523 4
def verifier_individual(xec, ldir, file, kwargs):
524
    """
525
    Individually verify files through a ThreadPoolExecutor.
526
527
    :param xec: ThreadPoolExecutor instance.
528
    :type xec: concurrent.futures.ThreadPoolExecutor
529
530
    :param ldir: Path containing files you wish to verify.
531
    :type ldir: str
532
533
    :param file: Filename.
534
    :type file: str
535
536
    :param kwargs: Values. Refer to `:func:verifier_config_loader`.
537
    :type kwargs: dict
538
    """
539 4
    print("HASHING:", os.path.basename(file))
540 4
    basename = file + ".cksum"
541 4
    targetname = os.path.join(ldir, basename)
542 4
    try:
543 4
        xec.submit(hash_writer, file, targetname, ldir, kwargs)
544 4
    except Exception as exc:
1 ignored issue
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
545 4
        exceptions.handle_exception(exc)
546
547
548 4
def gpgrunner(workingdir, keyid=None, pword=None, selective=False):
549
    """
550
    Create ASCII-armored PGP signatures for all files in a given directory, in parallel.
551
552
    :param workingdir: Path containing files you wish to verify.
553
    :type workingdir: str
554
555
    :param keyid: Key to use. 8-character hexadecimal, with or without 0x.
556
    :type keyid: str
557
558
    :param pword: Passphrase for given key.
559
    :type pword: str
560
561
    :param selective: Filtering filenames/extensions. Default is false.
562
    :type selective: bool
563
    """
564 4
    try:
565 4
        gpg = gnupg.GPG()
566 4
    except ValueError:
567 4
        print("COULD NOT FIND GnuPG!")
568 4
        raise SystemExit
569
    else:
570 4
        gpgrunner_clean(gpg, workingdir, keyid, pword, selective)
571
572
573 4
def prep_gpgkeyid(keyid=None):
574
    """
575
    Prepare GPG key ID.
576
577
    :param keyid: Key to use. 8-character hexadecimal, with or without 0x.
578
    :type keyid: str
579
    """
580 4
    return "0x" + keyid.upper() if not keyid.startswith("0x") else keyid.upper().replace("X", "x")
581
582
583 4
def prep_gpgrunner(workingdir, keyid=None):
584
    """
585
    Prepare key and files for gpgrunner function.
586
587
    :param workingdir: Path containing files you wish to verify.
588
    :type workingdir: str
589
590
    :param keyid: Key to use. 8-character hexadecimal, with or without 0x.
591
    :type keyid: str
592
    """
593 4
    keyid = prep_gpgkeyid(keyid)
594 4
    dirlist = os.listdir(workingdir)
595 4
    files = [file for file in dirlist if filefilter(file, workingdir)]
596 4
    return keyid, files
597
598
599 4
def gpgrunner_clean(gpg, workingdir, keyid=None, pword=None, selective=False):
600
    """
601
    Run GPG signature generation after filtering out errors.
602
603
    :param gpg: Instance of Python GnuPG executable.
604
    :type gpg: gnupg.GPG()
605
606
    :param workingdir: Path containing files you wish to verify.
607
    :type workingdir: str
608
609
    :param keyid: Key to use. 8-character hexadecimal, with or without 0x.
610
    :type keyid: str
611
612
    :param pword: Passphrase for given key.
613
    :type pword: str
614
615
    :param selective: Filtering filenames/extensions. Default is false.
616
    :type selective: bool
617
    """
618 4
    keyid, files = prep_gpgrunner(workingdir, keyid)    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
619 4
    with concurrent.futures.ThreadPoolExecutor(max_workers=utilities.workers(files)) as xec:
620 4
        for file in files:
621 4
            gpgwriter(gpg, xec, file, workingdir, selective, keyid, pword)
622
623
624 4
def gpgwriter(gpg, xec, file, workingdir, selective=False, keyid=None, pword=None):
625
    """
626
    Write individual GPG signatures.
627
628
    :param gpg: Instance of Python GnuPG executable.
629
    :type gpg: gnupg.GPG()
630
631
    :param xec: ThreadPoolExecutor instance.
632
    :type xec: concurrent.futures.ThreadPoolExecutor
633
634
    :param file: File inside workingdir that is being verified.
635
    :type file: str
636
637
    :param workingdir: Path containing files you wish to verify.
638
    :type workingdir: str
639
640
    :param selective: Filtering filenames/extensions. Default is false.
641
    :type selective: bool
642
643
    :param keyid: Key to use. 8-character hexadecimal, with or without 0x.
644
    :type keyid: str
645
646
    :param pword: Passphrase for given key.
647
    :type pword: str
648
    """
649 4
    sup = bbconstants.SUPPS + (".txt",) if selective else bbconstants.SUPPS
650 4
    if not file.endswith(sup):
651 4
        aps = bbconstants.ARCSPLUS
652 4
        pfx = bbconstants.PREFIXES
653 4
        if (utilities.prepends(file, pfx, aps)) if selective else True:
654 4
            gpgwriter_clean(gpg, xec, file, workingdir, keyid, pword)
655
656
657 4
def gpgwriter_clean(gpg, xec, file, workingdir, keyid=None, pword=None):
658
    """
659
    Write individual GPG signatures after filtering file list.
660
661
    :param gpg: Instance of Python GnuPG executable.
662
    :type gpg: gnupg.GPG()
663
664
    :param xec: ThreadPoolExecutor instance.
665
    :type xec: concurrent.futures.ThreadPoolExecutor
666
667
    :param file: File inside workingdir that is being verified.
668
    :type file: str
669
670
    :param workingdir: Path containing files you wish to verify.
671
    :type workingdir: str
672
673
    :param keyid: Key to use. 8-character hexadecimal, with or without 0x.
674
    :type keyid: str
675
676
    :param pword: Passphrase for given key.
677
    :type pword: str
678
    """
679 4
    print("VERIFYING:", os.path.basename(file))
680 4
    thepath = os.path.join(workingdir, file)
681 4
    try:
682 4
        xec.submit(gpgfile, thepath, gpg, keyid, pword)
683 4
    except Exception as exc:
1 ignored issue
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
684 4
        exceptions.handle_exception(exc)
685
686
687 4
def gpg_config_loader(homepath=None):
688
    """
689
    Read a ConfigParser file to get PGP key, password (optional)
690
691
    :param homepath: Folder containing ini file. Default is user directory.
692
    :type homepath: str
693
    """
694 4
    config = iniconfig.generic_loader('gpgrunner', homepath)
695 4
    gpgkey = config.get('key', fallback=None)
696 4
    gpgpass = config.get('pass', fallback=None)
697 4
    return gpgkey, gpgpass
698
699
700 4
def gpg_config_writer(key=None, password=None, homepath=None):
701
    """
702
    Write a ConfigParser file to store PGP key, password (optional)
703
704
    :param key: Key ID, leave as None to not write.
705
    :type key: str
706
707
    :param password: Key password, leave as None to not write.
708
    :type password: str
709
710
    :param homepath: Folder containing ini file. Default is user directory.
711
    :type homepath: str
712
    """
713 4
    results = {}
714 4
    if key is not None:
715 4
        results["key"] = key
716 4
    if password is not None:
717 4
        results["pass"] = password
718 4
    iniconfig.generic_writer("gpgrunner", results, homepath)
719
720
721 4
def verifier_config_loader(homepath=None):
722
    """
723
    Read a ConfigParser file to get hash preferences.
724
725
    :param homepath: Folder containing ini file. Default is user directory.
726
    :type homepath: str
727
    """
728 4
    ini = iniconfig.generic_loader("hashmodes", homepath)
729 4
    results = {}
730 4
    results['crc32'] = bool(ini.getboolean('crc32', fallback=False))
731 4
    results['adler32'] = bool(ini.getboolean('adler32', fallback=False))
732 4
    results['sha0'] = bool(ini.getboolean('sha0', fallback=False))
733 4
    results['sha1'] = bool(ini.getboolean('sha1', fallback=True))
734 4
    results['sha224'] = bool(ini.getboolean('sha224', fallback=False))
735 4
    results['sha256'] = bool(ini.getboolean('sha256', fallback=True))
736 4
    results['sha384'] = bool(ini.getboolean('sha384', fallback=False))
737 4
    results['sha512'] = bool(ini.getboolean('sha512', fallback=False))
738 4
    results['md5'] = bool(ini.getboolean('md5', fallback=True))
739 4
    results['md4'] = bool(ini.getboolean('md4', fallback=False))
740 4
    results['ripemd160'] = bool(ini.getboolean('ripemd160', fallback=False))
741 4
    results['whirlpool'] = bool(ini.getboolean('whirlpool', fallback=False))
742 4
    results['blocksize'] = int(ini.getint('blocksize', fallback=16777216))
743 4
    results['sha3224'] = bool(ini.getboolean('sha3224', fallback=False))
744 4
    results['sha3256'] = bool(ini.getboolean('sha3256', fallback=False))
745 4
    results['sha3384'] = bool(ini.getboolean('sha3384', fallback=False))
746 4
    results['sha3512'] = bool(ini.getboolean('sha3512', fallback=False))
747 4
    return results
748
749
750 4
def verifier_config_writer(resultdict=None, homepath=None):
751
    """
752
    Write a ConfigParser file to store hash preferences.
753
754
    :param resultdict: Dictionary of results: {method, bool}
755
    :type resultdict: dict({str, bool})
756
757
    :param homepath: Folder containing ini file. Default is user directory.
758
    :type homepath: str
759
    """
760 4
    if resultdict is None:
761 4
        resultdict = verifier_config_loader()
762 4
    results = {method: str(flag).lower() for method, flag in resultdict.items()}
763
    iniconfig.generic_writer("hashmodes", results, homepath)
764