2

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?

2

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

  • in that it appears its decrypted with a private key, I'd only have a public key to encrypt/decrypt – ZhouW Mar 7 '18 at 20:25
  • 1
    If you're doing symmetric encryption, why would you use a public key to do it? – smarx Mar 7 '18 at 21:38
1

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
0

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..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.