Why the private key is generating different public address

cryptographyellipticprivate-keypublic-keywallets

I'm using that Javascript code to generate three things: private key, public key and public address (last 40 characters from public key):

const EC = require('elliptic').ec;
const ec = new EC('secp256k1');

const key = ec.genKeyPair();
const publicKey = key.getPublic('hex');
const privateKey = key.getPrivate('hex');

console.log();
console.log('Private key: ', privateKey);

console.log();
console.log('Public key (big): ', publicKey);

console.log();
console.log('Public key (shorten): ', publicKey.slice(-40));

Although that code generates a private key, when I import that private key to Metamask (or other Ethereum wallet) it creates a wallet with a different public address than that address previously logged in terminal.

I don't know why it is happening, although I have some guesses about the possibilities:

  • I could be missing some necessary step when converting from private key to public key (hashing it, maybe?)

  • or when I'm logging the private and public key on console, each time it's logging from a new instance of the key

Does anyone know why it's happening and how to solve it?

Best Answer

Solved it. The code was generating a valid public address for Bitcoin, not Ethereum. Both Bitcoin and Ethereum have the same process to create a private key, but in order to generate an Ethereum public address from it, it's necessary more complex steps, not presented in that code.