12

I am trying to create a private key and its corresponding public key using EthereumJS library. So far so good I've been able to create private keys using keythereum.create() method. Nevertheless I find myself stuck when dealing with public key.

I heard using Elliptic Curve Digital Signature Algorithm (ECDSA) it is possible to get an Ethereum Public Key (64 bytes long) from its Private Key. The question is how can I code this process using EthereumJS library. Maybe there is some simple method to derive public key, but I cannot find it. Any help will be appreciated.

I found some limited info on previous StackExchange questions but I would prefer an answer focused on EthereumJS:

How are ethereum addresses generated?

Creating keyfile and address from private key

Thanks!

15

ethereumjs-wallet can be used to get public key from private key:

> const hdkey = require('ethereumjs-wallet/hdkey')
> const privateKey = hdkey.fromMasterSeed('random')._hdkey._privateKey
> const Wallet = require('ethereumjs-wallet')
> const wallet = Wallet.fromPrivateKey(privateKey)
> wallet.getPublicKeyString()
'0x11f2b30c9479ccaa639962e943ca7cfd3498705258ddb49dfe25bba00a555e48cb35a79f3d084ce26dbac0e6bb887463774817cb80e89b20c0990bc47f9075d5'
> wallet.getPublicKey()
<Buffer 11 f2 b3 0c 94 79 cc aa 63 99 62 e9 43 ca 7c fd 34 98 70 52 58 dd b4 9d fe 25 bb a0 0a 55 5e 48 cb 35 a7 9f 3d 08 4c e2 6d ba c0 e6 bb 88 74 63 77 48 ... >

Another option is to use ethereumjs-util (which is used by ethereumjs-wallet internally):

> const util = require('ethereumjs-util')
> util.privateToPublic(privateKey)
<Buffer 11 f2 b3 0c 94 79 cc aa 63 99 62 e9 43 ca 7c fd 34 98 70 52 58 dd b4 9d fe 25 bb a0 0a 55 5e 48 cb 35 a7 9f 3d 08 4c e2 6d ba c0 e6 bb 88 74 63 77 48 ... >

Yet another option is secp256k1:

> const secp256k1 = require('secp256k1')
> secp256k1.publicKeyCreate(privateKey, false).slice(1)
<Buffer 11 f2 b3 0c 94 79 cc aa 63 99 62 e9 43 ca 7c fd 34 98 70 52 58 dd b4 9d fe 25 bb a0 0a 55 5e 48 cb 35 a7 9f 3d 08 4c e2 6d ba c0 e6 bb 88 74 63 77 48 ... >

slice(1) is to drop type byte which is hardcoded as 04 ethereum.

  • How do you convert a string pk into a buffer for usage with the above methods ? tried new Buffer(pk, 'hex') but didn't work. – Rayjax Dec 20 '17 at 23:46
  • 1
    @Rayjax, you can try toBuffer from ethereumjs-util – max taldykin Dec 21 '17 at 9:40
  • How to use ethereumjs-wallet? There is not a package in npm to use npm install to install the dependency – Frankie Jun 22 '18 at 13:17
  • @Frankie, You can install it from npm regitsry: npm i ethereumjs-wallet – max taldykin Jun 25 '18 at 4:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.