Botan 3.9.0
Crypto and TLS for C&
pcurves_wrap.h
Go to the documentation of this file.
1/*
2* (C) 2024 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#ifndef BOTAN_PCURVES_WRAP_H_
8#define BOTAN_PCURVES_WRAP_H_
9
10#include <botan/exceptn.h>
11#include <botan/internal/pcurves.h>
12#include <botan/internal/pcurves_impl.h>
13
14namespace Botan::PCurve {
15
16template <typename C>
17concept curve_supports_scalar_invert = requires(const typename C::Scalar& s) {
18 { C::scalar_invert(s) } -> std::same_as<typename C::Scalar>;
19};
20
21/**
22* This class provides a bridge between the "public" (actually still
23* internal) PrimeOrderCurve type, and the inner templates which are
24* subclasses of EllipticCurve from pcurves_impl.h
25*/
26template <typename C>
28 public:
29 static_assert(C::OrderBits <= PrimeOrderCurve::MaximumBitLength);
30 static_assert(C::PrimeFieldBits <= PrimeOrderCurve::MaximumBitLength);
31
32 size_t order_bits() const override { return C::OrderBits; }
33
34 size_t scalar_bytes() const override { return C::Scalar::BYTES; }
35
36 size_t field_element_bytes() const override { return C::FieldElement::BYTES; }
37
38 ProjectivePoint mul_by_g(const Scalar& scalar, RandomNumberGenerator& rng) const override {
39 return stash(m_mul_by_g.mul(from_stash(scalar), rng));
40 }
41
42 ProjectivePoint mul(const AffinePoint& pt, const Scalar& scalar, RandomNumberGenerator& rng) const override {
43 auto tbl = WindowedBoothMulTable<C, VarPointWindowBits>(from_stash(pt));
44 return stash(tbl.mul(from_stash(scalar), rng));
45 }
46
48 const Scalar& scalar,
49 RandomNumberGenerator& rng) const override {
50 auto tbl = WindowedBoothMulTable<C, VarPointWindowBits>(from_stash(pt));
51 auto pt_x = to_affine_x<C>(tbl.mul(from_stash(scalar), rng));
52 secure_vector<uint8_t> x_bytes(C::FieldElement::BYTES);
53 pt_x.serialize_to(std::span<uint8_t, C::FieldElement::BYTES>{x_bytes});
54 return x_bytes;
55 }
56
58 public:
59 const auto& table() const { return m_table; }
60
61 explicit PrecomputedMul2TableC(const typename C::AffinePoint& x, const typename C::AffinePoint& y) :
62 m_table(x, y) {}
63
64 private:
66 };
67
68 std::unique_ptr<const PrecomputedMul2Table> mul2_setup_g(const AffinePoint& q) const override {
69 return std::make_unique<PrecomputedMul2TableC>(C::G, from_stash(q));
70 }
71
72 std::optional<ProjectivePoint> mul2_vartime(const PrecomputedMul2Table& tableb,
73 const Scalar& x,
74 const Scalar& y) const override {
75 try {
76 const auto& table = dynamic_cast<const PrecomputedMul2TableC&>(tableb);
77 auto pt = table.table().mul2_vartime(from_stash(x), from_stash(y));
78 if(pt.is_identity().as_bool()) {
79 return {};
80 } else {
81 return stash(pt);
82 }
83 } catch(std::bad_cast&) {
84 throw Invalid_Argument("Curve mismatch");
85 }
86 }
87
88 std::optional<ProjectivePoint> mul_px_qy(const AffinePoint& p,
89 const Scalar& x,
90 const AffinePoint& q,
91 const Scalar& y,
92 RandomNumberGenerator& rng) const override {
93 WindowedMul2Table<C, Mul2WindowBits> tbl(from_stash(p), from_stash(q));
94 auto pt = tbl.mul2(from_stash(x), from_stash(y), rng);
95 if(pt.is_identity().as_bool()) {
96 return {};
97 } else {
98 return stash(pt);
99 }
100 }
101
103 const Scalar& v,
104 const Scalar& x,
105 const Scalar& y) const override {
106 try {
107 const auto& table = dynamic_cast<const PrecomputedMul2TableC&>(tableb);
108 const auto pt = table.table().mul2_vartime(from_stash(x), from_stash(y));
109 // Variable time here, so the early return is fine
110 if(pt.is_identity().as_bool()) {
111 return false;
112 }
113
114 /*
115 * Avoid the inversion by instead projecting v.
116 *
117 * Given (x*z2) and v we want to know if x % n == v
118 *
119 * Inverting z2 to extract x is expensive. Instead compute (v*z2) and
120 * compare it with (x*z2).
121 *
122 * With overwhelming probability, this conversion is correct. The
123 * only time it is not is in the extremely unlikely case where the
124 * signer actually reduced the x coordinate modulo the group order.
125 * That is handled seperately in a second step.
126 */
127 const auto z2 = pt.z().square();
128
129 std::array<uint8_t, C::Scalar::BYTES> v_bytes{};
130 from_stash(v).serialize_to(v_bytes);
131
132 if(const auto fe_v = C::FieldElement::deserialize(v_bytes)) {
133 if((*fe_v * z2 == pt.x()).as_bool()) {
134 return true;
135 }
136
137 /*
138 * Possibly (if cryptographically unlikely) the signer
139 * reduced the value modulo the group order.
140 *
141 * If so we must check v + n similarly as before. However here
142 * we must be careful to not overflow since otherwise that
143 * would lead to us accepting an incorrect signature.
144 *
145 * If the order is > p then the reduction modulo p would not have
146 * had any effect and we don't need to consider the possibility
147 */
148 if constexpr(C::OrderIsLessThanField) {
149 /*
150 * We have to be careful to avoid overflow since this would
151 * lead to a forgery
152 *
153 * v < (p)-n => v + n < p
154 *
155 * The values n and neg_n could be precomputed but they are
156 * fast to compute and this codepath will ~never be taken
157 * unless when verifying an invalid signature. In any case
158 * it is many times cheaper than performing the modular inversion
159 * which this approach avoids.
160 */
161
162 // Create the group order as a field element, safe because n < p
163 const auto n = C::FieldElement::from_words(C::NW);
164 const auto neg_n = n.negate().to_words();
165
166 const auto vw = fe_v->to_words();
167 if(bigint_ct_is_lt(vw.data(), vw.size(), neg_n.data(), neg_n.size()).as_bool()) {
168 return (((*fe_v + n) * z2) == pt.x()).as_bool();
169 }
170 }
171 }
172
173 return false;
174 } catch(std::bad_cast&) {
175 throw Invalid_Argument("Curve mismatch");
176 }
177 }
178
179 Scalar base_point_mul_x_mod_order(const Scalar& scalar, RandomNumberGenerator& rng) const override {
180 auto pt = m_mul_by_g.mul(from_stash(scalar), rng);
181 std::array<uint8_t, C::FieldElement::BYTES> x_bytes{};
182 to_affine_x<C>(pt).serialize_to(std::span{x_bytes});
183 // Reduction might be required (if unlikely)
184 return stash(C::Scalar::from_wide_bytes(std::span<const uint8_t, C::FieldElement::BYTES>{x_bytes}));
185 }
186
187 AffinePoint generator() const override { return stash(C::G); }
188
189 AffinePoint point_to_affine(const ProjectivePoint& pt) const override {
190 auto affine = to_affine<C>(from_stash(pt));
191
192 const auto y2 = affine.y().square();
193 const auto x3_ax_b = C::x3_ax_b(affine.x());
194 const auto valid_point = affine.is_identity() || (y2 == x3_ax_b);
195
196 BOTAN_ASSERT(valid_point.as_bool(), "Computed point is on the curve");
197
198 return stash(affine);
199 }
200
201 ProjectivePoint point_add(const AffinePoint& a, const AffinePoint& b) const override {
202 return stash(C::ProjectivePoint::from_affine(from_stash(a)) + from_stash(b));
203 }
204
205 AffinePoint point_negate(const AffinePoint& pt) const override { return stash(from_stash(pt).negate()); }
206
207 bool affine_point_is_identity(const AffinePoint& pt) const override {
208 return from_stash(pt).is_identity().as_bool();
209 }
210
211 void serialize_point(std::span<uint8_t> bytes, const AffinePoint& pt) const override {
212 BOTAN_ARG_CHECK(bytes.size() == C::AffinePoint::BYTES, "Invalid length for serialize_point");
213 from_stash(pt).serialize_to(bytes.subspan<0, C::AffinePoint::BYTES>());
214 }
215
216 void serialize_scalar(std::span<uint8_t> bytes, const Scalar& scalar) const override {
217 BOTAN_ARG_CHECK(bytes.size() == C::Scalar::BYTES, "Invalid length to serialize_scalar");
218 return from_stash(scalar).serialize_to(bytes.subspan<0, C::Scalar::BYTES>());
219 }
220
221 std::optional<Scalar> deserialize_scalar(std::span<const uint8_t> bytes) const override {
222 if(auto scalar = C::Scalar::deserialize(bytes)) {
223 if(!scalar->is_zero().as_bool()) {
224 return stash(*scalar);
225 }
226 }
227
228 return {};
229 }
230
231 std::optional<Scalar> scalar_from_wide_bytes(std::span<const uint8_t> bytes) const override {
232 if(auto s = C::Scalar::from_wide_bytes_varlen(bytes)) {
233 return stash(*s);
234 } else {
235 return {};
236 }
237 }
238
239 std::optional<AffinePoint> deserialize_point(std::span<const uint8_t> bytes) const override {
240 // The identity element (see SEC1 section 2.3.4)
241 // TODO(Botan4) remove this - we should reject the identity encoding
242 if(bytes.size() == 1 && bytes[0] == 0x00) {
243 return stash(C::AffinePoint::identity());
244 }
245
246 constexpr size_t FieldElementBytes = C::FieldElement::BYTES;
247 constexpr size_t CompressedBytes = C::FieldElement::BYTES + 1;
248 constexpr size_t UncompressedBytes = 2 * C::FieldElement::BYTES + 1;
249
250 if(bytes.size() == UncompressedBytes && bytes[0] == 0x04) {
251 const auto encoded_point = bytes.subspan(1);
252 auto x = C::FieldElement::deserialize(encoded_point.first(FieldElementBytes));
253 auto y = C::FieldElement::deserialize(encoded_point.last(FieldElementBytes));
254
255 if(x && y) {
256 // Check that y^2 = x^3 + ax + b
257 const auto lhs = (*y).square();
258 const auto rhs = C::x3_ax_b(*x);
259 const auto valid = (lhs == rhs);
260 if(valid.as_bool()) {
261 return stash(typename C::AffinePoint(*x, *y));
262 }
263 }
264 } else if(bytes.size() == CompressedBytes && (bytes[0] == 0x02 || bytes[0] == 0x03)) {
265 const CT::Choice y_is_even = CT::Mask<uint8_t>::is_equal(bytes[0], 0x02).as_choice();
266
267 if(auto x = C::FieldElement::deserialize(bytes.subspan(1, FieldElementBytes))) {
268 if(auto y = sqrt_field_element<C>(C::x3_ax_b(*x)).as_optional_vartime()) {
269 return stash(typename C::AffinePoint(*x, y->correct_sign(y_is_even)));
270 }
271 }
272 }
273
274 return {};
275 }
276
277 AffinePoint hash_to_curve_nu(std::function<void(std::span<uint8_t>)> expand_message) const override {
278 if constexpr(C::ValidForSswuHash) {
279 return stash(hash_to_curve_sswu<C, false>(expand_message));
280 } else {
281 throw Not_Implemented("Hash to curve is not implemented for this curve");
282 }
283 }
284
285 ProjectivePoint hash_to_curve_ro(std::function<void(std::span<uint8_t>)> expand_message) const override {
286 if constexpr(C::ValidForSswuHash) {
287 return stash(hash_to_curve_sswu<C, true>(expand_message));
288 } else {
289 throw Not_Implemented("Hash to curve is not implemented for this curve");
290 }
291 }
292
293 Scalar scalar_add(const Scalar& a, const Scalar& b) const override {
294 return stash(from_stash(a) + from_stash(b));
295 }
296
297 Scalar scalar_sub(const Scalar& a, const Scalar& b) const override {
298 return stash(from_stash(a) - from_stash(b));
299 }
300
301 Scalar scalar_mul(const Scalar& a, const Scalar& b) const override {
302 return stash(from_stash(a) * from_stash(b));
303 }
304
305 Scalar scalar_square(const Scalar& s) const override { return stash(from_stash(s).square()); }
306
307 Scalar scalar_invert(const Scalar& ss) const override {
308 auto s = from_stash(ss);
309 if constexpr(curve_supports_scalar_invert<C>) {
310 return stash(C::scalar_invert(s));
311 } else {
312 return stash(s.invert());
313 }
314 }
315
316 Scalar scalar_invert_vartime(const Scalar& ss) const override {
317 auto s = from_stash(ss);
318 return stash(s.invert_vartime());
319 }
320
321 Scalar scalar_negate(const Scalar& s) const override { return stash(from_stash(s).negate()); }
322
323 bool scalar_is_zero(const Scalar& s) const override { return from_stash(s).is_zero().as_bool(); }
324
325 bool scalar_equal(const Scalar& a, const Scalar& b) const override {
326 return (from_stash(a) == from_stash(b)).as_bool();
327 }
328
329 Scalar scalar_one() const override { return stash(C::Scalar::one()); }
330
331 Scalar random_scalar(RandomNumberGenerator& rng) const override { return stash(C::Scalar::random(rng)); }
332
333 PrimeOrderCurveImpl() : m_mul_by_g(C::G) {}
334
335 static std::shared_ptr<const PrimeOrderCurve> instance() {
336 static auto g_curve = std::make_shared<const PrimeOrderCurveImpl<C>>();
337 return g_curve;
338 }
339
340 private:
341 static Scalar stash(const typename C::Scalar& s) {
342 return Scalar::_create(instance(), s.template stash_value<StorageWords>());
343 }
344
345 static typename C::Scalar from_stash(const Scalar& s) {
346 if(s._curve() != instance()) {
347 throw Invalid_Argument("Curve mismatch");
348 }
349 return C::Scalar::from_stash(s._value());
350 }
351
352 static AffinePoint stash(const typename C::AffinePoint& pt) {
353 auto x_w = pt.x().template stash_value<StorageWords>();
354 auto y_w = pt.y().template stash_value<StorageWords>();
355 return AffinePoint::_create(instance(), x_w, y_w);
356 }
357
358 static typename C::AffinePoint from_stash(const AffinePoint& pt) {
359 if(pt._curve() != instance()) {
360 throw Invalid_Argument("Curve mismatch");
361 }
362 auto x = C::FieldElement::from_stash(pt._x());
363 auto y = C::FieldElement::from_stash(pt._y());
364 return typename C::AffinePoint(x, y);
365 }
366
367 static ProjectivePoint stash(const typename C::ProjectivePoint& pt) {
368 auto x_w = pt.x().template stash_value<StorageWords>();
369 auto y_w = pt.y().template stash_value<StorageWords>();
370 auto z_w = pt.z().template stash_value<StorageWords>();
371 return ProjectivePoint::_create(instance(), x_w, y_w, z_w);
372 }
373
374 static typename C::ProjectivePoint from_stash(const ProjectivePoint& pt) {
375 if(pt._curve() != instance()) {
376 throw Invalid_Argument("Curve mismatch");
377 }
378 auto x = C::FieldElement::from_stash(pt._x());
379 auto y = C::FieldElement::from_stash(pt._y());
380 auto z = C::FieldElement::from_stash(pt._z());
381 return typename C::ProjectivePoint(x, y, z);
382 }
383
384 private:
385 const PrecomputedBaseMulTable<C, BasePointWindowBits> m_mul_by_g;
386};
387
388} // namespace Botan::PCurve
389
390#endif
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:62
static constexpr Mask< T > is_equal(T x, T y)
Definition ct_utils.h:470
PrecomputedMul2TableC(const typename C::AffinePoint &x, const typename C::AffinePoint &y)
AffinePoint point_negate(const AffinePoint &pt) const override
Scalar scalar_invert(const Scalar &ss) const override
Scalar inversion.
size_t field_element_bytes() const override
std::unique_ptr< const PrecomputedMul2Table > mul2_setup_g(const AffinePoint &q) const override
Setup a table for 2-ary multiplication where the first point is the generator.
bool scalar_equal(const Scalar &a, const Scalar &b) const override
Test if two scalars are equal.
void serialize_scalar(std::span< uint8_t > bytes, const Scalar &scalar) const override
bool affine_point_is_identity(const AffinePoint &pt) const override
Scalar scalar_sub(const Scalar &a, const Scalar &b) const override
Scalar subtraction.
size_t order_bits() const override
Return the bit length of the group order.
AffinePoint generator() const override
Return the standard generator.
ProjectivePoint mul_by_g(const Scalar &scalar, RandomNumberGenerator &rng) const override
size_t scalar_bytes() const override
Return the byte length of the scalar element.
AffinePoint hash_to_curve_nu(std::function< void(std::span< uint8_t >)> expand_message) const override
bool scalar_is_zero(const Scalar &s) const override
Test if scalar is zero.
Scalar scalar_one() const override
static std::shared_ptr< const PrimeOrderCurve > instance()
std::optional< Scalar > scalar_from_wide_bytes(std::span< const uint8_t > bytes) const override
ProjectivePoint hash_to_curve_ro(std::function< void(std::span< uint8_t >)> expand_message) const override
Scalar base_point_mul_x_mod_order(const Scalar &scalar, RandomNumberGenerator &rng) const override
std::optional< Scalar > deserialize_scalar(std::span< const uint8_t > bytes) const override
Scalar scalar_add(const Scalar &a, const Scalar &b) const override
Scalar addition.
Scalar scalar_negate(const Scalar &s) const override
Scalar negation.
Scalar scalar_invert_vartime(const Scalar &ss) const override
Scalar inversion (variable time)
bool mul2_vartime_x_mod_order_eq(const PrecomputedMul2Table &tableb, const Scalar &v, const Scalar &x, const Scalar &y) const override
ProjectivePoint point_add(const AffinePoint &a, const AffinePoint &b) const override
std::optional< AffinePoint > deserialize_point(std::span< const uint8_t > bytes) const override
Scalar random_scalar(RandomNumberGenerator &rng) const override
void serialize_point(std::span< uint8_t > bytes, const AffinePoint &pt) const override
Scalar scalar_square(const Scalar &s) const override
Scalar squaring.
secure_vector< uint8_t > mul_x_only(const AffinePoint &pt, const Scalar &scalar, RandomNumberGenerator &rng) const override
Scalar scalar_mul(const Scalar &a, const Scalar &b) const override
Scalar multiplication.
AffinePoint point_to_affine(const ProjectivePoint &pt) const override
std::optional< ProjectivePoint > mul2_vartime(const PrecomputedMul2Table &tableb, const Scalar &x, const Scalar &y) const override
ProjectivePoint mul(const AffinePoint &pt, const Scalar &scalar, RandomNumberGenerator &rng) const override
std::optional< ProjectivePoint > mul_px_qy(const AffinePoint &p, const Scalar &x, const AffinePoint &q, const Scalar &y, RandomNumberGenerator &rng) const override
static constexpr size_t MaximumBitLength
Definition pcurves.h:38
ProjectivePoint mul2(const Scalar &s1, const Scalar &s2, RandomNumberGenerator &rng) const
auto to_affine_x(const typename C::ProjectivePoint &pt)
constexpr CT::Option< typename C::FieldElement > sqrt_field_element(const typename C::FieldElement &fe)
BigInt square(const BigInt &x)
Definition numthry.cpp:157
auto hash_to_curve_sswu(const ExpandMsg &expand_message) -> std::conditional_t< RO, typename C::ProjectivePoint, typename C::AffinePoint >
constexpr auto to_affine(const typename C::ProjectivePoint &pt)
constexpr auto bigint_ct_is_lt(const W x[], size_t x_size, const W y[], size_t y_size, bool lt_or_equal=false) -> CT::Mask< W >
Definition mp_core.h:475
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:69