Botan 3.6.1
Crypto and TLS for C&
mce_workfactor.cpp
Go to the documentation of this file.
1/*
2 * (C) Copyright Projet SECRET, INRIA, Rocquencourt
3 * (C) Bhaskar Biswas and Nicolas Sendrier
4 * (C) 2014 Jack Lloyd
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 *
8 */
9
10#include <botan/mceliece.h>
11
12#include <botan/internal/bit_ops.h>
13#include <cmath>
14#include <numbers>
15
16namespace Botan {
17
18namespace {
19
20double binomial(size_t n, size_t k) {
21 double x = 1;
22
23 for(size_t i = 0; i != k; ++i) {
24 x *= n - i;
25 x /= k - i;
26 }
27
28 return x;
29}
30
31double log_binomial(size_t n, size_t k) {
32 double x = 0;
33
34 for(size_t i = 0; i != k; ++i) {
35 x += std::log(n - i);
36 x -= std::log(k - i);
37 }
38
39 return x / std::numbers::ln2;
40}
41
42double nb_iter(size_t n, size_t k, size_t w, size_t p, size_t l) {
43 double x = 2 * log_binomial(k / 2, p);
44 x += log_binomial(n - k - l, w - 2 * p);
45 x = log_binomial(n, w) - x;
46 return x;
47}
48
49double cout_iter(size_t n, size_t k, size_t p, size_t l) {
50 double x = binomial(k / 2, p);
51 const size_t i = static_cast<size_t>(std::log(x) / std::numbers::ln2);
52 double res = 2 * p * (n - k - l) * std::ldexp(x * x, -static_cast<int>(l));
53
54 // x <- binomial(k/2,p)*2*(2*l+log[2](binomial(k/2,p)))
55 x *= 2 * (2 * l + i);
56
57 // res <- k*(n-k)/2 +
58 // binomial(k/2,p)*2*(2*l+log[2](binomial(k/2,p))) +
59 // 2*p*(n-k-l)*binomial(k/2,p)^2/2^l
60 res += x + k * ((n - k) / 2.0);
61
62 return std::log(res) / std::numbers::ln2; // convert to bits
63}
64
65double cout_total(size_t n, size_t k, size_t w, size_t p, size_t l) {
66 return nb_iter(n, k, w, p, l) + cout_iter(n, k, p, l);
67}
68
69double best_wf(size_t n, size_t k, size_t w, size_t p) {
70 if(p >= k / 2) {
71 return -1;
72 }
73
74 double min = cout_total(n, k, w, p, 0);
75
76 for(size_t l = 1; l < n - k; ++l) {
77 const double lwf = cout_total(n, k, w, p, l);
78 if(lwf < min) {
79 min = lwf;
80 } else {
81 break;
82 }
83 }
84
85 return min;
86}
87
88} // namespace
89
90size_t mceliece_work_factor(size_t n, size_t t) {
91 const size_t k = n - ceil_log2(n) * t;
92
93 double min = cout_total(n, k, t, 0, 0); // correspond a p=1
94 for(size_t p = 0; p != t / 2; ++p) {
95 double lwf = best_wf(n, k + 1, t, p);
96 if(lwf < 0) {
97 break;
98 }
99
100 min = std::min(min, lwf);
101 }
102
103 return static_cast<size_t>(min);
104}
105
106} // namespace Botan
size_t mceliece_work_factor(size_t n, size_t t)
constexpr uint8_t ceil_log2(T x)
Definition bit_ops.h:122