Generate Mnemonic Phrase from window.crpyto.subtle.generateKey

917 views Asked by At

I am developing and web based end to end encrypted chat website. For that I am generating private keys using the window.crypto.subtle.generateKey function provided in the web crypto api.

I want the user to remember or store a mnemonic phrase like we use in ethereum wallets instead of an encryption key.

Is there a way to generate the mnemonic phrase from the private key that is generated by the window.crypto.subtle.generateKey function or is there any other way I should go to implement this?

Thanks in advance

2

There are 2 answers

3
Petr Hejda On BEST ANSWER

Is there a way to generate the mnemonic phrase from the private key

It's the other way around. A set of private keys can be determined from each mnemonic phrase - but you can't determine a mnemonic from a private key.


A widely-used standard is BIP-39. Even though it was first introduced as a Bitcoin Improvement Protocol, many Ethereum wallets use it too. You can find its JS implementation in this package for example.

Note: You're looking for functions mnemonicToSeed() and mnemonicToSeedSync(). Even though it might seem at the first look that entropyToMnemonic() translates private key to the phrase, it's not true - the entropy numbers are just positions of the words in the wordlist, not the private key bytes.

0
Lekhaka Ananta On

What you want, as you describe it, is to encode your private key into mnemonic words. Which you totally can, with the simplest example being: split up the key into chunks of n-bits, and match each chunk to a word list consisting of 2^n words.

Whether you actually want this for your overall purposes is a different question.

I'd also like to expand on Petr Hejda's answer, which at first confused me, but I now understand.

Petr is using the definition of "private key" in a different context than in the question. Petr is referring to "private keys" in terms of the bitcoin protocol, where the mnemonic is not used as an encoding for private keys, but to generate a seed which may then be used to generate any number of keys deterministically (BIP-0032), so that such generated keys can be re-generated when using the same seed, which in turn can be re-generated from the mnemonic. In this protocol, the mnemonic-to-seed is defined, but seed-to-mnemonic is not, because the protocol never does that. It only generates mnemonics from entropy, and then generate the seed from the mnemonic.

But in your case, you can simply feed it your "private key" (as you've defined it) as the "entropy" input in the entropyToMnemonic() function, and it will give you the mnemonic encoding of the "private key" that you wanted. You'll still have to decode it yourself though, as the BIP39 package doesn't have that functionality.