ethereumjs-wallet icon indicating copy to clipboard operation
ethereumjs-wallet copied to clipboard

fromPrivateKey issue

Open brightsider opened this issue 6 years ago • 1 comments

I can import wallet with privateKey + 1 random character. How to fix it?

let key = privateKey
if (key.startsWith('0x')) {
    key = key.substring(2)
}
let buf = Buffer.from(key, 'hex')
let result = ethereumjs.fromPrivateKey(buf)
let publicKey = '0x' + result.getAddress().toString('hex')
if (publicKey.toLowerCase() === address.toLowerCase()) {
    return privateKey
}

brightsider avatar Feb 27 '19 11:02 brightsider

This is owing to the behavior of Node's built in Buffer.from. In a Node REPL:

> Buffer.from('ff', 'hex')
<Buffer ff>
> Buffer.from('fF' + 'f', 'hex')
<Buffer ff>
> Buffer.from('ff' + 'Z', 'hex')
<Buffer ff>
> Buffer.from('ffpff', 'hex')
<Buffer ff>
> Buffer.from('Rffff', 'hex')
<Buffer >
> Buffer.from('frf', 'hex')
<Buffer >

That is, the function trims off the trailing character so that the input is the longest possible even number of hex characters. Note that Buffer.from also normalizes to lower case and the trimmed character/s may not even be valid hex. If the first two characters are not valid hex then you get an empty buffer, i.e. the same as Buffer.from('', 'hex').

There's nothing I see that ethereumjs-wallet can do to help in this situation since it's trimmed before fromPrivateKey is invoked.

michaelsbradleyjr avatar Aug 26 '19 19:08 michaelsbradleyjr