Exporting a MetaMask Public Key from Your Web Browser
In this article, we will explore how to export a MetaMask public key from your web browser. This is useful for various 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 of an account in MetaMask. Here’s how:
const keyB64 = await window.ethereum.request({
method: 'eth_getEncryptionPublicKey',
params: [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 Buffer 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. Here 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, we can use it to create an Ethereum wallet or any other application that requires a public key. Here’s how:
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
. Then, we 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 then use it when needed. With this article, you now know how to export your MetaMask public key from your web browser.
Tips and Variations
- Make sure to check if 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 properly access the MetaMask API.
- You can also use other methods, such as
eth_getPublicKey
, to get the public key from MetaMask.