]> git.friedersdorff.com Git - max/mnemkey.git/commitdiff
Backup arbitrary file as BIP39 mnemonic
authorMaximilian Friedersdorff <max@friedersdorff.com>
Sat, 18 Jul 2020 18:18:11 +0000 (19:18 +0100)
committerMaximilian Friedersdorff <max@friedersdorff.com>
Sat, 18 Jul 2020 18:18:11 +0000 (19:18 +0100)
mnemonic_key.py [new file with mode: 0644]

diff --git a/mnemonic_key.py b/mnemonic_key.py
new file mode 100644 (file)
index 0000000..908221d
--- /dev/null
@@ -0,0 +1,41 @@
+import hashlib
+import math
+
+
+def access_bit(data, num):
+    base = int(num // 8)
+    shift = int(num % 8)
+    return (data[base] & (1 << shift)) >> shift
+
+
+with open("./input.gpg", "rb") as f:
+    bs = bytearray(f.read())
+
+with open("./english.txt", "r") as wordlist:
+    words = [word.strip() for word in wordlist.readlines() if word.strip()]
+
+digest = hashlib.sha256(bs).digest()
+
+
+bits = [access_bit(bs, i) for i in range(len(bs) * 8)]
+checksum_bits = [access_bit(digest, i) for i in range(len(digest) * 8)]
+
+n_bits = len(bits)
+nearest_mulitple_of_11 = math.floor((n_bits/11) + 1) * 11
+bits_missing = nearest_mulitple_of_11 - n_bits
+bits += checksum_bits[0:bits_missing]
+
+
+mnemonic = []
+for i in range(0, len(bits), 11):
+    word_bits = bits[i:i+11]
+    word_int = 0
+    for j, bit in enumerate(word_bits):
+        word_int += bit << j
+    word = words[word_int] + "                    "
+    mnemonic.append(word[0:10])
+
+mnemonic += [""] * 5
+mnemonics = [mnemonic[i:i+5] for i in range(0, len(mnemonic), 5)]
+for m in mnemonics:
+    print("".join(m))