curve25519_dalek/backend/serial/scalar_mul/
vartime_double_base.rs

1// -*- mode: rust; -*-
2//
3// This file is part of curve25519-dalek.
4// Copyright (c) 2016-2021 isis lovecruft
5// Copyright (c) 2016-2019 Henry de Valence
6// See LICENSE for licensing information.
7//
8// Authors:
9// - isis agora lovecruft <isis@patternsinthevoid.net>
10// - Henry de Valence <hdevalence@hdevalence.ca>
11#![allow(non_snake_case)]
12
13use core::cmp::Ordering;
14
15use crate::backend::serial::curve_models::{ProjectiveNielsPoint, ProjectivePoint};
16use crate::constants;
17use crate::edwards::EdwardsPoint;
18use crate::scalar::Scalar;
19use crate::traits::Identity;
20use crate::window::NafLookupTable5;
21
22/// Compute \\(aA + bB\\) in variable time, where \\(B\\) is the Ed25519 basepoint.
23pub fn mul(a: &Scalar, A: &EdwardsPoint, b: &Scalar) -> EdwardsPoint {
24    let a_naf = a.non_adjacent_form(5);
25
26    #[cfg(feature = "precomputed-tables")]
27    let b_naf = b.non_adjacent_form(8);
28    #[cfg(not(feature = "precomputed-tables"))]
29    let b_naf = b.non_adjacent_form(5);
30
31    // Find starting index
32    let mut i: usize = 255;
33    let mut j: usize = 256;
34    while j > 0 {
35        j -= 1;
36        i = j;
37        if a_naf[i] != 0 || b_naf[i] != 0 {
38            break;
39        }
40    }
41
42    let table_A = NafLookupTable5::<ProjectiveNielsPoint>::from(A);
43    #[cfg(feature = "precomputed-tables")]
44    let table_B = &constants::AFFINE_ODD_MULTIPLES_OF_BASEPOINT;
45    #[cfg(not(feature = "precomputed-tables"))]
46    let table_B =
47        &NafLookupTable5::<ProjectiveNielsPoint>::from(&constants::ED25519_BASEPOINT_POINT);
48
49    let mut r = ProjectivePoint::identity();
50    loop {
51        let mut t = r.double();
52
53        match a_naf[i].cmp(&0) {
54            Ordering::Greater => t = &t.as_extended() + &table_A.select(a_naf[i] as usize),
55            Ordering::Less => t = &t.as_extended() - &table_A.select(-a_naf[i] as usize),
56            Ordering::Equal => {}
57        }
58
59        match b_naf[i].cmp(&0) {
60            Ordering::Greater => t = &t.as_extended() + &table_B.select(b_naf[i] as usize),
61            Ordering::Less => t = &t.as_extended() - &table_B.select(-b_naf[i] as usize),
62            Ordering::Equal => {}
63        }
64
65        r = t.as_projective();
66
67        if i == 0 {
68            break;
69        }
70        i -= 1;
71    }
72
73    r.as_extended()
74}