| 1 |
/* |
| 2 |
This file is for Benes network related functions |
| 3 |
|
| 4 |
For the implementation strategy, see |
| 5 |
https://eprint.iacr.org/2017/793.pdf |
| 6 |
*/ |
| 7 |
// 20221230 djb: add linker lines |
| 8 |
|
| 9 |
// linker define benes |
| 10 |
|
| 11 |
#include "util.h" |
| 12 |
#include "transpose.h" |
| 13 |
#include "params.h" |
| 14 |
#include "benes.h" |
| 15 |
|
| 16 |
/* one layer of the benes network */ |
| 17 |
static void layer(uint64_t * data, uint64_t * bits, int lgs) |
| 18 |
{ |
| 19 |
int i, j, s; |
| 20 |
|
| 21 |
uint64_t d; |
| 22 |
|
| 23 |
s = 1 << lgs; |
| 24 |
|
| 25 |
for (i = 0; i < 64; i += s*2) |
| 26 |
for (j = i; j < i+s; j++) |
| 27 |
{ |
| 28 |
|
| 29 |
d = (data[j+0] ^ data[j+s]); |
| 30 |
d &= (*bits++); |
| 31 |
data[j+0] ^= d; |
| 32 |
data[j+s] ^= d; |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
/* input: r, sequence of bits to be permuted */ |
| 37 |
/* bits, condition bits of the Benes network */ |
| 38 |
/* rev, 0 for normal application; !0 for inverse */ |
| 39 |
/* output: r, permuted bits */ |
| 40 |
void benes(uint64_t * r, const unsigned char * bits, int rev) |
| 41 |
{ |
| 42 |
int i; |
| 43 |
|
| 44 |
const unsigned char *cond_ptr; |
| 45 |
int inc, low; |
| 46 |
|
| 47 |
uint64_t cond[64]; |
| 48 |
|
| 49 |
// |
| 50 |
|
| 51 |
if (rev == 0) |
| 52 |
{ |
| 53 |
inc = 256; |
| 54 |
cond_ptr = bits; |
| 55 |
} |
| 56 |
else |
| 57 |
{ |
| 58 |
inc = -256; |
| 59 |
cond_ptr = bits + (2*GFBITS-2)*256; |
| 60 |
} |
| 61 |
|
| 62 |
// |
| 63 |
|
| 64 |
transpose_64x64(r, r); |
| 65 |
|
| 66 |
for (low = 0; low <= 5; low++) |
| 67 |
{ |
| 68 |
for (i = 0; i < 64; i++) cond[i] = load4(cond_ptr + i*4); |
| 69 |
transpose_64x64(cond, cond); |
| 70 |
layer(r, cond, low); |
| 71 |
cond_ptr += inc; |
| 72 |
} |
| 73 |
|
| 74 |
transpose_64x64(r, r); |
| 75 |
|
| 76 |
for (low = 0; low <= 5; low++) |
| 77 |
{ |
| 78 |
for (i = 0; i < 32; i++) cond[i] = load8(cond_ptr + i*8); |
| 79 |
layer(r, cond, low); |
| 80 |
cond_ptr += inc; |
| 81 |
} |
| 82 |
for (low = 4; low >= 0; low--) |
| 83 |
{ |
| 84 |
for (i = 0; i < 32; i++) cond[i] = load8(cond_ptr + i*8); |
| 85 |
layer(r, cond, low); |
| 86 |
cond_ptr += inc; |
| 87 |
} |
| 88 |
|
| 89 |
transpose_64x64(r, r); |
| 90 |
|
| 91 |
for (low = 5; low >= 0; low--) |
| 92 |
{ |
| 93 |
for (i = 0; i < 64; i++) cond[i] = load4(cond_ptr + i*4); |
| 94 |
transpose_64x64(cond, cond); |
| 95 |
layer(r, cond, low); |
| 96 |
cond_ptr += inc; |
| 97 |
} |
| 98 |
|
| 99 |
transpose_64x64(r, r); |
| 100 |
} |
| 101 |
|