Ethereum – Encrypting and Decrypting Messages with Public and Private Keys Using Metamask

ethereum-wallet-dappmetamaskweb3-providersweb3js

I am trying to use Ethereum private and public keys for message encryption like PGP and I found out this npm module on github, https://github.com/pubkey/eth-crypto#encryptwithpublickey, which it lets you get public key from private key, encrypt message with public key, and decrypt message with private key. I am using MetaMask as the web3 interface for my dapp and I am trying make the message encryption works seamlessly. However, I cannot find a way to automatically pass in MetaMask default account's private key to the npm modules rather than manually clicking export private key from MetaMask's extension UI.

Best Answer

The point of Metamask as a product is to never expose the private key to the web applications that the user browses to. In order for you to use that particular tool to encrypt data in a custom way, Metamask as a plugin would need to include a hook to have the web application pass in the data to be encrypted, and have Metamask to the encryption itself.

This is similar to the idea of signing a message; there's an established standard for using a private key to sign a given message, and Metamask provides a hook to allow application developers to send a string to Metamask and have it sign the string and return the signature, never exposing the private key.

The approach you'd probably want to take with your application is not to work with Metamask, but to create a utility that fulfils the same role as Metamask (is an Ethereum wallet in its own right), such that it receives the private keys (or mnemonic phrase) from the user, and then has the keys available to encrypt data for the user.

Related Topic