Photo by Zoltan Tasi on Unsplash

How Do I Implement Symmetric Key Encryption In Ethereum?

Prof Bill Buchanan OBE FRSE
3 min readAug 2, 2022

--

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.

--

--

Prof Bill Buchanan OBE FRSE

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