# How Do I Implement Symmetric Key Encryption In Ethereum?

--

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.

## Coding

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

import secrets

import web3from 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_MODULUSfrom py_ecc.typing import Optimized_Point3D

from py_ecc.fields import optimized_bn128_FQ, optimized_bn128_FQ2PointG1 = 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])

return…