| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | #define OPENSSL_UNSTABLE_EXPERIMENTAL_KYBER |
| 16 | #include <openssl/experimental/kyber.h> |
| 17 |
| 18 | #include <assert.h> |
| 19 | #include <stdlib.h> |
| 20 |
| 21 | #include <openssl/bytestring.h> |
| 22 | #include <openssl/rand.h> |
| 23 |
| 24 | #include "../fipsmodule/keccak/internal.h" |
| 25 | #include "../internal.h" |
| 26 | #include "./internal.h" |
| 27 |
| 28 |
| 29 | // See |
| 30 | // https://pq-crystals.org/kyber/data/kyber-specification-round3-20210804.pdf |
| 31 |
| 32 | static void prf(uint8_t *out, size_t out_len, const uint8_t in[33]) { |
| 33 | BORINGSSL_keccak(out, out_len, in, 33, boringssl_shake256); |
| 34 | } |
| 35 |
| 36 | static void hash_h(uint8_t out[32], const uint8_t *in, size_t len) { |
| 37 | BORINGSSL_keccak(out, 32, in, len, boringssl_sha3_256); |
| 38 | } |
| 39 |
| 40 | static void hash_g(uint8_t out[64], const uint8_t *in, size_t len) { |
| 41 | BORINGSSL_keccak(out, 64, in, len, boringssl_sha3_512); |
| 42 | } |
| 43 |
| 44 | static void kdf(uint8_t *out, size_t out_len, const uint8_t *in, size_t len) { |
| 45 | BORINGSSL_keccak(out, out_len, in, len, boringssl_shake256); |
| 46 | } |
| 47 |
| 48 | #define DEGREE 256 |
| 49 | #define RANK 3 |
| 50 |
| 51 | static const size_t kBarrettMultiplier = 5039; |
| 52 | static const unsigned kBarrettShift = 24; |
| 53 | static const uint16_t kPrime = 3329; |
| 54 | static const int kLog2Prime = 12; |
| 55 | static const uint16_t kHalfPrime = (/*kPrime=*/3329 - 1) / 2; |
| 56 | static const int kDU = 10; |
| 57 | static const int kDV = 4; |
| 58 | // kInverseDegree is 128^-1 mod 3329; 128 because kPrime does not have a 512th |
| 59 | // root of unity. |
| 60 | static const uint16_t kInverseDegree = 3303; |
| 61 | static const size_t kEncodedVectorSize = |
| 62 | (/*kLog2Prime=*/12 * DEGREE / 8) * RANK; |
| 63 | static const size_t kCompressedVectorSize = /*kDU=*/10 * RANK * DEGREE / 8; |
| 64 |
| 65 | typedef struct scalar { |
| 66 | // On every function entry and exit, 0 <= c < kPrime. |
| 67 | uint16_t c[DEGREE]; |
| 68 | } scalar; |
| 69 |
| 70 | typedef struct vector { |
| 71 | scalar v[RANK]; |
| 72 | } vector; |
| 73 |
| 74 | typedef struct matrix { |
| 75 | scalar v[RANK][RANK]; |
| 76 | } matrix; |
| 77 |
| 78 | // This bit of Python will be referenced in some of the following comments: |
| 79 | // |
| 80 | // p = 3329 |
| 81 | // |
| 82 | // def bitreverse(i): |
| 83 | // ret = 0 |
| 84 | // for n in range(7): |
| 85 | // bit = i & 1 |
| 86 | // ret <<= 1 |
| 87 | // ret |= bit |
| 88 | // i >>= 1 |
| 89 | // return ret |
| 90 |
| 91 | // kNTTRoots = [pow(17, bitreverse(i), p) for i in range(128)] |
| 92 | static const uint16_t kNTTRoots[128] = { |
| 93 | 1, 1729, 2580, 3289, 2642, 630, 1897, 848, 1062, 1919, 193, 797, |
| 94 | 2786, 3260, 569, 1746, 296, 2447, 1339, 1476, 3046, 56, 2240, 1333, |
| 95 | 1426, 2094, 535, 2882, 2393, 2879, 1974, 821, 289, 331, 3253, 1756, |
| 96 | 1197, 2304, 2277, 2055, 650, 1977, 2513, 632, 2865, 33, 1320, 1915, |
| 97 | 2319, 1435, 807, 452, 1438, 2868, 1534, 2402, 2647, 2617, 1481, 648, |
| 98 | 2474, 3110, 1227, 910, 17, 2761, 583, 2649, 1637, 723, 2288, 1100, |
| 99 | 1409, 2662, 3281, 233, 756, 2156, 3015, 3050, 1703, 1651, 2789, 1789, |
| 100 | 1847, 952, 1461, 2687, 939, 2308, 2437, 2388, 733, 2337, 268, 641, |
| 101 | 1584, 2298, 2037, 3220, 375, 2549, 2090, 1645, 1063, 319, 2773, 757, |
| 102 | 2099, 561, 2466, 2594, 2804, 1092, 403, 1026, 1143, 2150, 2775, 886, |
| 103 | 1722, 1212, 1874, 1029, 2110, 2935, 885, 2154, |
| 104 | }; |
| 105 |
| 106 | // kInverseNTTRoots = [pow(17, -bitreverse(i), p) for i in range(128)] |
| 107 | static const uint16_t kInverseNTTRoots[128] = { |
| 108 | 1, 1600, 40, 749, 2481, 1432, 2699, 687, 1583, 2760, 69, 543, |
| 109 | 2532, 3136, 1410, 2267, 2508, 1355, 450, 936, 447, 2794, 1235, 1903, |
| 110 | 1996, 1089, 3273, 283, 1853, 1990, 882, 3033, 2419, 2102, 219, 855, |
| 111 | 2681, 1848, 712, 682, 927, 1795, 461, 1891, 2877, 2522, 1894, 1010, |
| 112 | 1414, 2009, 3296, 464, 2697, 816, 1352, 2679, 1274, 1052, 1025, 2132, |
| 113 | 1573, 76, 2998, 3040, 1175, 2444, 394, 1219, 2300, 1455, 2117, 1607, |
| 114 | 2443, 554, 1179, 2186, 2303, 2926, 2237, 525, 735, 863, 2768, 1230, |
| 115 | 2572, 556, 3010, 2266, 1684, 1239, 780, 2954, 109, 1292, 1031, 1745, |
| 116 | 2688, 3061, 992, 2596, 941, 892, 1021, 2390, 642, 1868, 2377, 1482, |
| 117 | 1540, 540, 1678, 1626, 279, 314, 1173, 2573, 3096, 48, 667, 1920, |
| 118 | 2229, 1041, 2606, 1692, 680, 2746, 568, 3312, |
| 119 | }; |
| 120 |
| 121 | // kModRoots = [pow(17, 2*bitreverse(i) + 1, p) for i in range(128)] |
| 122 | static const uint16_t kModRoots[128] = { |
| 123 | 17, 3312, 2761, 568, 583, 2746, 2649, 680, 1637, 1692, 723, 2606, |
| 124 | 2288, 1041, 1100, 2229, 1409, 1920, 2662, 667, 3281, 48, 233, 3096, |
| 125 | 756, 2573, 2156, 1173, 3015, 314, 3050, 279, 1703, 1626, 1651, 1678, |
| 126 | 2789, 540, 1789, 1540, 1847, 1482, 952, 2377, 1461, 1868, 2687, 642, |
| 127 | 939, 2390, 2308, 1021, 2437, 892, 2388, 941, 733, 2596, 2337, 992, |
| 128 | 268, 3061, 641, 2688, 1584, 1745, 2298, 1031, 2037, 1292, 3220, 109, |
| 129 | 375, 2954, 2549, 780, 2090, 1239, 1645, 1684, 1063, 2266, 319, 3010, |
| 130 | 2773, 556, 757, 2572, 2099, 1230, 561, 2768, 2466, 863, 2594, 735, |
| 131 | 2804, 525, 1092, 2237, 403, 2926, 1026, 2303, 1143, 2186, 2150, 1179, |
| 132 | 2775, 554, 886, 2443, 1722, 1607, 1212, 2117, 1874, 1455, 1029, 2300, |
| 133 | 2110, 1219, 2935, 394, 885, 2444, 2154, 1175, |
| 134 | }; |
| 135 |
| 136 | // reduce_once reduces 0 <= x < 2*kPrime, mod kPrime. |
| 137 | static uint16_t reduce_once(uint16_t x) { |
| 138 | declassify_assert(x < 2 * kPrime); |
| 139 | const uint16_t subtracted = x - kPrime; |
| 140 | uint16_t mask = 0u - (subtracted >> 15); |
| 141 | // Although this is a constant-time select, we omit a value barrier here. |
| 142 | // Value barriers impede auto-vectorization (likely because it forces the |
| 143 | // value to transit through a general-purpose register). On AArch64, this is a |
| 144 | // difference of 2x. |
| 145 | // |
| 146 | // We usually add value barriers to selects because Clang turns consecutive |
| 147 | // selects with the same condition into a branch instead of CMOV/CSEL. This |
| 148 | // condition does not occur in Kyber, so omitting it seems to be safe so far, |
| 149 | // but see |scalar_centered_binomial_distribution_eta_2_with_prf|. |
| 150 | return (mask & x) | (~mask & subtracted); |
| 151 | } |
| 152 |
| 153 | // constant time reduce x mod kPrime using Barrett reduction. x must be less |
| 154 | // than kPrime + 2×kPrime². |
| 155 | static uint16_t reduce(uint32_t x) { |
| 156 | declassify_assert(x < kPrime + 2u * kPrime * kPrime); |
| 157 | uint64_t product = (uint64_t)x * kBarrettMultiplier; |
| 158 | uint32_t quotient = (uint32_t)(product >> kBarrettShift); |
| 159 | uint32_t remainder = x - quotient * kPrime; |
| 160 | return reduce_once(remainder); |
| 161 | } |
| 162 |
| 163 | static void scalar_zero(scalar *out) { OPENSSL_memset(out, 0, sizeof(*out)); } |
| 164 |
| 165 | static void vector_zero(vector *out) { OPENSSL_memset(out, 0, sizeof(*out)); } |
| 166 |
| 167 | // In place number theoretic transform of a given scalar. |
| 168 | // Note that Kyber's kPrime 3329 does not have a 512th root of unity, so this |
| 169 | // transform leaves off the last iteration of the usual FFT code, with the 128 |
| 170 | // relevant roots of unity being stored in |kNTTRoots|. This means the output |
| 171 | // should be seen as 128 elements in GF(3329^2), with the coefficients of the |
| 172 | // elements being consecutive entries in |s->c|. |
| 173 | static void scalar_ntt(scalar *s) { |
| 174 | int offset = DEGREE; |
| 175 | // `int` is used here because using `size_t` throughout caused a ~5% slowdown |
| 176 | // with Clang 14 on Aarch64. |
| 177 | for (int step = 1; step < DEGREE / 2; step <<= 1) { |
| 178 | offset >>= 1; |
| 179 | int k = 0; |
| 180 | for (int i = 0; i < step; i++) { |
| 181 | const uint32_t step_root = kNTTRoots[i + step]; |
| 182 | for (int j = k; j < k + offset; j++) { |
| 183 | uint16_t odd = reduce(step_root * s->c[j + offset]); |
| 184 | uint16_t even = s->c[j]; |
| 185 | s->c[j] = reduce_once(odd + even); |
| 186 | s->c[j + offset] = reduce_once(even - odd + kPrime); |
| 187 | } |
| 188 | k += 2 * offset; |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 |
| 193 | static void vector_ntt(vector *a) { |
| 194 | for (int i = 0; i < RANK; i++) { |
| 195 | scalar_ntt(&a->v[i]); |
| 196 | } |
| 197 | } |
| 198 |
| 199 | // In place inverse number theoretic transform of a given scalar, with pairs of |
| 200 | // entries of s->v being interpreted as elements of GF(3329^2). Just as with the |
| 201 | // number theoretic transform, this leaves off the first step of the normal iFFT |
| 202 | // to account for the fact that 3329 does not have a 512th root of unity, using |
| 203 | // the precomputed 128 roots of unity stored in |kInverseNTTRoots|. |
| 204 | static void scalar_inverse_ntt(scalar *s) { |
| 205 | int step = DEGREE / 2; |
| 206 | // `int` is used here because using `size_t` throughout caused a ~5% slowdown |
| 207 | // with Clang 14 on Aarch64. |
| 208 | for (int offset = 2; offset < DEGREE; offset <<= 1) { |
| 209 | step >>= 1; |
| 210 | int k = 0; |
| 211 | for (int i = 0; i < step; i++) { |
| 212 | uint32_t step_root = kInverseNTTRoots[i + step]; |
| 213 | for (int j = k; j < k + offset; j++) { |
| 214 | uint16_t odd = s->c[j + offset]; |
| 215 | uint16_t even = s->c[j]; |
| 216 | s->c[j] = reduce_once(odd + even); |
| 217 | s->c[j + offset] = reduce(step_root * (even - odd + kPrime)); |
| 218 | } |
| 219 | k += 2 * offset; |
| 220 | } |
| 221 | } |
| 222 | for (int i = 0; i < DEGREE; i++) { |
| 223 | s->c[i] = reduce(s->c[i] * kInverseDegree); |
| 224 | } |
| 225 | } |
| 226 |
| 227 | static void vector_inverse_ntt(vector *a) { |
| 228 | for (int i = 0; i < RANK; i++) { |
| 229 | scalar_inverse_ntt(&a->v[i]); |
| 230 | } |
| 231 | } |
| 232 |
| 233 | static void scalar_add(scalar *lhs, const scalar *rhs) { |
| 234 | for (int i = 0; i < DEGREE; i++) { |
| 235 | lhs->c[i] = reduce_once(lhs->c[i] + rhs->c[i]); |
| 236 | } |
| 237 | } |
| 238 |
| 239 | static void scalar_sub(scalar *lhs, const scalar *rhs) { |
| 240 | for (int i = 0; i < DEGREE; i++) { |
| 241 | lhs->c[i] = reduce_once(lhs->c[i] - rhs->c[i] + kPrime); |
| 242 | } |
| 243 | } |
| 244 |
| 245 | // Multiplying two scalars in the number theoretically transformed state. Since |
| 246 | // 3329 does not have a 512th root of unity, this means we have to interpret |
| 247 | // the 2*ith and (2*i+1)th entries of the scalar as elements of GF(3329)[X]/(X^2 |
| 248 | // - 17^(2*bitreverse(i)+1)) The value of 17^(2*bitreverse(i)+1) mod 3329 is |
| 249 | // stored in the precomputed |kModRoots| table. Note that our Barrett transform |
| 250 | // only allows us to multipy two reduced numbers together, so we need some |
| 251 | // intermediate reduction steps, even if an uint64_t could hold 3 multiplied |
| 252 | // numbers. |
| 253 | static void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { |
| 254 | for (int i = 0; i < DEGREE / 2; i++) { |
| 255 | uint32_t real_real = (uint32_t)lhs->c[2 * i] * rhs->c[2 * i]; |
| 256 | uint32_t img_img = (uint32_t)lhs->c[2 * i + 1] * rhs->c[2 * i + 1]; |
| 257 | uint32_t real_img = (uint32_t)lhs->c[2 * i] * rhs->c[2 * i + 1]; |
| 258 | uint32_t img_real = (uint32_t)lhs->c[2 * i + 1] * rhs->c[2 * i]; |
| 259 | out->c[2 * i] = |
| 260 | reduce(real_real + (uint32_t)reduce(img_img) * kModRoots[i]); |
| 261 | out->c[2 * i + 1] = reduce(img_real + real_img); |
| 262 | } |
| 263 | } |
| 264 |
| 265 | static void vector_add(vector *lhs, const vector *rhs) { |
| 266 | for (int i = 0; i < RANK; i++) { |
| 267 | scalar_add(&lhs->v[i], &rhs->v[i]); |
| 268 | } |
| 269 | } |
| 270 |
| 271 | static void matrix_mult(vector *out, const matrix *m, const vector *a) { |
| 272 | vector_zero(out); |
| 273 | for (int i = 0; i < RANK; i++) { |
| 274 | for (int j = 0; j < RANK; j++) { |
| 275 | scalar product; |
| 276 | scalar_mult(&product, &m->v[i][j], &a->v[j]); |
| 277 | scalar_add(&out->v[i], &product); |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 |
| 282 | static void matrix_mult_transpose(vector *out, const matrix *m, |
| 283 | const vector *a) { |
| 284 | vector_zero(out); |
| 285 | for (int i = 0; i < RANK; i++) { |
| 286 | for (int j = 0; j < RANK; j++) { |
| 287 | scalar product; |
| 288 | scalar_mult(&product, &m->v[j][i], &a->v[j]); |
| 289 | scalar_add(&out->v[i], &product); |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 |
| 294 | static void scalar_inner_product(scalar *out, const vector *lhs, |
| 295 | const vector *rhs) { |
| 296 | scalar_zero(out); |
| 297 | for (int i = 0; i < RANK; i++) { |
| 298 | scalar product; |
| 299 | scalar_mult(&product, &lhs->v[i], &rhs->v[i]); |
| 300 | scalar_add(out, &product); |
| 301 | } |
| 302 | } |
| 303 |
| 304 | // Algorithm 1 of the Kyber spec. Rejection samples a Keccak stream to get |
| 305 | // uniformly distributed elements. This is used for matrix expansion and only |
| 306 | // operates on public inputs. |
| 307 | static void scalar_from_keccak_vartime(scalar *out, |
| 308 | struct BORINGSSL_keccak_st *keccak_ctx) { |
| 309 | assert(keccak_ctx->squeeze_offset == 0); |
| 310 | assert(keccak_ctx->rate_bytes == 168); |
| 311 | static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); |
| 312 |
| 313 | int done = 0; |
| 314 | while (done < DEGREE) { |
| 315 | uint8_t block[168]; |
| 316 | BORINGSSL_keccak_squeeze(keccak_ctx, block, sizeof(block)); |
| 317 | for (size_t i = 0; i < sizeof(block) && done < DEGREE; i += 3) { |
| 318 | uint16_t d1 = block[i] + 256 * (block[i + 1] % 16); |
| 319 | uint16_t d2 = block[i + 1] / 16 + 16 * block[i + 2]; |
| 320 | if (d1 < kPrime) { |
| 321 | out->c[done++] = d1; |
| 322 | } |
| 323 | if (d2 < kPrime && done < DEGREE) { |
| 324 | out->c[done++] = d2; |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 |
| 330 | // Algorithm 2 of the Kyber spec, with eta fixed to two and the PRF call |
| 331 | // included. Creates binominally distributed elements by sampling 2*|eta| bits, |
| 332 | // and setting the coefficient to the count of the first bits minus the count of |
| 333 | // the second bits, resulting in a centered binomial distribution. Since eta is |
| 334 | // two this gives -2/2 with a probability of 1/16, -1/1 with probability 1/4, |
| 335 | // and 0 with probability 3/8. |
| 336 | static void scalar_centered_binomial_distribution_eta_2_with_prf( |
| 337 | scalar *out, const uint8_t input[33]) { |
| 338 | uint8_t entropy[128]; |
| 339 | static_assert(sizeof(entropy) == 2 * /*kEta=*/2 * DEGREE / 8, ""); |
| 340 | prf(entropy, sizeof(entropy), input); |
| 341 |
| 342 | for (int i = 0; i < DEGREE; i += 2) { |
| 343 | uint8_t byte = entropy[i / 2]; |
| 344 |
| 345 | uint16_t value = (byte & 1) + ((byte >> 1) & 1); |
| 346 | value -= ((byte >> 2) & 1) + ((byte >> 3) & 1); |
| 347 | // Add |kPrime| if |value| underflowed. See |reduce_once| for a discussion |
| 348 | // on why the value barrier is omitted. While this could have been written |
| 349 | // reduce_once(value + kPrime), this is one extra addition and small range |
| 350 | // of |value| tempts some versions of Clang to emit a branch. |
| 351 | uint16_t mask = 0u - (value >> 15); |
| 352 | out->c[i] = value + (kPrime & mask); |
| 353 |
| 354 | byte >>= 4; |
| 355 | value = (byte & 1) + ((byte >> 1) & 1); |
| 356 | value -= ((byte >> 2) & 1) + ((byte >> 3) & 1); |
| 357 | // See above. |
| 358 | mask = 0u - (value >> 15); |
| 359 | out->c[i + 1] = value + (kPrime & mask); |
| 360 | } |
| 361 | } |
| 362 |
| 363 | // Generates a secret vector by using |
| 364 | // |scalar_centered_binomial_distribution_eta_2_with_prf|, using the given seed |
| 365 | // appending and incrementing |counter| for entry of the vector. |
| 366 | static void vector_generate_secret_eta_2(vector *out, uint8_t *counter, |
| 367 | const uint8_t seed[32]) { |
| 368 | uint8_t input[33]; |
| 369 | OPENSSL_memcpy(input, seed, 32); |
| 370 | for (int i = 0; i < RANK; i++) { |
| 371 | input[32] = (*counter)++; |
| 372 | scalar_centered_binomial_distribution_eta_2_with_prf(&out->v[i], input); |
| 373 | } |
| 374 | } |
| 375 |
| 376 | // Expands the matrix of a seed for key generation and for encaps-CPA. |
| 377 | static void matrix_expand(matrix *out, const uint8_t rho[32]) { |
| 378 | uint8_t input[34]; |
| 379 | OPENSSL_memcpy(input, rho, 32); |
| 380 | for (int i = 0; i < RANK; i++) { |
| 381 | for (int j = 0; j < RANK; j++) { |
| 382 | input[32] = i; |
| 383 | input[33] = j; |
| 384 | struct BORINGSSL_keccak_st keccak_ctx; |
| 385 | BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake128); |
| 386 | BORINGSSL_keccak_absorb(&keccak_ctx, input, sizeof(input)); |
| 387 | scalar_from_keccak_vartime(&out->v[i][j], &keccak_ctx); |
| 388 | } |
| 389 | } |
| 390 | } |
| 391 |
| 392 | static const uint8_t kMasks[8] = {0x01, 0x03, 0x07, 0x0f, |
| 393 | 0x1f, 0x3f, 0x7f, 0xff}; |
| 394 |
| 395 | static void scalar_encode(uint8_t *out, const scalar *s, int bits) { |
| 396 | assert(bits <= (int)sizeof(*s->c) * 8 && bits != 1); |
| 397 |
| 398 | uint8_t out_byte = 0; |
| 399 | int out_byte_bits = 0; |
| 400 |
| 401 | for (int i = 0; i < DEGREE; i++) { |
| 402 | uint16_t element = s->c[i]; |
| 403 | int element_bits_done = 0; |
| 404 |
| 405 | while (element_bits_done < bits) { |
| 406 | int chunk_bits = bits - element_bits_done; |
| 407 | int out_bits_remaining = 8 - out_byte_bits; |
| 408 | if (chunk_bits >= out_bits_remaining) { |
| 409 | chunk_bits = out_bits_remaining; |
| 410 | out_byte |= (element & kMasks[chunk_bits - 1]) << out_byte_bits; |
| 411 | *out = out_byte; |
| 412 | out++; |
| 413 | out_byte_bits = 0; |
| 414 | out_byte = 0; |
| 415 | } else { |
| 416 | out_byte |= (element & kMasks[chunk_bits - 1]) << out_byte_bits; |
| 417 | out_byte_bits += chunk_bits; |
| 418 | } |
| 419 |
| 420 | element_bits_done += chunk_bits; |
| 421 | element >>= chunk_bits; |
| 422 | } |
| 423 | } |
| 424 |
| 425 | if (out_byte_bits > 0) { |
| 426 | *out = out_byte; |
| 427 | } |
| 428 | } |
| 429 |
| 430 | // scalar_encode_1 is |scalar_encode| specialised for |bits| == 1. |
| 431 | static void scalar_encode_1(uint8_t out[32], const scalar *s) { |
| 432 | for (int i = 0; i < DEGREE; i += 8) { |
| 433 | uint8_t out_byte = 0; |
| 434 | for (int j = 0; j < 8; j++) { |
| 435 | out_byte |= (s->c[i + j] & 1) << j; |
| 436 | } |
| 437 | *out = out_byte; |
| 438 | out++; |
| 439 | } |
| 440 | } |
| 441 |
| 442 | // Encodes an entire vector into 32*|RANK|*|bits| bytes. Note that since 256 |
| 443 | // (DEGREE) is divisible by 8, the individual vector entries will always fill a |
| 444 | // whole number of bytes, so we do not need to worry about bit packing here. |
| 445 | static void vector_encode(uint8_t *out, const vector *a, int bits) { |
| 446 | for (int i = 0; i < RANK; i++) { |
| 447 | scalar_encode(out + i * bits * DEGREE / 8, &a->v[i], bits); |
| 448 | } |
| 449 | } |
| 450 |
| 451 | // scalar_decode parses |DEGREE * bits| bits from |in| into |DEGREE| values in |
| 452 | // |out|. It returns one on success and zero if any parsed value is >= |
| 453 | // |kPrime|. |
| 454 | static int scalar_decode(scalar *out, const uint8_t *in, int bits) { |
| 455 | assert(bits <= (int)sizeof(*out->c) * 8 && bits != 1); |
| 456 |
| 457 | uint8_t in_byte = 0; |
| 458 | int in_byte_bits_left = 0; |
| 459 |
| 460 | for (int i = 0; i < DEGREE; i++) { |
| 461 | uint16_t element = 0; |
| 462 | int element_bits_done = 0; |
| 463 |
| 464 | while (element_bits_done < bits) { |
| 465 | if (in_byte_bits_left == 0) { |
| 466 | in_byte = *in; |
| 467 | in++; |
| 468 | in_byte_bits_left = 8; |
| 469 | } |
| 470 |
| 471 | int chunk_bits = bits - element_bits_done; |
| 472 | if (chunk_bits > in_byte_bits_left) { |
| 473 | chunk_bits = in_byte_bits_left; |
| 474 | } |
| 475 |
| 476 | element |= (in_byte & kMasks[chunk_bits - 1]) << element_bits_done; |
| 477 | in_byte_bits_left -= chunk_bits; |
| 478 | in_byte >>= chunk_bits; |
| 479 |
| 480 | element_bits_done += chunk_bits; |
| 481 | } |
| 482 |
| 483 | // An element is only out of range in the case of invalid input, in which |
| 484 | // case it is okay to leak the comparison. |
| 485 | if (constant_time_declassify_int(element >= kPrime)) { |
| 486 | return 0; |
| 487 | } |
| 488 | out->c[i] = element; |
| 489 | } |
| 490 |
| 491 | return 1; |
| 492 | } |
| 493 |
| 494 | // scalar_decode_1 is |scalar_decode| specialised for |bits| == 1. |
| 495 | static void scalar_decode_1(scalar *out, const uint8_t in[32]) { |
| 496 | for (int i = 0; i < DEGREE; i += 8) { |
| 497 | uint8_t in_byte = *in; |
| 498 | in++; |
| 499 | for (int j = 0; j < 8; j++) { |
| 500 | out->c[i + j] = in_byte & 1; |
| 501 | in_byte >>= 1; |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 |
| 506 | // Decodes 32*|RANK|*|bits| bytes from |in| into |out|. It returns one on |
| 507 | // success or zero if any parsed value is >= |kPrime|. |
| 508 | static int vector_decode(vector *out, const uint8_t *in, int bits) { |
| 509 | for (int i = 0; i < RANK; i++) { |
| 510 | if (!scalar_decode(&out->v[i], in + i * bits * DEGREE / 8, bits)) { |
| 511 | return 0; |
| 512 | } |
| 513 | } |
| 514 | return 1; |
| 515 | } |
| 516 |
| 517 | // Compresses (lossily) an input |x| mod 3329 into |bits| many bits by grouping |
| 518 | // numbers close to each other together. The formula used is |
| 519 | // round(2^|bits|/kPrime*x) mod 2^|bits|. |
| 520 | // Uses Barrett reduction to achieve constant time. Since we need both the |
| 521 | // remainder (for rounding) and the quotient (as the result), we cannot use |
| 522 | // |reduce| here, but need to do the Barrett reduction directly. |
| 523 | static uint16_t compress(uint16_t x, int bits) { |
| 524 | uint32_t shifted = (uint32_t)x << bits; |
| 525 | uint64_t product = (uint64_t)shifted * kBarrettMultiplier; |
| 526 | uint32_t quotient = (uint32_t)(product >> kBarrettShift); |
| 527 | uint32_t remainder = shifted - quotient * kPrime; |
| 528 |
| 529 | // Adjust the quotient to round correctly: |
| 530 | // 0 <= remainder <= kHalfPrime round to 0 |
| 531 | // kHalfPrime < remainder <= kPrime + kHalfPrime round to 1 |
| 532 | // kPrime + kHalfPrime < remainder < 2 * kPrime round to 2 |
| 533 | declassify_assert(remainder < 2u * kPrime); |
| 534 | quotient += 1 & constant_time_lt_w(kHalfPrime, remainder); |
| 535 | quotient += 1 & constant_time_lt_w(kPrime + kHalfPrime, remainder); |
| 536 | return quotient & ((1 << bits) - 1); |
| 537 | } |
| 538 |
| 539 | // Decompresses |x| by using an equi-distant representative. The formula is |
| 540 | // round(kPrime/2^|bits|*x). Note that 2^|bits| being the divisor allows us to |
| 541 | // implement this logic using only bit operations. |
| 542 | static uint16_t decompress(uint16_t x, int bits) { |
| 543 | uint32_t product = (uint32_t)x * kPrime; |
| 544 | uint32_t power = 1 << bits; |
| 545 | // This is |product| % power, since |power| is a power of 2. |
| 546 | uint32_t remainder = product & (power - 1); |
| 547 | // This is |product| / power, since |power| is a power of 2. |
| 548 | uint32_t lower = product >> bits; |
| 549 | // The rounding logic works since the first half of numbers mod |power| have a |
| 550 | // 0 as first bit, and the second half has a 1 as first bit, since |power| is |
| 551 | // a power of 2. As a 12 bit number, |remainder| is always positive, so we |
| 552 | // will shift in 0s for a right shift. |
| 553 | return lower + (remainder >> (bits - 1)); |
| 554 | } |
| 555 |
| 556 | static void scalar_compress(scalar *s, int bits) { |
| 557 | for (int i = 0; i < DEGREE; i++) { |
| 558 | s->c[i] = compress(s->c[i], bits); |
| 559 | } |
| 560 | } |
| 561 |
| 562 | static void scalar_decompress(scalar *s, int bits) { |
| 563 | for (int i = 0; i < DEGREE; i++) { |
| 564 | s->c[i] = decompress(s->c[i], bits); |
| 565 | } |
| 566 | } |
| 567 |
| 568 | static void vector_compress(vector *a, int bits) { |
| 569 | for (int i = 0; i < RANK; i++) { |
| 570 | scalar_compress(&a->v[i], bits); |
| 571 | } |
| 572 | } |
| 573 |
| 574 | static void vector_decompress(vector *a, int bits) { |
| 575 | for (int i = 0; i < RANK; i++) { |
| 576 | scalar_decompress(&a->v[i], bits); |
| 577 | } |
| 578 | } |
| 579 |
| 580 | namespace { |
| 581 |
| 582 | struct public_key { |
| 583 | vector t; |
| 584 | uint8_t rho[32]; |
| 585 | uint8_t public_key_hash[32]; |
| 586 | matrix m; |
| 587 | }; |
| 588 |
| 589 | static struct public_key *public_key_from_external( |
| 590 | const struct KYBER_public_key *external) { |
| 591 | static_assert(sizeof(struct KYBER_public_key) >= sizeof(struct public_key), |
| 592 | "Kyber public key is too small"); |
| 593 | static_assert(alignof(struct KYBER_public_key) >= alignof(struct public_key), |
| 594 | "Kyber public key align incorrect"); |
| 595 | return (struct public_key *)external; |
| 596 | } |
| 597 |
| 598 | struct private_key { |
| 599 | struct public_key pub; |
| 600 | vector s; |
| 601 | uint8_t fo_failure_secret[32]; |
| 602 | }; |
| 603 |
| 604 | static struct private_key *private_key_from_external( |
| 605 | const struct KYBER_private_key *external) { |
| 606 | static_assert(sizeof(struct KYBER_private_key) >= sizeof(struct private_key), |
| 607 | "Kyber private key too small"); |
| 608 | static_assert( |
| 609 | alignof(struct KYBER_private_key) >= alignof(struct private_key), |
| 610 | "Kyber private key align incorrect"); |
| 611 | return (struct private_key *)external; |
| 612 | } |
| 613 |
| 614 | } // namespace |
| 615 |
| 616 | // Calls |KYBER_generate_key_external_entropy| with random bytes from |
| 617 | // |RAND_bytes|. |
| 618 | void KYBER_generate_key(uint8_t out_encoded_public_key[KYBER_PUBLIC_KEY_BYTES], |
| 619 | struct KYBER_private_key *out_private_key) { |
| 620 | uint8_t entropy[KYBER_GENERATE_KEY_ENTROPY]; |
| 621 | RAND_bytes(entropy, sizeof(entropy)); |
| 622 | CONSTTIME_SECRET(entropy, sizeof(entropy)); |
| 623 | KYBER_generate_key_external_entropy(out_encoded_public_key, out_private_key, |
| 624 | entropy); |
| 625 | } |
| 626 |
| 627 | static int kyber_marshal_public_key(CBB *out, const struct public_key *pub) { |
| 628 | uint8_t *vector_output; |
| 629 | if (!CBB_add_space(out, &vector_output, kEncodedVectorSize)) { |
| 630 | return 0; |
| 631 | } |
| 632 | vector_encode(vector_output, &pub->t, kLog2Prime); |
| 633 | if (!CBB_add_bytes(out, pub->rho, sizeof(pub->rho))) { |
| 634 | return 0; |
| 635 | } |
| 636 | return 1; |
| 637 | } |
| 638 |
| 639 | // Algorithms 4 and 7 of the Kyber spec. Algorithms are combined since key |
| 640 | // generation is not part of the FO transform, and the spec uses Algorithm 7 to |
| 641 | // specify the actual key format. |
| 642 | void KYBER_generate_key_external_entropy( |
| 643 | uint8_t out_encoded_public_key[KYBER_PUBLIC_KEY_BYTES], |
| 644 | struct KYBER_private_key *out_private_key, |
| 645 | const uint8_t entropy[KYBER_GENERATE_KEY_ENTROPY]) { |
| 646 | struct private_key *priv = private_key_from_external(out_private_key); |
| 647 | uint8_t hashed[64]; |
| 648 | hash_g(hashed, entropy, 32); |
| 649 | const uint8_t *const rho = hashed; |
| 650 | const uint8_t *const sigma = hashed + 32; |
| 651 | // rho is public. |
| 652 | CONSTTIME_DECLASSIFY(rho, 32); |
| 653 | OPENSSL_memcpy(priv->pub.rho, hashed, sizeof(priv->pub.rho)); |
| 654 | matrix_expand(&priv->pub.m, rho); |
| 655 | uint8_t counter = 0; |
| 656 | vector_generate_secret_eta_2(&priv->s, &counter, sigma); |
| 657 | vector_ntt(&priv->s); |
| 658 | vector error; |
| 659 | vector_generate_secret_eta_2(&error, &counter, sigma); |
| 660 | vector_ntt(&error); |
| 661 | matrix_mult_transpose(&priv->pub.t, &priv->pub.m, &priv->s); |
| 662 | vector_add(&priv->pub.t, &error); |
| 663 | // t is part of the public key and thus is public. |
| 664 | CONSTTIME_DECLASSIFY(&priv->pub.t, sizeof(priv->pub.t)); |
| 665 |
| 666 | CBB cbb; |
| 667 | CBB_init_fixed(&cbb, out_encoded_public_key, KYBER_PUBLIC_KEY_BYTES); |
| 668 | if (!kyber_marshal_public_key(&cbb, &priv->pub)) { |
| 669 | abort(); |
| 670 | } |
| 671 |
| 672 | hash_h(priv->pub.public_key_hash, out_encoded_public_key, |
| 673 | KYBER_PUBLIC_KEY_BYTES); |
| 674 | OPENSSL_memcpy(priv->fo_failure_secret, entropy + 32, 32); |
| 675 | } |
| 676 |
| 677 | void KYBER_public_from_private(struct KYBER_public_key *out_public_key, |
| 678 | const struct KYBER_private_key *private_key) { |
| 679 | struct public_key *const pub = public_key_from_external(out_public_key); |
| 680 | const struct private_key *const priv = private_key_from_external(private_key); |
| 681 | *pub = priv->pub; |
| 682 | } |
| 683 |
| 684 | // Algorithm 5 of the Kyber spec. Encrypts a message with given randomness to |
| 685 | // the ciphertext in |out|. Without applying the Fujisaki-Okamoto transform this |
| 686 | // would not result in a CCA secure scheme, since lattice schemes are vulnerable |
| 687 | // to decryption failure oracles. |
| 688 | static void encrypt_cpa(uint8_t out[KYBER_CIPHERTEXT_BYTES], |
| 689 | const struct public_key *pub, const uint8_t message[32], |
| 690 | const uint8_t randomness[32]) { |
| 691 | uint8_t counter = 0; |
| 692 | vector secret; |
| 693 | vector_generate_secret_eta_2(&secret, &counter, randomness); |
| 694 | vector_ntt(&secret); |
| 695 | vector error; |
| 696 | vector_generate_secret_eta_2(&error, &counter, randomness); |
| 697 | uint8_t input[33]; |
| 698 | OPENSSL_memcpy(input, randomness, 32); |
| 699 | input[32] = counter; |
| 700 | scalar scalar_error; |
| 701 | scalar_centered_binomial_distribution_eta_2_with_prf(&scalar_error, input); |
| 702 | vector u; |
| 703 | matrix_mult(&u, &pub->m, &secret); |
| 704 | vector_inverse_ntt(&u); |
| 705 | vector_add(&u, &error); |
| 706 | scalar v; |
| 707 | scalar_inner_product(&v, &pub->t, &secret); |
| 708 | scalar_inverse_ntt(&v); |
| 709 | scalar_add(&v, &scalar_error); |
| 710 | scalar expanded_message; |
| 711 | scalar_decode_1(&expanded_message, message); |
| 712 | scalar_decompress(&expanded_message, 1); |
| 713 | scalar_add(&v, &expanded_message); |
| 714 | vector_compress(&u, kDU); |
| 715 | vector_encode(out, &u, kDU); |
| 716 | scalar_compress(&v, kDV); |
| 717 | scalar_encode(out + kCompressedVectorSize, &v, kDV); |
| 718 | } |
| 719 |
| 720 | // Calls KYBER_encap_external_entropy| with random bytes from |RAND_bytes| |
| 721 | void KYBER_encap(uint8_t out_ciphertext[KYBER_CIPHERTEXT_BYTES], |
| 722 | uint8_t out_shared_secret[KYBER_SHARED_SECRET_BYTES], |
| 723 | const struct KYBER_public_key *public_key) { |
| 724 | uint8_t entropy[KYBER_ENCAP_ENTROPY]; |
| 725 | RAND_bytes(entropy, KYBER_ENCAP_ENTROPY); |
| 726 | CONSTTIME_SECRET(entropy, KYBER_ENCAP_ENTROPY); |
| 727 | KYBER_encap_external_entropy(out_ciphertext, out_shared_secret, public_key, |
| 728 | entropy); |
| 729 | } |
| 730 |
| 731 | // Algorithm 8 of the Kyber spec, safe for line 2 of the spec. The spec there |
| 732 | // hashes the output of the system's random number generator, since the FO |
| 733 | // transform will reveal it to the decrypting party. There is no reason to do |
| 734 | // this when a secure random number generator is used. When an insecure random |
| 735 | // number generator is used, the caller should switch to a secure one before |
| 736 | // calling this method. |
| 737 | void KYBER_encap_external_entropy( |
| 738 | uint8_t out_ciphertext[KYBER_CIPHERTEXT_BYTES], |
| 739 | uint8_t out_shared_secret[KYBER_SHARED_SECRET_BYTES], |
| 740 | const struct KYBER_public_key *public_key, |
| 741 | const uint8_t entropy[KYBER_ENCAP_ENTROPY]) { |
| 742 | const struct public_key *pub = public_key_from_external(public_key); |
| 743 | uint8_t input[64]; |
| 744 | OPENSSL_memcpy(input, entropy, KYBER_ENCAP_ENTROPY); |
| 745 | OPENSSL_memcpy(input + KYBER_ENCAP_ENTROPY, pub->public_key_hash, |
| 746 | sizeof(input) - KYBER_ENCAP_ENTROPY); |
| 747 | uint8_t prekey_and_randomness[64]; |
| 748 | hash_g(prekey_and_randomness, input, sizeof(input)); |
| 749 | encrypt_cpa(out_ciphertext, pub, entropy, prekey_and_randomness + 32); |
| 750 | // The ciphertext is public. |
| 751 | CONSTTIME_DECLASSIFY(out_ciphertext, KYBER_CIPHERTEXT_BYTES); |
| 752 | hash_h(prekey_and_randomness + 32, out_ciphertext, KYBER_CIPHERTEXT_BYTES); |
| 753 | kdf(out_shared_secret, KYBER_SHARED_SECRET_BYTES, prekey_and_randomness, |
| 754 | sizeof(prekey_and_randomness)); |
| 755 | } |
| 756 |
| 757 | // Algorithm 6 of the Kyber spec. |
| 758 | static void decrypt_cpa(uint8_t out[32], const struct private_key *priv, |
| 759 | const uint8_t ciphertext[KYBER_CIPHERTEXT_BYTES]) { |
| 760 | vector u; |
| 761 | vector_decode(&u, ciphertext, kDU); |
| 762 | vector_decompress(&u, kDU); |
| 763 | vector_ntt(&u); |
| 764 | scalar v; |
| 765 | scalar_decode(&v, ciphertext + kCompressedVectorSize, kDV); |
| 766 | scalar_decompress(&v, kDV); |
| 767 | scalar mask; |
| 768 | scalar_inner_product(&mask, &priv->s, &u); |
| 769 | scalar_inverse_ntt(&mask); |
| 770 | scalar_sub(&v, &mask); |
| 771 | scalar_compress(&v, 1); |
| 772 | scalar_encode_1(out, &v); |
| 773 | } |
| 774 |
| 775 | // Algorithm 9 of the Kyber spec, performing the FO transform by running |
| 776 | // encrypt_cpa on the decrypted message. The spec does not allow the decryption |
| 777 | // failure to be passed on to the caller, and instead returns a result that is |
| 778 | // deterministic but unpredictable to anyone without knowledge of the private |
| 779 | // key. |
| 780 | void KYBER_decap(uint8_t out_shared_secret[KYBER_SHARED_SECRET_BYTES], |
| 781 | const uint8_t ciphertext[KYBER_CIPHERTEXT_BYTES], |
| 782 | const struct KYBER_private_key *private_key) { |
| 783 | const struct private_key *priv = private_key_from_external(private_key); |
| 784 | uint8_t decrypted[64]; |
| 785 | decrypt_cpa(decrypted, priv, ciphertext); |
| 786 | OPENSSL_memcpy(decrypted + 32, priv->pub.public_key_hash, |
| 787 | sizeof(decrypted) - 32); |
| 788 | uint8_t prekey_and_randomness[64]; |
| 789 | hash_g(prekey_and_randomness, decrypted, sizeof(decrypted)); |
| 790 | uint8_t expected_ciphertext[KYBER_CIPHERTEXT_BYTES]; |
| 791 | encrypt_cpa(expected_ciphertext, &priv->pub, decrypted, |
| 792 | prekey_and_randomness + 32); |
| 793 | uint8_t mask = |
| 794 | constant_time_eq_int_8(CRYPTO_memcmp(ciphertext, expected_ciphertext, |
| 795 | sizeof(expected_ciphertext)), |
| 796 | 0); |
| 797 | uint8_t input[64]; |
| 798 | for (int i = 0; i < 32; i++) { |
| 799 | input[i] = constant_time_select_8(mask, prekey_and_randomness[i], |
| 800 | priv->fo_failure_secret[i]); |
| 801 | } |
| 802 | hash_h(input + 32, ciphertext, KYBER_CIPHERTEXT_BYTES); |
| 803 | kdf(out_shared_secret, KYBER_SHARED_SECRET_BYTES, input, sizeof(input)); |
| 804 | } |
| 805 |
| 806 | int KYBER_marshal_public_key(CBB *out, |
| 807 | const struct KYBER_public_key *public_key) { |
| 808 | return kyber_marshal_public_key(out, public_key_from_external(public_key)); |
| 809 | } |
| 810 |
| 811 | // kyber_parse_public_key_no_hash parses |in| into |pub| but doesn't calculate |
| 812 | // the value of |pub->public_key_hash|. |
| 813 | static int kyber_parse_public_key_no_hash(struct public_key *pub, CBS *in) { |
| 814 | CBS t_bytes; |
| 815 | if (!CBS_get_bytes(in, &t_bytes, kEncodedVectorSize) || |
| 816 | !vector_decode(&pub->t, CBS_data(&t_bytes), kLog2Prime) || |
| 817 | !CBS_copy_bytes(in, pub->rho, sizeof(pub->rho))) { |
| 818 | return 0; |
| 819 | } |
| 820 | matrix_expand(&pub->m, pub->rho); |
| 821 | return 1; |
| 822 | } |
| 823 |
| 824 | int KYBER_parse_public_key(struct KYBER_public_key *public_key, CBS *in) { |
| 825 | struct public_key *pub = public_key_from_external(public_key); |
| 826 | CBS orig_in = *in; |
| 827 | if (!kyber_parse_public_key_no_hash(pub, in) || // |
| 828 | CBS_len(in) != 0) { |
| 829 | return 0; |
| 830 | } |
| 831 | hash_h(pub->public_key_hash, CBS_data(&orig_in), CBS_len(&orig_in)); |
| 832 | return 1; |
| 833 | } |
| 834 |
| 835 | int KYBER_marshal_private_key(CBB *out, |
| 836 | const struct KYBER_private_key *private_key) { |
| 837 | const struct private_key *const priv = private_key_from_external(private_key); |
| 838 | uint8_t *s_output; |
| 839 | if (!CBB_add_space(out, &s_output, kEncodedVectorSize)) { |
| 840 | return 0; |
| 841 | } |
| 842 | vector_encode(s_output, &priv->s, kLog2Prime); |
| 843 | if (!kyber_marshal_public_key(out, &priv->pub) || |
| 844 | !CBB_add_bytes(out, priv->pub.public_key_hash, |
| 845 | sizeof(priv->pub.public_key_hash)) || |
| 846 | !CBB_add_bytes(out, priv->fo_failure_secret, |
| 847 | sizeof(priv->fo_failure_secret))) { |
| 848 | return 0; |
| 849 | } |
| 850 | return 1; |
| 851 | } |
| 852 |
| 853 | int KYBER_parse_private_key(struct KYBER_private_key *out_private_key, |
| 854 | CBS *in) { |
| 855 | struct private_key *const priv = private_key_from_external(out_private_key); |
| 856 |
| 857 | CBS s_bytes; |
| 858 | if (!CBS_get_bytes(in, &s_bytes, kEncodedVectorSize) || |
| 859 | !vector_decode(&priv->s, CBS_data(&s_bytes), kLog2Prime) || |
| 860 | !kyber_parse_public_key_no_hash(&priv->pub, in) || |
| 861 | !CBS_copy_bytes(in, priv->pub.public_key_hash, |
| 862 | sizeof(priv->pub.public_key_hash)) || |
| 863 | !CBS_copy_bytes(in, priv->fo_failure_secret, |
| 864 | sizeof(priv->fo_failure_secret)) || |
| 865 | CBS_len(in) != 0) { |
| 866 | return 0; |
| 867 | } |
| 868 | return 1; |
| 869 | } |
| 870 |