4

I retrieve the public key of a users account using Web3 as follows:

 web3.eth.sign(web3.eth.accounts[0], web3.sha3('test'), function (err, signature) {
          var sigtest = signature
          const util = require('ethereumjs-util');
          const sig = util.fromRpcSig(sigtest);
          const publicKey = util.ecrecover(util.sha3('test'), sig.v, sig.r, sig.s);
      });

I then want to encrypt a message with this public key (without having a users private key) - How to encrypt a message with the public-key of an Ethereum address gives an answer but in that example a private key is also given. How should this be done?

ZhouW
  • 1,348
  • 2
  • 18
  • 35

3 Answers3

3

You could try this library it works perfectly. https://github.com/LimelabsTech/eth-ecies

Kristian
  • 296
  • 1
  • 8
2

web3.eth.sign is deprecated in Metamask

instead of sign use sendAsync:

  const signature = await new Promise((resolve, reject) => {
    web3.currentProvider.sendAsync({
      method: 'personal_sign',
      params: [web3.utils.utf8ToHex(message), address],
      from: address,
    }, (err, response) => {
      if(err) return reject(err);
      resolve(response.result);
    });
  });

then use eth-crypto

to get address from signed message:

  const signer = EthCrypto.recover(
    signature,
    web3.eth.accounts.hashMessage(message)
  );

to get public key from signed message:

  const pubkey = EthCrypto.recoverPublicKey(
    signature,
    web3.eth.accounts.hashMessage(message)
  );

if you do recovering in browser just browserify eth-crypto:

  browserify node_modules/eth-crypto/dist/lib/browserify.index.js -o eth-crypto.js
Eugene
  • 219
  • 1
  • 3
1

Public key cryptography relies on an asymmetric algorithm like RSA.

From a private key we get a public key to get pair keys=(priv,pub)

so encryption as a function is RSA: K x M -> C

where K,M,C is spaces of public keys, messages, ciphertexts respectively

and rsa(pub,m)=c is an instance specific to keys=(priv,pub)

We have a corresponding decryption function

dRSA: K' x C -> M

where Pr[drsa(priv,c) == m]==1

So the keys don't encrypt.. 'keyed' functions (algorithms like RSA) encrypt..