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?
2 Answers
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');
- 1,157
- 1
- 10
- 15
Assuming you have the public key of the person you want to send a message to (if they've already signed a transaction you can recover it from the signature) it should be possible to encrypt and decrypt using ECIES. Apparently there's a JavaScript library for this, I assume you can use it in a browser: https://bitcointalk.org/index.php?topic=627927.0
I have no idea either way whether or not these libraries are good enough to use securely.
Another approach is to generate a separate keypair that's actually designed for encryption, then use the Ethereum key to sign the public key and send it to the other party.
- 16,897
- 1
- 29
- 58
You can however use the Ethereum privKey to generate a new pubKey from the library above like so,
var pubKey = new bitcore.PublicKey.fromPrivateKey(privKey);You can now encrypt and decrypt messages. Any suggestions on how I can use this library without having a workaround? Thanks! – Malone Feb 28 '17 at 23:59bitcore-ecieshas performance-issues right now. Thanks again. – Malone Mar 01 '17 at 22:03eth_decrypt(https://docs.metamask.io/guide/rpc-api.html#other-rpc-methods) – Xavier59 Mar 01 '22 at 15:34