MetaMask / eth-sig-util

A collection of functions for signing and verifying data with Ethereum keys.
ISC License
575 stars 227 forks source link

Error with encrypt function: "Cannot read properties of undefined (reading 'bufferToHex')" or "Cannot read properties of undefined (reading 'encrypt')" #222

Closed saad-121 closed 2 years ago

saad-121 commented 3 years ago

I am trying to get the public key of a connected wallet, use it to encrypt data, and then use the private key of the same user to decrypt it. So far, I have used the following to get the public key:

 let encryptionPublicKey;
window.ethereum
    .request({
      method: 'eth_getEncryptionPublicKey',
      params: [accounts[0]], // you must have access to the specified account
    })
 .then((result) => {
      encryptionPublicKey = result;
      console.log(encryptionPublicKey);
      this.setState({encryptionPublicKey})
    })
 .catch((error) => {
      if (error.code === 4001) {
        // EIP-1193 userRejectedRequest error
        console.log("We can't encrypt anything without the key.");
      } else {
        console.error(error);
      }
    });

Then, I use this function to encrypt:

async encrypt(content){
/* Encrypting */
const encryptedMessage = ethUtil.bufferToHex(
Buffer.from(
  JSON.stringify(
        encrypt(
          this.state.encryptionPublicKey,
          { data: 'Hello world!' },
          'x25519-xsalsa20-poly1305'
        )
      ),
      'utf8'
    )
  );
  return encryptedMessage;
  }

I am using 'Hello World' just to test for starters.

I get this error "Cannot read properties of undefined (reading 'bufferToHex')". Sometimes when I change a few things, I get this "Cannot read properties of undefined (reading 'encrypt')". FYI, I plan to use this function to decrypt the encrypted data.

  decrypt(encryptedContent){ 
              /* Decrypting */
              let decryptedResult = "";
        window.ethereum
        .request({
          method: 'eth_decrypt',
          params: [encryptedContent, this.state.account],
        })
        .then((decryptedMessage) =>
          // console.log('The decrypted message is:', decryptedMessage);
          decryptedResult = decryptedMessage
        )
        .catch((error) => console.log(error.message));

        return(decryptedResult);
  }

Here are the relevant dependencies:

import {ethUtil, sigUtil}  from 'ethereumjs-util';
import {encrypt} from 'eth-sig-util';

I would appreciate some assistance. Thank you.

mcmire commented 2 years ago

Hi @shhs121,

Sorry for the late reply on this. For future googlers, it looks like you are importing ethereumjs-util incorrectly. You can just say

import { bufferToHex }  from 'ethereumjs-util';

Hope this helps.