Debian Codegraph @

crypto_kem/8192128pcf/vec/encrypt.c

raw
1 /*
2 This file is for Niederreiter encryption
3 */
4 // 20240805 djb: more cryptoint usage
5 // 20240508 djb: using crypto_sort_int16()
6 // 20240507 djb: using crypto_uint64_load()
7 // 20240504 djb: negifcollision
8 // 20240504 djb: use crypto_xof_bitwrite16
9 // 20240503 djb: remove #ifdef KAT ... #endif
10 // 20230102 djb: rename encrypt() as pke_encrypt()
11 // 20221231 djb: move encrypt.h last for macos portability; tnx thom wiggers
12 // 20221230 djb: add linker line
13
14 // linker define pke_encrypt
15
16 #include "randombytes.h"
17 #include "crypto_sort_int16.h"
18 #include "params.h"
19 #include "util.h"
20
21 #include <stdint.h>
22 #include "crypto_declassify.h"
23 #include "crypto_int16.h"
24 #include "crypto_uint16.h"
25 #include "crypto_uint64.h"
26 #include "crypto_xof_bitwrite16.h"
27
28 #include "encrypt.h"
29
30 /* output: e, an error vector of weight t */
31 static void gen_e(unsigned char *e)
32 {
33 int i, j;
34
35 uint16_t ind[ SYS_T ];
36 crypto_int16 negifcollision;
37 unsigned char indbytes[ SYS_T*2 ];
38 unsigned char bytes[ sizeof(ind) ];
39
40 while (1)
41 {
42 randombytes(bytes, sizeof(bytes));
43
44 for (i = 0; i < SYS_T; i++)
45 ind[i] = load_gf(bytes + i*2);
46
47 // check for repetition
48
49 crypto_sort_int16(ind, SYS_T);
50
51 negifcollision = 0;
52 for (i = 1; i < SYS_T; i++)
53 negifcollision |= (ind[i-1]^ind[i])-1;
54
55 negifcollision = crypto_int16_negative_mask(negifcollision);
56 crypto_declassify(&negifcollision,sizeof negifcollision);
57
58 if (!negifcollision)
59 break;
60 }
61
62 for (j = 0; j < SYS_T; j++)
63 crypto_uint16_store(indbytes+2*j,ind[j]);
64
65 crypto_xof_bitwrite16(e,SYS_N/8,indbytes,2*SYS_T);
66 }
67
68 /* input: public key pk, error vector e */
69 /* output: syndrome s */
70 static void syndrome(unsigned char *s, const unsigned char *pk, unsigned char *e)
71 {
72 crypto_uint64 b;
73
74 const unsigned char *pk_ptr;
75 const unsigned char *e_ptr = e + SYND_BYTES;
76 crypto_uint64 eword[PK_NCOLS/64];
77
78 int i, j;
79
80 //
81
82 for (i = 0; i < SYND_BYTES; i++)
83 s[i] = e[i];
84
85 for (j = 0;j < PK_NCOLS/64;++j)
86 eword[j] = crypto_uint64_load(e_ptr+8*j);
87
88 for (i = 0; i < PK_NROWS; i++)
89 {
90 pk_ptr = pk + PK_ROW_BYTES * i;
91
92 b = 0;
93 for (j = 0; j < PK_NCOLS/64; j++)
94 b ^= crypto_uint64_load(pk_ptr+8*j) & eword[j];
95
96 b ^= b >> 32;
97 b ^= b >> 16;
98 b ^= b >> 8;
99 b ^= b >> 4;
100 b ^= b >> 2;
101 b ^= b >> 1;
102 b = crypto_uint64_bottombit_01(b);
103
104 s[ i/8 ] ^= (b << (i%8));
105 }
106 }
107
108 /* input: public key pk */
109 /* output: error vector e, syndrome s */
110 void pke_encrypt(unsigned char *s, const unsigned char *pk, unsigned char *e)
111 {
112 gen_e(e);
113 syndrome(s, pk, e);
114 }
115