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    for j in (0..256).rev() {
34        i = j;
35        if a_naf[i] != 0 || b_naf[i] != 0 {
36            break;
37        }
38    }
39
40    let table_A = NafLookupTable5::<ProjectiveNielsPoint>::from(A);
41    #[cfg(feature = "precomputed-tables")]
42    let table_B = &constants::AFFINE_ODD_MULTIPLES_OF_BASEPOINT;
43    #[cfg(not(feature = "precomputed-tables"))]
44    let table_B =
45        &NafLookupTable5::<ProjectiveNielsPoint>::from(&constants::ED25519_BASEPOINT_POINT);
46
47    let mut r = ProjectivePoint::identity();
48    loop {
49        let mut t = r.double();
50
51        match a_naf[i].cmp(&0) {
52            Ordering::Greater => t = &t.as_extended() + &table_A.select(a_naf[i] as usize),
53            Ordering::Less => t = &t.as_extended() - &table_A.select(-a_naf[i] as usize),
54            Ordering::Equal => {}
55        }
56
57        match b_naf[i].cmp(&0) {
58            Ordering::Greater => t = &t.as_extended() + &table_B.select(b_naf[i] as usize),
59            Ordering::Less => t = &t.as_extended() - &table_B.select(-b_naf[i] as usize),
60            Ordering::Equal => {}
61        }
62
63        r = t.as_projective();
64
65        if i == 0 {
66            break;
67        }
68        i -= 1;
69    }
70
71    r.as_extended()
72}