简体   繁体   中英

Off-chain encryption using public key

I am trying to sign and encrypt a metadata using a user's public key before uploading it to the blockchain, and decrypt the data with the user's private key off-chain. I have followed this and it worked perfectly but it is asking for the user's private key of the currently connected user in Metamask.

So I tried following the tutorial in Metamask's documentation [1] . And this is the code:

await window.ethereum.enable();
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });

let encryptionPublicKey;

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

console.log(encryptionPublicKey);
const encryptedMessage = ethUtil.bufferToHex(
    Buffer.from(
      JSON.stringify(
        sigUtil.encrypt({
          publicKey: encryptionPublicKey,
          data: 'hello world!',
          version: 'x25519-xsalsa20-poly1305',
        })
      ),
      'utf8'
    )
);

I'm getting an empty result, thus an empty encryptionPublicKey. Hence, I am getting this error:

Uncaught (in promise) Error: Missing publicKey parameter

How can I fix this? Any help is greatly appreciated.

Similar Question on encrypting data using public key but there is no clear answer: [1]

I managed to get it working by putting await before ethereum.request .

Additional Question: Does this encryption and decryption method works in creating and retrieving transactions in blockchain?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM