-
Notifications
You must be signed in to change notification settings - Fork 0
/
hbkdf
executable file
·54 lines (45 loc) · 1.63 KB
/
hbkdf
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
#!/usr/bin/env python3
# Brief:
# A basic key-derivation-function with a Hashcash-like PoW.
# The Hashcash method employed here uses the following pseudocode:
#
# curr_hash=hash(input)
# token=init_value
# loop until curr_hash has n trailing zeroes
# curr_hash=hash(curr_hash+token)
# token=increment(token)
#
# The ordered iteration ensures the algorithm cannot be sped up using multithreading.
#
# Usage:
# ./hashcash <text> <number of trailing zeroes in hex representation of target hash>
#
# Adapted from https://gist.github.com/i3visio/388ef5154052ed8173df4b7b9eda541b
import hashlib, math, itertools, sys
def trailing_zeros(n):
"""Number of trailing 0s in binary representation of integer n."""
if n <= 0: return 0
for i in itertools.count(0):
if n & (1<<i): return i
def irange(n):
"""Implementation of xrange(n) that does not overflow."""
i = 0
while i < n:
yield i; i += 1
def all_strings(charset='0123456789ABCDEF'):
"""Yields all strings in given character set, sorted by length."""
m = len(charset)
for n in itertools.count(0):
for i in irange(m**n):
yield ''.join([charset[(i//(m**j))%m] for j in range(n)])
def make_token(s, n, charset='0123456789ABCDEF'):
"""Makes hashcash token of value 'n' against basestring 's'."""
h = hashlib.sha512(s.encode()).hexdigest()
for token in all_strings(charset):
h=hashlib.sha512(h.encode()+token.encode()).hexdigest()
if trailing_zeros(int(h,16)) >= n: return [token,h]
key=sys.argv[1]
nzeroes=sys.argv[2]
output=make_token(key,4*int(nzeroes))
print("Key: ",output[0])
print("Final SHA512: ",output[1])