I'm running a tutorial on how to sign an ethereum transaction programmatically, and I'm getting the following error:

RangeError: private key length is invalid

This is the code:

var Web3 = require('web3');
var web3 = new Web3(new 
var util = require('ethereumjs-util');
var tx = require('ethereumjs-tx');

var privateKey = '0x...';
var publicKey = util.bufferToHex(util.privateToPublic(privateKey));

The error is on the last line, that attempts to get the public key from the private key.

My private key is an alphanumeric string with a length of 64 characters. From all I can see it's the correct length.

What am I missing?


According to the docs util.privateToPublic() expects a buffer. Try feeding it something more like:

new Buffer(privateKey.substring(2,66), 'hex')

  • 1
    Yes, that clears the error, thanks. new Buffer() btw is deprecated, so should be Buffer.from().
    – Eddy
    Jul 25 '18 at 6:22

try to remove the 0x from the privatekey

privKey = privKey.substring(2)

I'm not sure. Different ethereum libs have different key rules.

EthersJS for example enforces 0x across the board where others might not.

  • Same error, after removing it.
    – Eddy
    Jul 24 '18 at 17:02
  • 1
    Why would someone dislike this answer. Solved my problem and saved my day :)) Dec 25 '19 at 15:29

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.