7
$\begingroup$

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;
    uint16_t mask = 0;

    for(i=0; i<256; i++)
    {
        mask = i ^ x;
        mask = (mask - 1) >> 8;
        ret |= sbox_table[i] & mask;
    }

    return ret;
}

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

    for(i=0; i<256; i++)
    {
        mask = sbox_table[i] ^ x;
        mask = (mask - 1) >> 8;
        ret |= i & mask;
    }

    return ret;
}

```
$\endgroup$
  • 2
    $\begingroup$ Also yes, this question is on-topic thanks to our "side channels and their countermeasures" exception for code-related tasks. $\endgroup$ – SEJPM Jul 20 at 13:13
  • 2
    $\begingroup$ @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$. $\endgroup$ – poncho Jul 20 at 18:02
  • 1
    $\begingroup$ Regarding "arbitrary S-box", note that both SM4 and Camellia have S-boxes that can be calculated in terms of AES's S-boxes if you have hardware capable of AES (x86 AES-NI, ARMv8). $\endgroup$ – Myria Jul 20 at 18:32
  • 5
    $\begingroup$ Note that C does not guarantee the above code will be constant time: execution time is not considered an observable effect by the C standard, so NO code can be guaranteed to be constant time if written in C. It almost certainly is in practice, but compilers don't make any attempt to enforce this (or any other side-channel resistance). $\endgroup$ – SAI Peregrinus Jul 20 at 19:23
  • 1
    $\begingroup$ Note that to achieve constant timing BearSSL uses BitSlicing $\endgroup$ – kelalaka Jul 20 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.