Photo by Zoltan Tasi on Unsplash

How Do I Implement Symmetric Key Encryption In Ethereum?

Prof Bill Buchanan OBE


With symmetric-key, we have the ability to encrypt with a key and then decrypt with the same key. The most typical method of this is AES. But, AES is a power-intensive method which can take up quite a bit of memory. It is thus not well matched to Ethereum, and which will charge gas for the processing. Well, in our toolbox is the Keccak-256 hashing method, adding points, multiplying points and XOR methods. So, let’s see if we can create a symmetric key method using just Keccak-256 and XOR.

For this, we will take a secret (s_ij) and use an encryption key (k_ij) to encrypt the value, and then for us to be able to reverse this back to the secret. Each of the values will be 256 bits long (as this supports uint256). First, we hash our secret key and append a counter value (j):

The encrypted value is then:

and then to decrypt:

The hash method will just be Keccak-256. In our smart contract, when we want to generate the decryption key (decryption_key), we can generate it with:

uint256 decryption_key = uint256(keccak256(abi.encodePacked(sij, j)));

and then decrypt with:

sij ^= decryption_key;

Note that the “^” operation is XOR in Solidity.


The following is the code [taken from here][1]:

import secrets
import web3
from typing import Tuple, Dict, List, Iterable, Union
from py_ecc.optimized_bn128 import G1, G2
from py_ecc.optimized_bn128 import add, multiply, neg, normalize
from py_ecc.optimized_bn128 import curve_order as CURVE_ORDER
from py_ecc.optimized_bn128 import field_modulus as FIELD_MODULUS
from py_ecc.typing import Optimized_Point3D
from py_ecc.fields import optimized_bn128_FQ, optimized_bn128_FQ2
PointG1 = Optimized_Point3D[optimized_bn128_FQ]keccak_256 = web3.Web3.solidityKeccakdef random_scalar() -> int:
return secrets.randbelow(CURVE_ORDER)
def encrypt_share(s_ij: int, k_ij: PointG1, j: int) -> int:
x = normalize(k_ij)[0].n
h = keccak_256(abi_types=["uint256", "uint256"], values=[x, j])



Prof Bill Buchanan OBE

Professor of Cryptography. Serial innovator. Believer in fairness, justice & freedom. Based in Edinburgh. Old World Breaker. New World Creator. Building trust.