# How to implement arbitrary s-box in a side-channel-free way in C?

This could be a question for CodeReview.SE, but I thought it might require non-trivial cryptographic knowledge to merit it on-topic here.

The C language is chosen as it's a common language for implementing cryptographic algorithms. Also, as we're choosing C, the primary platforms under consideration are PCs, smart devices such as cellphones, tablets, and TVs, and servers.

Arbitrary s-box may be required when designing products for sale in jurisdictions that mandates local cryptography standards such as SM4, Camellia, SEED in China, Japan, and South Korea.

Here's my attempt at reducing side-channel when implementing arbitrary s-box. To the best of my knowledge, it's now constant-time, but

Q: how should other side-channel attacks such as fault attack and electromagnetic detector in proximity etc. be prevented?

#include <stdint.h>

const extern uint8_t sbox_table[256];

uint8_t sbox(uint8_t x)
{
int i;
uint8_t ret = 0;

for(i=0; i<256; i++)
{
}

return ret;
}

uint8_t invsbox(uint8_t x)
{
int i;
uint8_t ret = 0;

for(i=0; i<256; i++)
{
$$$$
`
• @bdegnan: actually, all memory accesses here are independent of the value $x$, hence whether a memory access is a hit or miss does not leak any information about $x$. – poncho Jul 20 '20 at 18:02