7

I am trying to find a way to do encryption in solidity.I have a string and I want to encrypt it using some key. Can we do it in solidity?

Shane Fontaine
  • 18,036
  • 20
  • 54
  • 82
Vikas
  • 101
  • 2
  • 5
  • For added context. 1 use case would be using asymmetric encryption of a string(or data) originating from the contract. The contract would use the public key to encrypt the data. – Tjad Clark May 15 '21 at 20:56

2 Answers2

5

If you send the data and then encrypt it in solidity, the data will be visible in the transaction that in the first place was used to send the data to the contract. Also, solidity doesn't have a function to encrypt (to the best of my knowledge).

You can use web3 to encrypt the data and send it encrypted to your contract.

Jaime
  • 8,340
  • 1
  • 12
  • 20
  • Jaime thanks for the answer but I am sending string in parts into contract then concatenating it in contract now I want to encrypt that concatenated string. – Vikas May 04 '18 at 16:46
  • Vikas, what is the reason to encrypt the data? if it is to prevent someone from reading it, the fact that the transactions are public make your data public as well. – Jaime May 04 '18 at 17:01
4

Generally, the answer is no. If you want to encrypt data, you should encrypt the data before it is sent to the contract using parameters/salt/etc. that is not visible to the public (client side code).

Here are some reasons why you currently cannot encrypt data securely in Solidity. For example:

  1. You can use one of Solidity's hash functions i.e. keccak256 to hash your strings. However, anyone using web3 can use the web3.eth.abi.decodeParameters(typesArray, hexString) function to decode that hash by inputing the hash and input parameter types into the function.
  2. You can write your own encryption function, but any function you write in solidity is visible to the public so any malicious actor is able to implement a decryption function for what you write. Also, if you want to add salt to your encryption function as a variable, it will also be viewable to users when setting the variable via either transaction or contract deployment.
brianbhsu
  • 536
  • 4
  • 5
  • This makes sense. what if the string originates from the contract as well. Using asymmetric encryption the contract could use the pub key to encrypt the data originating from the smart contract. This is what I would like to do. Are there any good known solutions ? – Tjad Clark May 15 '21 at 20:50