1

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 
Web3.providers.HttpProvider('https://ropsten.infura.io/'));
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?

2 Answers 2

3

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

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

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

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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