[Ethereum] How to encrypt a message with the public-key of an Ethereum address

addressescryptographyencryptionpublic-key

I am writing some code in nodejs/browser.
I have successfully created ethereum-addresses with the secp256k1-library.
I was also able to sign and verify messages.
Now I want to encrypt/decrypt a message with the public and private-key of the generated addresses.
Has anyone done this before? Can I use CryptoJS to accomplish my goal?

Best Answer

thx @Edmunx Edgar, i tried to use ECIES, but it failed to install because of a subdepencency. I now used the bitcore-lib together with bitcore-ecies. This works like expected.

EDIT: I created a npm-module which does exactly theses things and also has some performance optimisations and tutorials: github:eth-crypto.

Here is my code for anyone with the same question:

// run 'npm install eth-crypto --save'

const EthCrypto = require('eth-crypto');

// create identitiy with key-pairs and address
const alice = EthCrypto.createIdentity();

const secretMessage = 'My name is Satoshi Buterin';
const encrypted = await EthCrypto.encryptWithPublicKey(
    alice.publicKey, // encrypt with alice's publicKey
    secretMessage
);

const decrypted = await EthCrypto.decryptWithPrivateKey(
    alice.privateKey,
    encrypted
);

if(decrypted === secretMessage) console.log('success');

Run via CodeSandbox

Related Topic