is there a way using public key cryptography (asymmetric cryptography) in a smart contract. The idea is to:

1) Encrypt some text and publish it on the block chain as a transaction.

function encryptData(string pubKey, string text){

2) And later, have a call (local invocation of a contract function) to decrypt it:

function decryptData(string privKey, string text){

I've found some related topics about signatures using ecrecover , but not about cryptography.


Note that no matter if you are using an internal or external call, in order to decrypt something on-chain, you have to give the miners the private key, which is obviously not so private anymore. That is the reason why encryption is hardly implementable in open blockchains like Ethereum.


You can certainly do what you want to do, but it would make no sense whatsoever.

Using very simple commands on the Ethereum node's RPC, any person with access to any node could see the clear text sent to the encryptData function. Yes, you could write Solidity code to encrypt the text on-chain, but it would have already been sent through a very public interface.

It would be very much better to encrypt the text prior to sending it and storing the encrypted text on-chain.

Probably the reason why you're not finding any information on this topic is because it doesn't work.

  • Thanks, my prior intention was to move the encryption and decryption functionality on-chain to avoid multiple implementations in different applications. However, your answer makes a lot of sense - thanks for clarification. – jim Aug 14 '17 at 10:49

It appears what you are trying to do is make a function like this:

function encryptData(string pubKey, string text) constant returns (string) {

From what I know that would not send anything to the miners and thus do the job or am I missing something here? You would of course then have to store what you encrypted with a transaction.

( the respective decryption function would then be:

function decryptData(string privKey, string text) constant returns (string) {



You can use ecies to encrypted and decrypt data with the ethereum-keys.

const EthCrypto = require('eth-crypto');
const encrypted = await EthCrypto.encryptWithPublicKey(
const decrypted = await EthCrypto.decryptWithPrivateKey(

I made a tutorial for this use-case.

  • The question was how to do it in a smart contract. You're giving a Javascript answer. – Lauri Peltonen Feb 28 '18 at 16:08

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.