Web3js – Can Web3.eth.sign With Private Key: A Detailed Guide

signatureweb3js

I want to use web3.eth.sign to create a signature that will be stored in blockchain and verified later by a contract (with ecrecover). I'd like to use as few libraries as possible.

Web3 docs specify that to use web3.eth.sign a public key should be provided and account should be unlocked.

  1. can I unlock an account without running an ethereum node?
  2. I know private key for this account, can I create signature using private key instead of public key and without unlocking? Seems like it can be done with a help of secp256k1 package, but is this doable with web3 alone?

Best Answer

  1. N/A, in that you don't need to unlock an account at all.
  2. Yes, see below.

The following uses Web3.js version 1.0.0-beta which is now the default installed by npm. Note that no node is attached.

> var Web3 = require('web3');
> var web3 = new Web3();
> web3.version
'1.0.0-beta.10'

The second parameter in the below is the private key:

> web3.eth.accounts.sign("Hello, world!", '0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef')
{ message: 'Hello, world!',
  messageHash: '0xb453bd4e271eed985cbab8231da609c4ce0a9cf1f763b6c1594e76315510e0f1',
  v: '0x1b',
  r: '0x3bc843a917d6c19c487c1d0c660cdd61389ce2a7651ee3171bcc212ffddca164',
  s: '0x193f1f2e06f7ed8f9fbf2254232d99848a8102b552032b68a5507b4d81492f0f',
  signature: '0x3bc843a917d6c19c487c1d0c660cdd61389ce2a7651ee3171bcc212ffddca164193f1f2e06f7ed8f9fbf2254232d99848a8102b552032b68a5507b4d81492f0f1b' }

And the signature checks out, too (the recovered account is the same as the account generated from the private key directly):

> web3.eth.accounts.recover('0xb453bd4e271eed985cbab8231da609c4ce0a9cf1f763b6c1594e76315510e0f1', '0x1b', '0x3bc843a917d6c19c487c1d0c660cdd61389ce2a7651ee3171bcc212ffddca164', '0x193f1f2e06f7ed8f9fbf2254232d99848a8102b552032b68a5507b4d81492f0f')
'0xFCAd0B19bB29D4674531d6f115237E16AfCE377c'
>
> web3.eth.accounts.privateKeyToAccount('0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef');
{ address: '0xFCAd0B19bB29D4674531d6f115237E16AfCE377c',
  privateKey: '0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
...}