Generating private key (as string) from generated Uint8Array #28
-
Hi, I am using your libraries as follows to generate the Uint8Array: const mn = bip39.generateMnemonic(wordlist);
const seed = await bip39.mnemonicToSeed(mn); I am curious how I get proceed further to also generate the private key as a string. I tried this trying to imitate the README https://github.com/paulmillr/noble-hashes#usage const privateKey = bytesToHex(sha256(seed)) Any guidance appreciated! Thanks for your awesome work. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I assume you're talking about secp256k1. secp256k1 can receive 32 bytes as private key. It can directly work with Uint8Arrays. const mn = bip39.generateMnemonic(wordlist);
const seed = await bip39.mnemonicToSeed(mn);
const privateKey = seed.slice(0, 32);
const publicKey = secp256k1.getPublicKey(privateKey); There is a caveat: not all 32-byte values are not valid private keys. E.g. const mn = bip39.generateMnemonic(wordlist);
const seed = await bip39.mnemonicToSeed(mn);
const privateKeyN = secp256k1.utils.mod(BigInt('0x' + bytesToHex(seed)))); // number
const privateKey = privateKeyN.toString(16).padStart(64, '0'); // hex string
const publicKey = secp256k1.getPublicKey(privateKey); If you're talking about ed25519, any 32-bit string/uint8array is fine - no need to do utils.mod. |
Beta Was this translation helpful? Give feedback.
-
thank you! |
Beta Was this translation helpful? Give feedback.
I assume you're talking about secp256k1. secp256k1 can receive 32 bytes as private key. It can directly work with Uint8Arrays.
mnemonicToSeed
produces 64 bytes of output. Which means you can strip its 32 bytes:There is a caveat: not all 32-byte values are not valid private keys. E.g.
"ff".repeat(32)
is not a valid key becasuse it's bigger thanCURVE.n
. You can modulo divide it to get a valid key in these rare circumstances: