Exporting MetaMask Public Key from Web Browser

In this article, we will explore how to export MetaMask public key from your web browser. This is useful for various applications, such as creating Ethereum wallets on other platforms or generating a QR code with your public address.
The eth_getEncryptionPublicKey method
To get your 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 of an account in MetaMask. Here is how to do it:
const keyB64 = await window.ethereum.request({
method: 'eth_getEncryptionPublicKey',
parameters: [accounts],
});
Converting Binary Key to Text
The response from eth_getEncryptionPublicKey is a binary string, which we need to convert to text format. 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 clipboard to text
To get the actual public key in plain text format, we need to convert the buffer to a string using the toString() method. You can export your public key here.
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',
parameters: [accounts],
});
const publicKeyText = publicKeyText.split('/');
const address = publicKeyText[0];
In this example, we first get the private key using eth_getPrivateKey. Then, we extract the public key by splitting the response string into an array and taking the first element.
Conclusion
Exporting your 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 then use it as needed. With this article, you now know how to export your MetaMask public key from your web browser.
Tips and Variations
- Be sure to check that your MetaMask account is synced before attempting to retrieve the public key.
- If you are running in headless mode (e.g. on a server), you may need to adjust the
window.ethereumcontext to properly access the MetaMask API.
- You can also use other methods, such as
eth_getPublicKey, to retrieve the public key from MetaMask.