I recently encountered a requirement to encrypt and decrypt messages in my project. After some research, I found a way to achieve this using @metamask/eth-sig-util. Below is the approach I used ( this is only available for Metamask as only Metamask is allowing encryption/decryption until now ).
Encryption
To encrypt the message, I used the encrypt function from @metamask/eth-sig-util:
import { encrypt } from "@metamask/eth-sig-util";
const encrypted = encrypt({
publicKey: encryptionPublicKey,
data: inputMessage, // The message to encrypt
version: "x25519-xsalsa20-poly1305",
});
const encryptedString =
"0x" + Buffer.from(JSON.stringify(encrypted)).toString("hex");
Decryption
To decrypt the encrypted message, I used eth_decrypt provided by MetaMask:
const decrypted = await window.ethereum.request({
method: "eth_decrypt",
params: [encryptedData, address],
});
This approach worked seamlessly in my project. Hope this helps someone facing a similar issue! 🚀
Let me know if you have any questions.