trezor / python-mnemonic

:snake: Mnemonic code for generating deterministic keys, BIP39
https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
MIT License
843 stars 372 forks source link

[FR] encode arbitrary binary file as a list of words #85

Closed NightMachinery closed 3 years ago

NightMachinery commented 3 years ago

I like to be able to do

cat some.png | encode_mnemonic

And get a string of words.

There should obviously also be a decoding function.

prusnak commented 3 years ago

Use the following code:

from mnemonic import Mnemonic
from hashlib import sha256

f = "some.png"
e = sha256(open(f, "rb").read()).digest()
m = Mnemonic("english").to_mnemonic(e)

print(m)

If you need 12 words instead of 24 words, replace e = sha256(open(f, "rb").read()).digest() with the following:

e = sha256(open(f, "rb").read()).digest()
e = e[:16]
NightMachinery commented 3 years ago

@prusnak This is also cool, but I meant to encode the whole binary file, not to seed a key from it.

prusnak commented 3 years ago

@prusnak This is also cool, but I meant to encode the whole binary file, not to seed a key from it.

Ah, this is not a good idea. 10KB file would expand into 7680 words and you don't want to write that down.

NightMachinery commented 3 years ago

@prusnak A gpg private key can be less than 1 KB, and I want to print it anyway.

prusnak commented 3 years ago
from mnemonic import Mnemonic

f = "foo.txt"
d = open(f, "rb").read()

def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i + n].ljust(n, b'\0')

m = Mnemonic("english")
for c in chunks(d, 32):
  print(m.to_mnemonic(c))
NightMachinery commented 3 years ago

@prusnak How do I decode it back? Looking at the available methods, none seem suitable:

In [40]: dir(m)
Out[40]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_get_directory',
 'check',
 'detect_language',
 'expand',
 'expand_word',
 'generate',
 'language',
 'list_languages',
 'normalize_string',
 'radix',
 'to_entropy',
 'to_hd_master_key',
 'to_mnemonic',
 'to_seed',
 'wordlist']