Debian Codegraph @

src/lib/pubkey/curve448/x448/x448_internal.cpp

raw
1 /*
2 * X448 Internal
3 * (C) 2024 Jack Lloyd
4 * 2024 Fabian Albert - Rohde & Schwarz Cybersecurity
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 */
8 #include <botan/internal/x448_internal.h>
9
10 #include <botan/internal/ct_utils.h>
11 #include <botan/internal/curve448_gf.h>
12
13 namespace Botan {
14
15 namespace {
16 uint64_t get_bit(const ScalarX448& scalar, size_t bit) {
17 return (scalar[bit / 8] >> (bit % 8)) & 1;
18 }
19 } // namespace
20
21 secure_vector<uint8_t> encode_point(const Point448& p) {
22 return {p.begin(), p.end()};
23 }
24
25 Point448 decode_point(std::span<const uint8_t> p_bytes) {
26 BOTAN_ARG_CHECK(p_bytes.size() == X448_LEN, "Invalid size for X448 point");
27 return typecast_copy<Point448>(p_bytes);
28 }
29
30 ScalarX448 decode_scalar(std::span<const uint8_t> scalar_bytes) {
31 BOTAN_ARG_CHECK(scalar_bytes.size() == X448_LEN, "Invalid size for X448 scalar");
32 auto buf = typecast_copy<ScalarX448>(scalar_bytes);
33
34 buf[0] &= 0xfc;
35 buf[55] |= 0x80;
36
37 return buf;
38 }
39
40 /// Multiply a scalar with the base group element (5)
41 Point448 x448_basepoint(const ScalarX448& k) {
42 const Point448 u({5});
43 return x448(k, u);
44 }
45
46 // Algorithm see RFC 7748, Section 5:
47 // https://datatracker.ietf.org/doc/html/rfc7748#section-5
48 Point448 x448(const ScalarX448& k, const Point448& u) {
49 const Gf448Elem x_1 = Gf448Elem(u.get());
50 Gf448Elem x_2 = Gf448Elem::one();
51 Gf448Elem z_2 = Gf448Elem::zero();
52 Gf448Elem x_3 = Gf448Elem(u.get());
53 Gf448Elem z_3 = Gf448Elem::one();
54 auto swap = CT::Mask<uint64_t>::cleared();
55
56 for(int16_t t = 448 - 1; t >= 0; --t) {
57 auto k_t = CT::Mask<uint64_t>::expand(get_bit(k, t));
58 swap ^= k_t;
59
60 x_2.ct_cond_swap(swap, x_3);
61 z_2.ct_cond_swap(swap, z_3);
62 swap = k_t;
63
64 const auto A = x_2 + z_2;
65 const auto AA = square(A);
66 const auto B = x_2 - z_2;
67 const auto BB = square(B);
68 const auto E = AA - BB;
69 const auto C = x_3 + z_3;
70 const auto D = x_3 - z_3;
71 const auto DA = D * A;
72 const auto CB = C * B;
73 x_3 = square(DA + CB);
74 z_3 = x_1 * square(DA - CB);
75 x_2 = AA * BB;
76 z_2 = E * (AA + mul_a24(E));
77 }
78
79 x_2.ct_cond_swap(swap, x_3);
80 z_2.ct_cond_swap(swap, z_3);
81
82 const auto res = x_2 / z_2;
83
84 return Point448(res.to_bytes());
85 }
86
87 } // namespace Botan