Exporting a MetaMask Public Key from a Web Browser

In this article, we will explore how to export a MetaMask public key from your web browser. This is useful for a variety of applications, such as creating an Ethereum wallet on other platforms or generating a QR code with your public address.

The eth_getEncryptionPublicKey method

To get a MetaMask public key, you need to use the eth_getEncryptionPublicKey method provided by the Ethereum Virtual Machine (EVM). This method is used to retrieve the public encryption key for an account in MetaMask. Here’s how to do it:

const keyB64 = await window.ethereum.request({

method: 'eth_getEncryptionPublicKey',

params: [accounts],

});

Converting the binary key to plain text

The response from eth_getEncryptionPublicKey is a binary string, which we need to convert to plain text. We can do this using the Buffer.from() method:

const publicKey = Buffer.from(keyB64, 'base64');

This will give us a Buffer object containing the encrypted public key.

Converting the Buffer to Plain Text

To get the actual public key in plain text format, we need to convert the Buffer to a string using the toString() method. This is where you can export your public key.

const publicKeyText = publicKey.toString('base64');

This will give us the public key as a base64 encoded string.

Using the Public Key

Now that we have the public key in plain text format, we can use it to create an Ethereum wallet or any other application that requires a public key. Here’s how to do it:

const privateKey = await window.ethereum.request({

method: 'eth_getPrivateKey',

params: [accounts],

});

const publicKeyText = publicKeyText.split('/');

const address = publicKeyText[0];

In this example, we first get the private key using eth_getPrivateKey. We then extract the public key by splitting the response string into an array and taking the first element.

Conclusion

Exporting a MetaMask public key from your web browser is a simple process that uses the eth_getEncryptionPublicKey method to retrieve the public encryption key. Once you have the binary key, you can convert it to text format using the Buffer.from() method and use it as needed. With this article, you now know how to export your MetaMask public key from your web browser.

Tips and Variations

Metamask: How to Export public key from Metamask

  • Make sure to verify that your MetaMask account is synced before attempting to retrieve a public key.
  • If you are running in headless mode (e.g. on a server), you may need to adjust the window.ethereum context to access the MetaMask API correctly.
  • You can also use other methods, such as eth_getPublicKey, to get the MetaMask public key.

Share This:

Source