fillinsha256sum: create nicer filenames
[pgp-tools.git] / gpgparticipants / fillinsha256sum.py
1 #!/usr/bin/env python2
2
3 __author__ = "Stefan Huber <shuber@sthu.org>"
4
5 import sys
6 import hashlib
7 import getopt
8
9
10 def insertspaces(s):
11 """Inserts a space after every 4-th character, and three spaces after every
12 8-th character of string s."""
13
14 def inpacks(s, n):
15 while len(s) > 0:
16 yield s[0:n]
17 s = s[n:]
18
19 out = " ".join([ " ".join(inpacks(octp, 4)) for octp in inpacks(s, 8)])
20 return out
21
22
23 def range_hex(length):
24 """Give all hex-strings from 00...0 until ff...f of given length."""
25
26 if length == 0:
27 yield ""
28
29 elif length == 1:
30 for c in "0123456789abcdef":
31 yield c
32 elif length > 1:
33 for prefix in range_hex(length-1):
34 for postfix in range_hex(1):
35 yield prefix + postfix
36
37
38 def usage():
39 """Print --help text"""
40
41 print("""Usage:
42 {0} <emptylist> <filledlist>
43 {0} --help
44 {0} -h
45
46 Takes a file produced by gpgparticipants as <emptylist> and trys to fill in
47 some digits into the SHA256 field such that the resulting list actually has
48 a SHA256 checksum that starts with those digits. Whenever a match is found a
49 file with the digits filled in is written to `<filledlist>.DIGITS`.
50
51 OPTIONS:
52
53 --fastforward If a match is found of given length and --fastforward
54 is given then the programm immediately jumps to the next
55 length.
56 --min-length NUM Start looking for hex strings of given length
57
58 """.format(sys.argv[0]))
59
60 if __name__ == "__main__":
61
62 fastforward = False
63 minlength = 1
64
65 optlist, args = getopt.getopt(sys.argv[1:], 'h', ['fastforward', 'min-length='])
66 for o, a in optlist:
67
68 if o in ("-h", "--help"):
69 usage()
70 exit(0)
71
72 if o in ("--fastforward"):
73 fastforward = True
74
75 if o in ("--min-length"):
76 minlength = int(a)
77
78 if len(args) < 2:
79 print >>sys.stderr, "You need to give two filenames."""
80 exit(1)
81
82 emptyfile = open(args[0]).read()
83
84 idx = emptyfile.find("SHA256 Checksum:")
85 idx = emptyfile.find("_", idx)
86
87 for l in range(minlength, 32):
88 print "Looking at length", l
89
90 for h in range_hex(l):
91
92 H = insertspaces(h.upper())
93 filledfile = emptyfile[:idx] + H + emptyfile[idx+len(H):]
94 actual = hashlib.sha256(filledfile).hexdigest()
95
96 if actual[:len(h)] == h:
97 print "Found: ", H
98 open(args[1] + "." + h, "w").write(filledfile)
99
100 if fastforward:
101 break