I am trying to encrypt a message by using a method from the Metamask RPC API (here). I first use 'eth_getEncryptionPublicKey' to get the encryption key for the account that I am connected to. I then use the following code to encrypt my message. However, I am getting the following error and I do not understand how to address it. Please can someone advise?
I do not know if this has anything to do with my errors but '@metamask/eth-sig-util' is written in TypeScript.
import ethUtil from 'ethereumjs-util';
import sigUtil from '@metamask/eth-sig-util';
const encryptString = (encryptionKey, text) => {
console.log('encryptString.encryptionKey: ' + encryptionKey);
console.log('encryptString.text: ' + text);
const encryptedMessage = ethUtil.bufferToHex(
Buffer.from(
JSON.stringify(
sigUtil.encrypt({
publicKey: encryptionKey,
data: text,
version: 'x25519-xsalsa20-poly1305',
})
),
'utf-8'
)
);
};
console:
encryptString.publicKey: Rb1/QuAkQ7qpyo9wzY5+E0Kw2AkL1Vipb8LObOGkkNw=
encryptString.text: Hello World
Error:
Uncaught TypeError: Cannot read properties of undefined (reading 'bufferToHex')
I had the same error, using these imports worked for me:
import { bufferToHex } from 'ethereumjs-util';
import { encrypt } from '@metamask/eth-sig-util';
Full code adapted for your case:
import { bufferToHex } from 'ethereumjs-util';
import { encrypt } from '@metamask/eth-sig-util';
const encryptedMessage = bufferToHex(
Buffer.from(
JSON.stringify(
encrypt({
publicKey: encryptionKey,
data: 'hello world!',
version: 'x25519-xsalsa20-poly1305',
}),
),
'utf8',
),
);
console.log(`Encrypted message: ${encryptedMessage}`);
const decryptedMessage = await window as.ethereum.request({
method: 'eth_decrypt',
params: [encryptedMessage, account],
});
console.log(`Decrypted message: ${decryptedMessage}`);