wordmap/wordmap.py

60 lines
1.8 KiB
Python
Raw Permalink Normal View History

2021-02-17 09:38:46 +00:00
#!/usr/bin/env python3
from sys import argv
2021-02-18 18:26:09 +00:00
from hashlib import blake2b
def hashfun(input: str, digest_size: int = 4): # digest size is in bytes
hash = blake2b(bytes(input, "utf-8"), digest_size=digest_size)
input_hash = int(hash.hexdigest(), 16)
return input_hash
2021-02-17 09:38:46 +00:00
2021-02-18 06:57:36 +00:00
def load_words(wordlist_file: str):
2021-02-17 09:38:46 +00:00
with open(wordlist_file) as word_file:
valid_words = sorted(set(word_file.read().split("\n")))
return valid_words
2021-02-18 18:26:09 +00:00
def scale(val: int, src, dst):
2021-02-18 06:57:36 +00:00
# Scale the given value from the scale of src to the scale of dst.
2021-02-17 09:38:46 +00:00
return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0]
2021-02-18 18:26:09 +00:00
def wordmap(wordlist_file: str, input: str, digest_size: int = 4):
2021-02-18 06:57:36 +00:00
words = load_words(wordlist_file)
2021-02-18 18:26:09 +00:00
words_max = len(words)
digest_max = int.from_bytes(b'\xff' * digest_size, "big")
input_hash = hashfun(input, digest_size=digest_size)
# digest_max+1 is so that it can round up to the max
input_hash_mapped = scale(input_hash, (0, digest_max+1), (0, words_max))
2021-02-19 12:22:51 +00:00
# alternatively, change round() to math.floor()
2021-02-18 18:26:09 +00:00
input_hash_mapped = round(input_hash_mapped)
print(words[input_hash_mapped], end="")
2021-02-18 06:57:36 +00:00
if __name__ == "__main__":
2021-02-18 18:26:09 +00:00
def usage():
2021-02-19 12:22:51 +00:00
print(
f"Usage: {argv[0]} " +
"<wordlist file> " +
"<string to hash> " +
"[string to append]")
2021-02-18 06:57:36 +00:00
quit(1)
2021-02-18 18:26:09 +00:00
try:
if argv[1] == "-h" or argv[1] == "--help":
usage()
wordlist_file = argv[1]
input = argv[2]
try:
2021-02-19 12:22:51 +00:00
extrawords = argv[3]
except IndexError:
2021-02-19 12:22:51 +00:00
extrawords = ""
2021-02-18 18:26:09 +00:00
except IndexError:
usage()
2021-02-19 12:22:51 +00:00
# input = "example"
# wordlist_file = "wordlists/term16color.txt"
2021-02-18 18:26:09 +00:00
wordmap(wordlist_file, input)
print(extrawords+"\x1b[0m")