3 ms·
Do not use the input as indices, do not branch depending on the input, and do not use division, mod, and even multiplication on the input. Check how libsodium d
by dependenttypes 6y ago
Do not use the input as indices, do not branch depending on the input, and do not use division, mod, and even multiplication on the input. Check how libsodium does it. Here is a safe rot13 implementation in C if it is any help (note: it assumes a safe islower and isupper implementation).
#include <ctype.h>
#define IFTHENELSE(c, t, e) ((-(!!(c)) & (t)) | (-(!(c)) & (e)))
unsigned char
mod26 (unsigned char x)
{
x -= IFTHENELSE(x >= 26 * 4,
26 * 4,
0);
x -= IFTHENELSE(x >= 26 * 2,
26 * 2,
0);
x -= IFTHENELSE(x >= 26 * 2,
26 * 2,
0);
x -= IFTHENELSE(x >= 26,
26,
0);
return x;
}
unsigned char
rot13 (unsigned char x)
{
return IFTHENELSE(islower(x), mod26(x - 'a' + 13) + 'a',
IFTHENELSE(isupper(x), mod26(x - 'A' + 13) + 'A',
x));
}
implementing base32h should be much easier as you do not need to perform mod with a non-power of 2.