Merge branch 'release/0.14.0'

This commit is contained in:
Isis Lovecruft 2017-12-04 02:10:25 +00:00
commit 251b1d591d
Failed to extract signature
30 changed files with 2376 additions and 4824 deletions

View file

@ -1,6 +1,6 @@
[package] [package]
name = "curve25519-dalek" name = "curve25519-dalek"
version = "0.13.2" version = "0.14.0"
authors = ["Isis Lovecruft <isis@patternsinthevoid.net>", authors = ["Isis Lovecruft <isis@patternsinthevoid.net>",
"Henry de Valence <hdevalence@hdevalence.ca>"] "Henry de Valence <hdevalence@hdevalence.ca>"]
readme = "README.md" readme = "README.md"
@ -12,9 +12,11 @@ categories = ["cryptography", "no-std"]
keywords = ["cryptography", "curve25519", "elliptic", "curve", "ECC"] keywords = ["cryptography", "curve25519", "elliptic", "curve", "ECC"]
description = "A low-level cryptographic library for point, group, field, and scalar operations on a curve isomorphic to the twisted Edwards curve defined by -x²+y² = 1 - 121665/121666 x²y² over GF(2²⁵⁵ - 19)." description = "A low-level cryptographic library for point, group, field, and scalar operations on a curve isomorphic to the twisted Edwards curve defined by -x²+y² = 1 - 121665/121666 x²y² over GF(2²⁵⁵ - 19)."
exclude = [ exclude = [
"**/.gitignore",
".gitignore", ".gitignore",
".travis.yml", ".travis.yml",
] ]
build = "build.rs"
[package.metadata.docs.rs] [package.metadata.docs.rs]
rustdoc-args = ["--html-in-header", ".cargo/registry/src/github.com-1ecc6299db9ec823/curve25519-dalek-0.13.2/rustdoc-include-katex-header.html"] rustdoc-args = ["--html-in-header", ".cargo/registry/src/github.com-1ecc6299db9ec823/curve25519-dalek-0.13.2/rustdoc-include-katex-header.html"]
@ -26,9 +28,6 @@ travis-ci = { repository = "isislovecruft/curve25519-dalek", branch = "master"}
version = "1.0" version = "1.0"
optional = true optional = true
[dependencies.arrayref]
version = "0.3.4"
[dependencies.rand] [dependencies.rand]
optional = true optional = true
version = "0.3" version = "0.3"
@ -50,6 +49,17 @@ version = "0.6"
[dev-dependencies.serde_cbor] [dev-dependencies.serde_cbor]
version = "0.6" version = "0.6"
[build-dependencies]
subtle = "^0.3"
rand = "0.3"
generic-array = "^0.8"
digest = "0.6"
arrayref = "0.3.4"
[build-dependencies.serde]
version = "1.0"
optional = true
[features] [features]
nightly = ["radix_51", "subtle/nightly"] nightly = ["radix_51", "subtle/nightly"]
default = ["std"] default = ["std"]
@ -60,3 +70,6 @@ yolocrypto = []
bench = [] bench = []
# Radix-51 arithmetic using u128 # Radix-51 arithmetic using u128
radix_51 = [] radix_51 = []
# Include precomputed basepoint tables. This is off by default so that build.rs can generate the tables, and then re-enabled by build.rs in the main-stage compilation.
precomputed_tables = []

View file

@ -1,3 +1,8 @@
FEATURES := nightly yolocrypto
doc: doc:
cargo rustdoc --features "nightly yolocrypto" -- --html-in-header katex-header.html cargo rustdoc --features "$(FEATURES)" -- --html-in-header rustdoc-include-katex-header.html
doc-internal:
cargo rustdoc --features "$(FEATURES)" -- --html-in-header rustdoc-include-katex-header.html --document-private-items

View file

@ -44,22 +44,34 @@ Extensive documentation is available [here](https://docs.rs/curve25519-dalek).
To install, add the following to the dependencies section of your project's To install, add the following to the dependencies section of your project's
`Cargo.toml`: `Cargo.toml`:
curve25519-dalek = "^0.13" ```toml
curve25519-dalek = "^0.14"
```
Then, in your library or executable source, add: Then, in your library or executable source, add:
extern crate curve25519_dalek extern crate curve25519_dalek;
## Features
On nightly Rust, using the `nightly` feature enables a radix-51 field On nightly Rust, using the `nightly` feature enables a radix-51 field
arithmetic implementation using `u128`s, which is approximately twice as arithmetic implementation using `u128`s, which is approximately twice as
fast. fast. It will also enable additional developer documentation when
compiling via `make doc-internal`.
By default, the benchmarks are not compiled without the `bench`
feature. To run the benchmarks, do:
```sh
cargo bench --features="bench"
```
## TODO ## TODO
We intend to stabilise the following before curve25519-dalek-1.0.0: We intend to stabilise the following before curve25519-dalek-1.0.0:
* Implement hashing to a point on the curve (Elligator). * Implement hashing to a point on the curve (Elligator).
* Finish Ristretto (Decaf for curve25519) implementation. * Finish Ristretto documentation.
## Contributing ## Contributing

92
build.rs Normal file
View file

@ -0,0 +1,92 @@
#![cfg_attr(feature = "nightly", feature(i128_type))]
#![allow(unused_variables)]
#![allow(non_snake_case)]
#![allow(dead_code)]
extern crate core;
extern crate subtle;
extern crate rand;
extern crate digest;
extern crate generic_array;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
// Replicate lib.rs in the build.rs, since we're effectively building the whole crate twice.
//
// This should be fixed up by refactoring our code to seperate the "minimal" parts from the rest.
//
// For instance, this shouldn't exist here at all, but it does.
#[cfg(feature = "serde")]
extern crate serde;
// Public modules
#[path="src/scalar.rs"]
mod scalar;
#[path="src/montgomery.rs"]
mod montgomery;
#[path="src/edwards.rs"]
mod edwards;
#[path="src/ristretto.rs"]
mod ristretto;
#[path="src/constants.rs"]
mod constants;
#[path="src/traits.rs"]
mod traits;
// Internal modules
#[path="src/field.rs"]
mod field;
#[path="src/curve_models/mod.rs"]
mod curve_models;
#[path="src/backend/mod.rs"]
mod backend;
use edwards::EdwardsBasepointTable;
fn main() {
// Enable the "precomputed_tables" feature in the main build stage
println!("cargo:rustc-cfg=feature=\"precomputed_tables\"\n");
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("basepoint_table.rs");
let mut f = File::create(&dest_path).unwrap();
// Generate a table of precomputed multiples of the basepoint
let table = EdwardsBasepointTable::create(&constants::ED25519_BASEPOINT_POINT);
f.write_all(format!("\n
#[cfg(feature=\"radix_51\")]
use backend::u64::field::FieldElement64;
#[cfg(not(feature=\"radix_51\"))]
use backend::u32::field::FieldElement32;
use edwards::EdwardsBasepointTable;
use curve_models::AffineNielsPoint;
/// Table containing precomputed multiples of the basepoint `B = (x,4/5)`.
///
/// The table is defined so `constants::base[i][j-1] = j*(16^2i)*B`,
/// for `0 ≤ i < 32`, `1 ≤ j < 9`.
pub const ED25519_BASEPOINT_TABLE: EdwardsBasepointTable = {:?};
\n\n", &table).as_bytes()).unwrap();
// Now generate AFFINE_ODD_MULTIPLES_OF_BASEPOINT
let B = &constants::ED25519_BASEPOINT_POINT;
let B2 = B.double();
let mut odd_multiples = [B.to_affine_niels(); 8];
for i in 0..7 {
odd_multiples[i+1] = (&B2 + &odd_multiples[i]).to_extended().to_affine_niels();
}
f.write_all(format!("\n
/// Odd multiples of the basepoint `[B, 3B, 5B, 7B, 9B, 11B, 13B, 15B]`.
pub(crate) const AFFINE_ODD_MULTIPLES_OF_BASEPOINT: [AffineNielsPoint; 8] = {:?};
\n\n", &odd_multiples).as_bytes()).unwrap();
}

4
fuzz/.gitignore vendored
View file

@ -1,4 +0,0 @@
target
corpus
artifacts

View file

@ -1,32 +0,0 @@
[package]
name = "curve25519-dalek-fuzz"
version = "0.0.1"
authors = ["Automatically generated"]
publish = false
[package.metadata]
cargo-fuzz = true
[dependencies.curve25519-dalek]
path = ".."
[features]
yolocrypto = ["curve25519-dalek/yolocrypto"]
nightly = ["curve25519-dalek/nightly"]
radix_51 = ["curve25519-dalek/radix_51"]
[dependencies.libfuzzer-sys]
git = "https://github.com/rust-fuzz/libfuzzer-sys.git"
# Prevent this from interfering with workspaces
[workspace]
members = ["."]
[[bin]]
name = "decaf"
path = "fuzz_targets/decaf.rs"
[[bin]]
name = "scalar_constructor_accepts_256bit_values"
path = "fuzz_targets/scalar_constructor_accepts_256bit_values.rs"

View file

@ -1,21 +0,0 @@
#![no_main]
#[macro_use] extern crate libfuzzer_sys;
extern crate curve25519_dalek;
use curve25519_dalek::curve::ValidityCheck;
use curve25519_dalek::decaf::DecafPoint;
use curve25519_dalek::field::FieldElement;
fuzz_target!(|data: &[u8]| {
if data.len() != 32 {
return;
}
let mut field_bytes = [0u8; 32];
for (by, data) in field_bytes.iter_mut().zip(data.iter()) {
*by = *data;
}
let fe = FieldElement::from_bytes(&field_bytes);
let p = DecafPoint::elligator_decaf_flavour(&fe);
assert!(p.0.is_valid());
p.compress();
});

View file

@ -1,36 +0,0 @@
#![no_main]
#[macro_use] extern crate libfuzzer_sys;
extern crate curve25519_dalek;
use curve25519_dalek::scalar::Scalar;
/// Check that the Scalar constructor accepts 256-bit input values and
/// behaves correctly on them.
///
/// Specifically, we take 256-bit values `a` and `b` from the fuzzer
/// input data and check that `(a mod l) * (b mod l) == (a * b) mod l`.
fuzz_target!(|data: &[u8]| {
if data.len() != 64 {
return;
}
let mut a_bytes = [0u8; 32];
let mut b_bytes = [0u8; 32];
// Set a, b to be random 256-bit integers
a_bytes.copy_from_slice(&data[ 0..32]);
b_bytes.copy_from_slice(&data[32..64]);
// Compute c = a*b (mod l)
let c1 = &Scalar(a_bytes) * &Scalar(b_bytes);
// Compute c = (a mod l) * (b mod l)
let mut tmp = [0u8; 64];
tmp[0..32].copy_from_slice(&a_bytes[..]);
let a_mod_l = Scalar::reduce(&tmp);
tmp[0..32].copy_from_slice(&b_bytes[..]);
let b_mod_l = Scalar::reduce(&tmp);
let c2 = &a_mod_l * &b_mod_l;
assert_eq!(c1, c2);
});

30
src/backend/mod.rs Normal file
View file

@ -0,0 +1,30 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! This module contains "backends" that contain different
//! implementations of common code for different architectures.
//!
//! The naming of the `u32` and `u64` modules is somewhat unfortunate,
//! since these are also the names of primitive types. Since types have
//! a different namespace than modules, this isn't a problem to the
//! compiler, but it could cause confusion.
//!
//! However, it's unlikely that the names of those modules would be
//! brought into scope directly, instead of used as
//! `backend::u32::field` or similar. Unfortunately we can't use
//! `32bit` since identifiers can't start with letters, and the backends
//! do use `u32`/`u64`, so this seems like a least-bad option.
#[cfg(not(feature="radix_51"))]
pub mod u32;
#[cfg(feature="radix_51")]
pub mod u64;

View file

@ -0,0 +1,150 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! This module contains various constants (such as curve parameters
//! and useful field elements like `sqrt(-1)`), as well as
//! lookup tables of pre-computed points.
use backend::u32::field::FieldElement32;
use backend::u32::scalar::Scalar32;
use edwards::ExtendedPoint;
/// Edwards `d` value, equal to `-121665/121666 mod p`.
pub(crate) const EDWARDS_D: FieldElement32 = FieldElement32([
56195235, 13857412, 51736253, 6949390, 114729,
24766616, 60832955, 30306712, 48412415, 21499315,
]);
/// Edwards `2*d` value, equal to `2*(-121665/121666) mod p`.
pub(crate) const EDWARDS_D2: FieldElement32 = FieldElement32([
45281625, 27714825, 36363642, 13898781, 229458,
15978800, 54557047, 27058993, 29715967, 9444199,
]);
/// `= sqrt(a*d - 1)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters.
pub(crate) const SQRT_AD_MINUS_ONE: FieldElement32 = FieldElement32([
24849947, 33400850, 43495378, 6347714, 46036536,
32887293, 41837720, 18186727, 66238516, 14525638,
]);
/// `= 1/sqrt(a-d)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters.
pub(crate) const INVSQRT_A_MINUS_D: FieldElement32 = FieldElement32([
6111466, 4156064, 39310137, 12243467, 41204824,
120896, 20826367, 26493656, 6093567, 31568420,
]);
/// Precomputed value of one of the square roots of -1 (mod p)
pub(crate) const SQRT_M1: FieldElement32 = FieldElement32([
34513072, 25610706, 9377949, 3500415, 12389472,
33281959, 41962654, 31548777, 326685, 11406482,
]);
/// In Montgomery form y² = x³+Ax²+x, Curve25519 has A=486662.
pub(crate) const MONTGOMERY_A: FieldElement32 = FieldElement32([
486662, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]);
/// `APLUS2_OVER_FOUR` is (A+2)/4. (This is used internally within the Montgomery ladder.)
pub(crate) const APLUS2_OVER_FOUR: FieldElement32 = FieldElement32([
121666, 0, 0, 0, 0, 0, 0, 0, 0, 0
]);
/// `SQRT_MINUS_APLUS2` is sqrt(-486664)
pub(crate) const SQRT_MINUS_APLUS2: FieldElement32 = FieldElement32([
54885894, 25242303, 55597453, 9067496, 51808079,
33312638, 25456129, 14121551, 54921728, 3972023,
]);
/// `L` is the order of base point, i.e. 2^252 +
/// 27742317777372353535851937790883648493
pub(crate) const L: Scalar32 = Scalar32([ 0x1cf5d3ed, 0x009318d2, 0x1de73596, 0x1df3bd45,
0x0000014d, 0x00000000, 0x00000000, 0x00000000,
0x00100000 ]);
/// `L` * `LFACTOR` = -1 (mod 2^29)
pub(crate) const LFACTOR: u32 = 0x12547e1b;
/// `R` = R % L where R = 2^261
pub(crate) const R: Scalar32 = Scalar32([ 0x114df9ed, 0x1a617303, 0x0f7c098c, 0x16793167,
0x1ffd656e, 0x1fffffff, 0x1fffffff, 0x1fffffff,
0x000fffff ]);
/// `RR` = (R^2) % L where R = 2^261
pub(crate) const RR: Scalar32 = Scalar32([ 0x0b5f9d12, 0x1e141b17, 0x158d7f3d, 0x143f3757,
0x1972d781, 0x042feb7c, 0x1ceec73d, 0x1e184d1e,
0x0005046d ]);
/// The Ed25519 basepoint has y = 4/5. This is called `_POINT` to
/// distinguish it from `_TABLE`, which should be used for scalar
/// multiplication (it's much faster).
pub const ED25519_BASEPOINT_POINT: ExtendedPoint = ExtendedPoint{
X: FieldElement32([52811034, 25909283, 16144682, 17082669, 27570973, 30858332, 40966398, 8378388, 20764389, 8758491]),
Y: FieldElement32([40265304, 26843545, 13421772, 20132659, 26843545, 6710886, 53687091, 13421772, 40265318, 26843545]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([28827043, 27438313, 39759291, 244362, 8635006, 11264893, 19351346, 13413597, 16611511, 27139452]),
};
/// The 8-torsion subgroup Ɛ[8].
///
/// In the case of Curve25519, it is cyclic; the `i`th element of the
/// array is `i*P`, where `P` is a point of order 8 generating Ɛ[8].
///
/// Thus Ɛ[4] is the points indexed by 0,2,4,6 and Ɛ[2] is the points
/// indexed by 0,4.
pub const EIGHT_TORSION: [ExtendedPoint; 8] = [
ExtendedPoint{
X: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Y: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
},
ExtendedPoint{
X: FieldElement32([21352778, 5345713, 4660180, 25206575, 24143089, 14568123, 30185756, 21306662, 33579924, 8345318]),
Y: FieldElement32([6952903, 1265500, 60246523, 7057497, 4037696, 5447722, 35427965, 15325401, 19365852, 31985330]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([41846657, 21581751, 11716001, 27684820, 48915701, 16297738, 20670665, 24995334, 3541542, 28543251])
},
ExtendedPoint{
X: FieldElement32([32595773, 7943725, 57730914, 30054016, 54719391, 272472, 25146209, 2005654, 66782178, 22147949]),
Y: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
},
ExtendedPoint{
X: FieldElement32([21352778, 5345713, 4660180, 25206575, 24143089, 14568123, 30185756, 21306662, 33579924, 8345318]),
Y: FieldElement32([60155942, 32288931, 6862340, 26496934, 63071167, 28106709, 31680898, 18229030, 47743011, 1569101]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([25262188, 11972680, 55392862, 5869611, 18193162, 17256693, 46438198, 8559097, 63567321, 5011180])
},
ExtendedPoint{
X: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Y: FieldElement32([67108844, 33554431, 67108863, 33554431, 67108863, 33554431, 67108863, 33554431, 67108863, 33554431]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
},
ExtendedPoint{
X: FieldElement32([45756067, 28208718, 62448683, 8347856, 42965774, 18986308, 36923107, 12247769, 33528939, 25209113]),
Y: FieldElement32([60155942, 32288931, 6862340, 26496934, 63071167, 28106709, 31680898, 18229030, 47743011, 1569101]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([41846657, 21581751, 11716001, 27684820, 48915701, 16297738, 20670665, 24995334, 3541542, 28543251])
},
ExtendedPoint{
X: FieldElement32([34513072, 25610706, 9377949, 3500415, 12389472, 33281959, 41962654, 31548777, 326685, 11406482]),
Y: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
},
ExtendedPoint{
X: FieldElement32([45756067, 28208718, 62448683, 8347856, 42965774, 18986308, 36923107, 12247769, 33528939, 25209113]),
Y: FieldElement32([6952903, 1265500, 60246523, 7057497, 4037696, 5447722, 35427965, 15325401, 19365852, 31985330]),
Z: FieldElement32([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
T: FieldElement32([25262188, 11972680, 55392862, 5869611, 18193162, 17256693, 46438198, 8559097, 63567321, 5011180])
},
];

520
src/backend/u32/field.rs Normal file
View file

@ -0,0 +1,520 @@
// -*- mode: rust; coding: utf-8; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! Field arithmetic modulo \\(p = 2\^{255} - 19\\), using \\(32\\)-bit
//! limbs with \\(64\\)-bit products.
//!
//! This code was originally derived from Adam Langley's Golang ed25519
//! implementation, and was then rewritten to use unsigned limbs instead
//! of signed limbs.
use core::fmt::Debug;
use core::ops::{Add, AddAssign};
use core::ops::{Sub, SubAssign};
use core::ops::{Mul, MulAssign};
use core::ops::Neg;
use subtle::ConditionallyAssignable;
/// A `FieldElement32` represents an element of the field
/// \\( \mathbb Z / (2\^{255} - 19)\\).
///
/// In the 32-bit implementation, a `FieldElement` is represented in
/// radix \\(2\^{25.5}\\) as ten `u32`s. This means that a field
/// element \\(x\\) is represented as
/// $$
/// x = \sum\_{i=0}\^9 x\_i 2\^{\lceil i \frac {51} 2 \rceil}
/// = x\_0 + x\_1 2\^{26} + x\_2 2\^{51} + x\_3 2\^{77} + \cdots + x\_9 2\^{230};
/// $$
/// the coefficients are alternately bounded by \\(2\^{25}\\) and
/// \\(2\^{26}\\). The limbs are allowed to grow between reductions up
/// to \\(2\^{25+b}\\) or \\(2\^{26+b}\\), where \\(b = 1.75\\).
///
/// # Note
///
/// The `curve25519_dalek::field` module provides a type alias
/// `curve25519_dalek::field::FieldElement` to either `FieldElement64`
/// or `FieldElement32`.
///
/// The backend-specific type `FieldElement32` should not be used
/// outside of the `curve25519_dalek::field` module.
#[derive(Copy, Clone)]
pub struct FieldElement32(pub (crate) [u32; 10]);
impl Debug for FieldElement32 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "FieldElement32({:?})", &self.0[..])
}
}
impl<'b> AddAssign<&'b FieldElement32> for FieldElement32 {
fn add_assign(&mut self, _rhs: &'b FieldElement32) {
for i in 0..10 {
self.0[i] += _rhs.0[i];
}
}
}
impl<'a, 'b> Add<&'b FieldElement32> for &'a FieldElement32 {
type Output = FieldElement32;
fn add(self, _rhs: &'b FieldElement32) -> FieldElement32 {
let mut output = *self;
output += _rhs;
output
}
}
impl<'b> SubAssign<&'b FieldElement32> for FieldElement32 {
fn sub_assign(&mut self, _rhs: &'b FieldElement32) {
// See comment in FieldElement64::Sub
//
// Compute a - b as ((a + 2^4 * p) - b) to avoid underflow.
let b = &_rhs.0;
self.0 = FieldElement32::reduce([
((self.0[0] + (0x3ffffed << 4)) - b[0]) as u64,
((self.0[1] + (0x1ffffff << 4)) - b[1]) as u64,
((self.0[2] + (0x3ffffff << 4)) - b[2]) as u64,
((self.0[3] + (0x1ffffff << 4)) - b[3]) as u64,
((self.0[4] + (0x3ffffff << 4)) - b[4]) as u64,
((self.0[5] + (0x1ffffff << 4)) - b[5]) as u64,
((self.0[6] + (0x3ffffff << 4)) - b[6]) as u64,
((self.0[7] + (0x1ffffff << 4)) - b[7]) as u64,
((self.0[8] + (0x3ffffff << 4)) - b[8]) as u64,
((self.0[9] + (0x1ffffff << 4)) - b[9]) as u64,
]).0;
}
}
impl<'a, 'b> Sub<&'b FieldElement32> for &'a FieldElement32 {
type Output = FieldElement32;
fn sub(self, _rhs: &'b FieldElement32) -> FieldElement32 {
let mut output = *self;
output -= _rhs;
output
}
}
impl<'b> MulAssign<&'b FieldElement32> for FieldElement32 {
fn mul_assign(&mut self, _rhs: &'b FieldElement32) {
let result = (self as &FieldElement32) * _rhs;
self.0 = result.0;
}
}
impl<'a, 'b> Mul<&'b FieldElement32> for &'a FieldElement32 {
type Output = FieldElement32;
fn mul(self, _rhs: &'b FieldElement32) -> FieldElement32 {
/// Helper function to multiply two 32-bit integers with 64 bits
/// of output.
#[inline(always)]
fn m(x: u32, y: u32) -> u64 { (x as u64) * (y as u64) }
// Alias self, _rhs for more readable formulas
let x: &[u32;10] = &self.0; let y: &[u32;10] = &_rhs.0;
// We assume that the input limbs x[i], y[i] are bounded by:
//
// x[i], y[i] < 2^(26 + b) if i even
// x[i], y[i] < 2^(25 + b) if i odd
//
// where b is a (real) parameter representing the excess bits of
// the limbs. We track the bitsizes of all variables through
// the computation and solve at the end for the allowable
// headroom bitsize b (which determines how many additions we
// can perform between reductions or multiplications).
let y1_19 = 19 * y[1]; // This fits in a u32
let y2_19 = 19 * y[2]; // iff 26 + b + lg(19) < 32
let y3_19 = 19 * y[3]; // if b < 32 - 26 - 4.248 = 1.752
let y4_19 = 19 * y[4];
let y5_19 = 19 * y[5]; // below, b<2.5: this is a bottleneck,
let y6_19 = 19 * y[6]; // could be avoided by promoting to
let y7_19 = 19 * y[7]; // u64 here instead of in m()
let y8_19 = 19 * y[8];
let y9_19 = 19 * y[9];
// What happens when we multiply x[i] with y[j] and place the
// result into the (i+j)-th limb?
//
// x[i] represents the value x[i]*2^ceil(i*51/2)
// y[j] represents the value y[j]*2^ceil(j*51/2)
// z[i+j] represents the value z[i+j]*2^ceil((i+j)*51/2)
// x[i]*y[j] represents the value x[i]*y[i]*2^(ceil(i*51/2)+ceil(j*51/2))
//
// Since the radix is already accounted for, the result placed
// into the (i+j)-th limb should be
//
// x[i]*y[i]*2^(ceil(i*51/2)+ceil(j*51/2) - ceil((i+j)*51/2)).
//
// The value of ceil(i*51/2)+ceil(j*51/2) - ceil((i+j)*51/2) is
// 1 when both i and j are odd, and 0 otherwise. So we add
//
// x[i]*y[j] if either i or j is even
// 2*x[i]*y[j] if i and j are both odd
//
// by using precomputed multiples of x[i] for odd i:
let x1_2 = 2 * x[1]; // This fits in a u32 iff 25 + b + 1 < 32
let x3_2 = 2 * x[3]; // iff b < 6
let x5_2 = 2 * x[5];
let x7_2 = 2 * x[7];
let x9_2 = 2 * x[9];
let z0 = m(x[0],y[0]) + m(x1_2,y9_19) + m(x[2],y8_19) + m(x3_2,y7_19) + m(x[4],y6_19) + m(x5_2,y5_19) + m(x[6],y4_19) + m(x7_2,y3_19) + m(x[8],y2_19) + m(x9_2,y1_19);
let z1 = m(x[0],y[1]) + m(x[1],y[0]) + m(x[2],y9_19) + m(x[3],y8_19) + m(x[4],y7_19) + m(x[5],y6_19) + m(x[6],y5_19) + m(x[7],y4_19) + m(x[8],y3_19) + m(x[9],y2_19);
let z2 = m(x[0],y[2]) + m(x1_2,y[1]) + m(x[2],y[0]) + m(x3_2,y9_19) + m(x[4],y8_19) + m(x5_2,y7_19) + m(x[6],y6_19) + m(x7_2,y5_19) + m(x[8],y4_19) + m(x9_2,y3_19);
let z3 = m(x[0],y[3]) + m(x[1],y[2]) + m(x[2],y[1]) + m(x[3],y[0]) + m(x[4],y9_19) + m(x[5],y8_19) + m(x[6],y7_19) + m(x[7],y6_19) + m(x[8],y5_19) + m(x[9],y4_19);
let z4 = m(x[0],y[4]) + m(x1_2,y[3]) + m(x[2],y[2]) + m(x3_2,y[1]) + m(x[4],y[0]) + m(x5_2,y9_19) + m(x[6],y8_19) + m(x7_2,y7_19) + m(x[8],y6_19) + m(x9_2,y5_19);
let z5 = m(x[0],y[5]) + m(x[1],y[4]) + m(x[2],y[3]) + m(x[3],y[2]) + m(x[4],y[1]) + m(x[5],y[0]) + m(x[6],y9_19) + m(x[7],y8_19) + m(x[8],y7_19) + m(x[9],y6_19);
let z6 = m(x[0],y[6]) + m(x1_2,y[5]) + m(x[2],y[4]) + m(x3_2,y[3]) + m(x[4],y[2]) + m(x5_2,y[1]) + m(x[6],y[0]) + m(x7_2,y9_19) + m(x[8],y8_19) + m(x9_2,y7_19);
let z7 = m(x[0],y[7]) + m(x[1],y[6]) + m(x[2],y[5]) + m(x[3],y[4]) + m(x[4],y[3]) + m(x[5],y[2]) + m(x[6],y[1]) + m(x[7],y[0]) + m(x[8],y9_19) + m(x[9],y8_19);
let z8 = m(x[0],y[8]) + m(x1_2,y[7]) + m(x[2],y[6]) + m(x3_2,y[5]) + m(x[4],y[4]) + m(x5_2,y[3]) + m(x[6],y[2]) + m(x7_2,y[1]) + m(x[8],y[0]) + m(x9_2,y9_19);
let z9 = m(x[0],y[9]) + m(x[1],y[8]) + m(x[2],y[7]) + m(x[3],y[6]) + m(x[4],y[5]) + m(x[5],y[4]) + m(x[6],y[3]) + m(x[7],y[2]) + m(x[8],y[1]) + m(x[9],y[0]);
// How big is the contribution to z[i+j] from x[i], y[j]?
//
// Using the bounds above, we get:
//
// i even, j even: x[i]*y[j] < 2^(26+b)*2^(26+b) = 2*2^(51+2*b)
// i odd, j even: x[i]*y[j] < 2^(25+b)*2^(26+b) = 1*2^(51+2*b)
// i even, j odd: x[i]*y[j] < 2^(26+b)*2^(25+b) = 1*2^(51+2*b)
// i odd, j odd: 2*x[i]*y[j] < 2*2^(25+b)*2^(25+b) = 1*2^(51+2*b)
//
// We perform inline reduction mod p by replacing 2^255 by 19
// (since 2^255 - 19 = 0 mod p). This adds a factor of 19, so
// we get the bounds (z0 is the biggest one, but calculated for
// posterity here in case finer estimation is needed later):
//
// z0 < ( 2 + 1*19 + 2*19 + 1*19 + 2*19 + 1*19 + 2*19 + 1*19 + 2*19 + 1*19 )*2^(51 + 2b) = 249*2^(51 + 2*b)
// z1 < ( 1 + 1 + 1*19 + 1*19 + 1*19 + 1*19 + 1*19 + 1*19 + 1*19 + 1*19 )*2^(51 + 2b) = 154*2^(51 + 2*b)
// z2 < ( 2 + 1 + 2 + 1*19 + 2*19 + 1*19 + 2*19 + 1*19 + 2*19 + 1*19 )*2^(51 + 2b) = 195*2^(51 + 2*b)
// z3 < ( 1 + 1 + 1 + 1 + 1*19 + 1*19 + 1*19 + 1*19 + 1*19 + 1*19 )*2^(51 + 2b) = 118*2^(51 + 2*b)
// z4 < ( 2 + 1 + 2 + 1 + 2 + 1*19 + 2*19 + 1*19 + 2*19 + 1*19 )*2^(51 + 2b) = 141*2^(51 + 2*b)
// z5 < ( 1 + 1 + 1 + 1 + 1 + 1 + 1*19 + 1*19 + 1*19 + 1*19 )*2^(51 + 2b) = 82*2^(51 + 2*b)
// z6 < ( 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1*19 + 2*19 + 1*19 )*2^(51 + 2b) = 87*2^(51 + 2*b)
// z7 < ( 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1*19 + 1*19 )*2^(51 + 2b) = 46*2^(51 + 2*b)
// z6 < ( 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1*19 )*2^(51 + 2b) = 33*2^(51 + 2*b)
// z7 < ( 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 )*2^(51 + 2b) = 10*2^(51 + 2*b)
//
// So z[0] fits into a u64 if 51 + 2*b + lg(249) < 64
// if b < 2.5.
FieldElement32::reduce([z0, z1, z2, z3, z4, z5, z6, z7, z8, z9])
}
}
impl<'a> Neg for &'a FieldElement32 {
type Output = FieldElement32;
fn neg(self) -> FieldElement32 {
let mut output = *self;
output.negate();
output
}
}
impl ConditionallyAssignable for FieldElement32 {
fn conditional_assign(&mut self, f: &FieldElement32, choice: u8) {
let mask = (-(choice as i32)) as u32;
for i in 0..10 {
self.0[i] ^= mask & (self.0[i] ^ f.0[i]);
}
}
}
impl FieldElement32 {
/// Invert the sign of this field element
pub fn negate(&mut self) {
// Compute -b as ((2^4 * p) - b) to avoid underflow.
let neg = FieldElement32::reduce([
((0x3ffffed << 4) - self.0[0]) as u64,
((0x1ffffff << 4) - self.0[1]) as u64,
((0x3ffffff << 4) - self.0[2]) as u64,
((0x1ffffff << 4) - self.0[3]) as u64,
((0x3ffffff << 4) - self.0[4]) as u64,
((0x1ffffff << 4) - self.0[5]) as u64,
((0x3ffffff << 4) - self.0[6]) as u64,
((0x1ffffff << 4) - self.0[7]) as u64,
((0x3ffffff << 4) - self.0[8]) as u64,
((0x1ffffff << 4) - self.0[9]) as u64,
]);
self.0 = neg.0;
}
/// Construct zero.
pub fn zero() -> FieldElement32 {
FieldElement32([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ])
}
/// Construct one.
pub fn one() -> FieldElement32 {
FieldElement32([ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ])
}
/// Construct -1.
pub fn minus_one() -> FieldElement32 {
FieldElement32([
0x3ffffec, 0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff,
0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff, 0x1ffffff,
])
}
/// Given unreduced coefficients `z[0], ..., z[9]` of any size,
/// carry and reduce them mod p to obtain a `FieldElement32`
/// whose coefficients have excess `b < 0.007`.
///
/// In other words, each coefficient of the result is bounded by
/// either `2^(25 + 0.007)` or `2^(26 + 0.007)`, as appropriate.
fn reduce(mut z: [u64; 10]) -> FieldElement32 {
const LOW_25_BITS: u64 = (1 << 25) - 1;
const LOW_26_BITS: u64 = (1 << 26) - 1;
/// Carry the value from limb i = 0..8 to limb i+1
#[inline(always)]
fn carry(z: &mut [u64; 10], i: usize) {
debug_assert!(i < 9);
if i % 2 == 0 {
// Even limbs have 26 bits
z[i+1] += z[i] >> 26;
z[i] &= LOW_26_BITS;
} else {
// Odd limbs have 25 bits
z[i+1] += z[i] >> 25;
z[i] &= LOW_25_BITS;
}
}
// Perform two halves of the carry chain in parallel.
carry(&mut z, 0); carry(&mut z, 4);
carry(&mut z, 1); carry(&mut z, 5);
carry(&mut z, 2); carry(&mut z, 6);
carry(&mut z, 3); carry(&mut z, 7);
// Since z[3] < 2^64, c < 2^(64-25) = 2^39,
// so z[4] < 2^26 + 2^39 < 2^39.0002
carry(&mut z, 4); carry(&mut z, 8);
// Now z[4] < 2^26
// and z[5] < 2^25 + 2^13.0002 < 2^25.0004 (good enough)
// Last carry has a multiplication by 19:
z[0] += 19*(z[9] >> 25);
z[9] &= LOW_25_BITS;
// Since z[9] < 2^64, c < 2^(64-25) = 2^39,
// so z[0] + 19*c < 2^26 + 2^43.248 < 2^43.249.
carry(&mut z, 0);
// Now z[1] < 2^25 - 2^(43.249 - 26)
// < 2^25.007 (good enough)
// and we're done.
FieldElement32([
z[0] as u32, z[1] as u32, z[2] as u32, z[3] as u32, z[4] as u32,
z[5] as u32, z[6] as u32, z[7] as u32, z[8] as u32, z[9] as u32,
])
}
/// Load a `FieldElement64` from the low 255 bits of a 256-bit
/// input.
///
/// # Warning
///
/// This function does not check that the input used the canonical
/// representative. It masks the high bit, but it will happily
/// decode 2^255 - 18 to 1. Applications that require a canonical
/// encoding of every field element should decode, re-encode to
/// the canonical encoding, and check that the input was
/// canonical.
pub fn from_bytes(data: &[u8; 32]) -> FieldElement32 { //FeFromBytes
#[inline]
fn load3(b: &[u8]) -> u64 {
(b[0] as u64) | ((b[1] as u64) << 8) | ((b[2] as u64) << 16)
}
#[inline]
fn load4(b: &[u8]) -> u64 {
(b[0] as u64) | ((b[1] as u64) << 8) | ((b[2] as u64) << 16) | ((b[3] as u64) << 24)
}
let mut h = [0u64;10];
const LOW_23_BITS: u64 = (1 << 23) - 1;
h[0] = load4(&data[ 0..]);
h[1] = load3(&data[ 4..]) << 6;
h[2] = load3(&data[ 7..]) << 5;
h[3] = load3(&data[10..]) << 3;
h[4] = load3(&data[13..]) << 2;
h[5] = load4(&data[16..]);
h[6] = load3(&data[20..]) << 7;
h[7] = load3(&data[23..]) << 5;
h[8] = load3(&data[26..]) << 4;
h[9] = (load3(&data[29..]) & LOW_23_BITS) << 2;
FieldElement32::reduce(h)
}
/// Serialize this `FieldElement64` to a 32-byte array. The
/// encoding is canonical.
pub fn to_bytes(&self) -> [u8; 32] {
let inp = &self.0;
// Reduce the value represented by `in` to the range [0,2*p)
let mut h: [u32; 10] = FieldElement32::reduce([
// XXX this cast is annoying
inp[0] as u64, inp[1] as u64, inp[2] as u64, inp[3] as u64, inp[4] as u64,
inp[5] as u64, inp[6] as u64, inp[7] as u64, inp[8] as u64, inp[9] as u64,
]).0;
// Let h be the value to encode.
//
// Write h = pq + r with 0 <= r < p. We want to compute r = h mod p.
//
// Since h < 2*p, q = 0 or 1, with q = 0 when h < p and q = 1 when h >= p.
//
// Notice that h >= p <==> h + 19 >= p + 19 <==> h + 19 >= 2^255.
// Therefore q can be computed as the carry bit of h + 19.
let mut q: u32 = (h[0] + 19) >> 26;
q = (h[1] + q) >> 25;
q = (h[2] + q) >> 26;
q = (h[3] + q) >> 25;
q = (h[4] + q) >> 26;
q = (h[5] + q) >> 25;
q = (h[6] + q) >> 26;
q = (h[7] + q) >> 25;
q = (h[8] + q) >> 26;
q = (h[9] + q) >> 25;
debug_assert!( q == 0 || q == 1 );
// Now we can compute r as r = h - pq = r - (2^255-19)q = r + 19q - 2^255q
const LOW_25_BITS: u32 = (1 << 25) - 1;
const LOW_26_BITS: u32 = (1 << 26) - 1;
h[0] += 19*q;
// Now carry the result to compute r + 19q...
h[1] += h[0] >> 26;
h[0] = h[0] & LOW_26_BITS;
h[2] += h[1] >> 25;
h[1] = h[1] & LOW_25_BITS;
h[3] += h[2] >> 26;
h[2] = h[2] & LOW_26_BITS;
h[4] += h[3] >> 25;
h[3] = h[3] & LOW_25_BITS;
h[5] += h[4] >> 26;
h[4] = h[4] & LOW_26_BITS;
h[6] += h[5] >> 25;
h[5] = h[5] & LOW_25_BITS;
h[7] += h[6] >> 26;
h[6] = h[6] & LOW_26_BITS;
h[8] += h[7] >> 25;
h[7] = h[7] & LOW_25_BITS;
h[9] += h[8] >> 26;
h[8] = h[8] & LOW_26_BITS;
// ... but instead of carrying the value
// (h[9] >> 25) = q*2^255 into another limb,
// discard it, subtracting the value from h.
debug_assert!( (h[9] >> 25) == 0 || (h[9] >> 25) == 1);
h[9] = h[9] & LOW_25_BITS;
let mut s = [0u8; 32];
s[0] = (h[0] >> 0) as u8;
s[1] = (h[0] >> 8) as u8;
s[2] = (h[0] >> 16) as u8;
s[3] = ((h[0] >> 24) | (h[1] << 2)) as u8;
s[4] = (h[1] >> 6) as u8;
s[5] = (h[1] >> 14) as u8;
s[6] = ((h[1] >> 22) | (h[2] << 3)) as u8;
s[7] = (h[2] >> 5) as u8;
s[8] = (h[2] >> 13) as u8;
s[9] = ((h[2] >> 21) | (h[3] << 5)) as u8;
s[10] = (h[3] >> 3) as u8;
s[11] = (h[3] >> 11) as u8;
s[12] = ((h[3] >> 19) | (h[4] << 6)) as u8;
s[13] = (h[4] >> 2) as u8;
s[14] = (h[4] >> 10) as u8;
s[15] = (h[4] >> 18) as u8;
s[16] = (h[5] >> 0) as u8;
s[17] = (h[5] >> 8) as u8;
s[18] = (h[5] >> 16) as u8;
s[19] = ((h[5] >> 24) | (h[6] << 1)) as u8;
s[20] = (h[6] >> 7) as u8;
s[21] = (h[6] >> 15) as u8;
s[22] = ((h[6] >> 23) | (h[7] << 3)) as u8;
s[23] = (h[7] >> 5) as u8;
s[24] = (h[7] >> 13) as u8;
s[25] = ((h[7] >> 21) | (h[8] << 4)) as u8;
s[26] = (h[8] >> 4) as u8;
s[27] = (h[8] >> 12) as u8;
s[28] = ((h[8] >> 20) | (h[9] << 6)) as u8;
s[29] = (h[9] >> 2) as u8;
s[30] = (h[9] >> 10) as u8;
s[31] = (h[9] >> 18) as u8;
// Check that high bit is cleared
debug_assert!((s[31] & 0b1000_0000u8) == 0u8);
s
}
fn square_inner(&self) -> [u64; 10] {
// Optimized version of multiplication for the case of squaring.
// Pre- and post- conditions identical to multiplication function.
let x = &self.0;
let x0_2 = 2 * x[0];
let x1_2 = 2 * x[1];
let x2_2 = 2 * x[2];
let x3_2 = 2 * x[3];
let x4_2 = 2 * x[4];
let x5_2 = 2 * x[5];
let x6_2 = 2 * x[6];
let x7_2 = 2 * x[7];
let x5_19 = 19 * x[5];
let x6_19 = 19 * x[6];
let x7_19 = 19 * x[7];
let x8_19 = 19 * x[8];
let x9_19 = 19 * x[9];
/// Helper function to multiply two 32-bit integers with 64 bits
/// of output.
#[inline(always)]
fn m(x: u32, y: u32) -> u64 { (x as u64) * (y as u64) }
// This block is rearranged so that instead of doing a 32-bit multiplication by 38, we do a
// 64-bit multiplication by 2 on the results. This is because lg(38) is too big: we would
// have less than 1 bit of headroom left, which is too little.
let mut z = [0u64;10];
z[0] = m(x[0],x[0]) + m(x2_2,x8_19) + m(x4_2,x6_19) + (m(x1_2,x9_19) + m(x3_2,x7_19) + m(x[5],x5_19))*2;
z[1] = m(x0_2,x[1]) + m(x3_2,x8_19) + m(x5_2,x6_19) + (m(x[2],x9_19) + m(x[4],x7_19))*2;
z[2] = m(x0_2,x[2]) + m(x1_2,x[1]) + m(x4_2,x8_19) + m(x[6],x6_19) + (m(x3_2,x9_19) + m(x5_2,x7_19))*2;
z[3] = m(x0_2,x[3]) + m(x1_2,x[2]) + m(x5_2,x8_19) + (m(x[4],x9_19) + m(x[6],x7_19))*2;
z[4] = m(x0_2,x[4]) + m(x1_2,x3_2) + m(x[2],x[2]) + m(x6_2,x8_19) + (m(x5_2,x9_19) + m(x[7],x7_19))*2;
z[5] = m(x0_2,x[5]) + m(x1_2,x[4]) + m(x2_2,x[3]) + m(x7_2,x8_19) + m(x[6],x9_19)*2;
z[6] = m(x0_2,x[6]) + m(x1_2,x5_2) + m(x2_2,x[4]) + m(x3_2,x[3]) + m(x[8],x8_19) + m(x7_2,x9_19)*2;
z[7] = m(x0_2,x[7]) + m(x1_2,x[6]) + m(x2_2,x[5]) + m(x3_2,x[4]) + m(x[8],x9_19)*2;
z[8] = m(x0_2,x[8]) + m(x1_2,x7_2) + m(x2_2,x[6]) + m(x3_2,x5_2) + m(x[4],x[4]) + m(x[9],x9_19)*2;
z[9] = m(x0_2,x[9]) + m(x1_2,x[8]) + m(x2_2,x[7]) + m(x3_2,x[6]) + m(x4_2,x[5]) ;
z
}
/// Compute `self^2`.
pub fn square(&self) -> FieldElement32 {
FieldElement32::reduce(self.square_inner())
}
/// Compute `2*self^2`.
pub fn square2(&self) -> FieldElement32 {
let mut coeffs = self.square_inner();
for i in 0..self.0.len() {
coeffs[i] += coeffs[i];
}
FieldElement32::reduce(coeffs)
}
}

21
src/backend/u32/mod.rs Normal file
View file

@ -0,0 +1,21 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! The `u32` backend uses `u32`s and a `(u32, u32) -> u64` multiplier.
//!
//! This code is intended to be portable, but it requires that
//! multiplication of two \\(32\\)-bit values to a \\(64\\)-bit result
//! is constant-time on the target platform.
pub mod field;
pub mod scalar;
pub mod constants;

View file

@ -0,0 +1,130 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! This module contains backend-specific constant values, such as the 64-bit limbs of curve constants.
use backend::u64::field::FieldElement64;
use backend::u64::scalar::Scalar64;
use edwards::ExtendedPoint;
/// Edwards `d` value, equal to `-121665/121666 mod p`.
pub(crate) const EDWARDS_D: FieldElement64 = FieldElement64([929955233495203, 466365720129213, 1662059464998953, 2033849074728123, 1442794654840575]);
/// Edwards `2*d` value, equal to `2*(-121665/121666) mod p`.
pub(crate) const EDWARDS_D2: FieldElement64 = FieldElement64([1859910466990425, 932731440258426, 1072319116312658, 1815898335770999, 633789495995903]);
/// `= sqrt(a*d - 1)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters.
pub(crate) const SQRT_AD_MINUS_ONE: FieldElement64 = FieldElement64([
2241493124984347, 425987919032274, 2207028919301688, 1220490630685848, 974799131293748
]);
/// `= 1/sqrt(a-d)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters.
pub(crate) const INVSQRT_A_MINUS_D: FieldElement64 = FieldElement64([
278908739862762, 821645201101625, 8113234426968, 1777959178193151, 2118520810568447
]);
/// Precomputed value of one of the square roots of -1 (mod p)
pub(crate) const SQRT_M1: FieldElement64 = FieldElement64([1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133]);
/// In Montgomery form y² = x³+Ax²+x, Curve25519 has A=486662.
pub(crate) const MONTGOMERY_A: FieldElement64 = FieldElement64([486662, 0, 0, 0, 0]);
/// `APLUS2_OVER_FOUR` is (A+2)/4. (This is used internally within the Montgomery ladder.)
pub(crate) const APLUS2_OVER_FOUR: FieldElement64 = FieldElement64([121666, 0, 0, 0, 0]);
/// `SQRT_MINUS_APLUS2` is sqrt(-486664)
pub(crate) const SQRT_MINUS_APLUS2: FieldElement64 = FieldElement64([1693982333959686, 608509411481997, 2235573344831311, 947681270984193, 266558006233600]);
/// `L` is the order of base point, i.e. 2^252 + 27742317777372353535851937790883648493
pub(crate) const L: Scalar64 = Scalar64([ 0x0002631a5cf5d3ed, 0x000dea2f79cd6581, 0x000000000014def9, 0x0000000000000000, 0x0000100000000000 ]);
/// `L` * `LFACTOR` = -1 (mod 2^51)
pub(crate) const LFACTOR: u64 = 0x51da312547e1b;
/// `R` = R % L where R = 2^260
pub(crate) const R: Scalar64 = Scalar64([ 0x000f48bd6721e6ed, 0x0003bab5ac67e45a, 0x000fffffeb35e51b, 0x000fffffffffffff, 0x00000fffffffffff ]);
/// `RR` = (R^2) % L where R = 2^260
pub(crate) const RR: Scalar64 = Scalar64([ 0x0009d265e952d13b, 0x000d63c715bea69f, 0x0005be65cb687604, 0x0003dceec73d217f, 0x000009411b7c309a ]);
/// The Ed25519 basepoint has y = 4/5. This is called `_POINT` to
/// distinguish it from `_TABLE`, which should be used for scalar
/// multiplication (it's much faster).
pub const ED25519_BASEPOINT_POINT: ExtendedPoint = ExtendedPoint{
X: FieldElement64([1738742601995546, 1146398526822698, 2070867633025821, 562264141797630, 587772402128613]),
Y: FieldElement64([1801439850948184, 1351079888211148, 450359962737049, 900719925474099, 1801439850948198]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([1841354044333475, 16398895984059, 755974180946558, 900171276175154, 1821297809914039]),
};
/// The 8-torsion subgroup Ɛ[8].
///
/// In the case of Curve25519, it is cyclic; the `i`th element of the
/// array is `i*P`, where `P` is a point of order 8 generating Ɛ[8].
///
/// Thus Ɛ[4] is the points indexed by 0,2,4,6 and Ɛ[2] is the points
/// indexed by 0,4.
pub const EIGHT_TORSION: [ExtendedPoint; 8] = [
ExtendedPoint {
X: FieldElement64([0, 0, 0, 0, 0]),
Y: FieldElement64([1, 0, 0, 0, 0]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([0, 0, 0, 0, 0]),
}
,
ExtendedPoint {
X: FieldElement64([358744748052810, 1691584618240980, 977650209285361, 1429865912637724, 560044844278676]),
Y: FieldElement64([84926274344903, 473620666599931, 365590438845504, 1028470286882429, 2146499180330972]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([1448326834587521, 1857896831960481, 1093722731865333, 1677408490711241, 1915505153018406]),
}
,
ExtendedPoint {
X: FieldElement64([533094393274173, 2016890930128738, 18285341111199, 134597186663265, 1486323764102114]),
Y: FieldElement64([0, 0, 0, 0, 0]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([0, 0, 0, 0, 0]),
}
,
ExtendedPoint {
X: FieldElement64([358744748052810, 1691584618240980, 977650209285361, 1429865912637724, 560044844278676]),
Y: FieldElement64([2166873539340326, 1778179147085316, 1886209374839743, 1223329526802818, 105300633354275]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([803472979097708, 393902981724766, 1158077081819914, 574391322974006, 336294660666841]),
}
,
ExtendedPoint {
X: FieldElement64([0, 0, 0, 0, 0]),
Y: FieldElement64([2251799813685228, 2251799813685247, 2251799813685247, 2251799813685247, 2251799813685247]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([0, 0, 0, 0, 0]),
}
,
ExtendedPoint {
X: FieldElement64([1893055065632419, 560215195444267, 1274149604399886, 821933901047523, 1691754969406571]),
Y: FieldElement64([2166873539340326, 1778179147085316, 1886209374839743, 1223329526802818, 105300633354275]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([1448326834587521, 1857896831960481, 1093722731865333, 1677408490711241, 1915505153018406]),
}
,
ExtendedPoint {
X: FieldElement64([1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133]),
Y: FieldElement64([0, 0, 0, 0, 0]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([0, 0, 0, 0, 0]),
}
,
ExtendedPoint {
X: FieldElement64([1893055065632419, 560215195444267, 1274149604399886, 821933901047523, 1691754969406571]),
Y: FieldElement64([84926274344903, 473620666599931, 365590438845504, 1028470286882429, 2146499180330972]),
Z: FieldElement64([1, 0, 0, 0, 0]),
T: FieldElement64([803472979097708, 393902981724766, 1158077081819914, 574391322974006, 336294660666841]),
}
];

View file

@ -8,14 +8,8 @@
// - Isis Agora Lovecruft <isis@patternsinthevoid.net> // - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca> // - Henry de Valence <hdevalence@hdevalence.ca>
//! Field arithmetic for ℤ/(2²⁵⁵-19), using 64-bit arithmetic wuth //! Field arithmetic modulo \\(p = 2\^{255} - 19\\), using \\(64\\)-bit
//! 128-bit products. //! limbs with \\(128\\)-bit products.
//!
//! On x86_64, the multiplications lower to `MUL` instructions taking
//! 64-bit inputs and producing 128-bit outputs. On other platforms,
//! this implementation is not recommended. On Haswell and newer, the
//! BMI2 instruction set provides `MULX` and friends, which gives even
//! better performance.
use core::fmt::Debug; use core::fmt::Debug;
use core::ops::{Add, AddAssign}; use core::ops::{Add, AddAssign};
@ -25,37 +19,27 @@ use core::ops::Neg;
use subtle::ConditionallyAssignable; use subtle::ConditionallyAssignable;
use utils::load8; /// A `FieldElement64` represents an element of the field
/// \\( \mathbb Z / (2\^{255} - 19)\\).
/// In the 64-bit implementation, field elements are represented in
/// radix 2^51 as five `u64`s.
pub type Limb = u64;
/// A `FieldElement64` represents an element of the field GF(2^255 - 19).
/// ///
/// In the 64-bit implementation, a `FieldElement` is represented in /// In the 64-bit implementation, a `FieldElement` is represented in
/// radix 2^51 as five `u64`s; the coefficients are allowed to grow up /// radix \\(2\^{51}\\) as five `u64`s; the coefficients are allowed to
/// to 2^54 between reductions mod `p`. /// grow up to \\(2\^{54}\\) between reductions modulo \\(p\\).
/// ///
/// # Warning /// # Note
/// ///
/// You almost certainly do not want to use `FieldElement64` directly. Consider /// The `curve25519_dalek::field` module provides a type alias
/// using `curve25519_dalek::field::FieldElement`, which will automatically /// `curve25519_dalek::field::FieldElement` to either `FieldElement64`
/// select between `FieldElement32` and `FieldElement64` depending on whether /// or `FieldElement32`.
/// curve25519-dalek was compiled with `--features="nightly"`.
/// ///
/// This implementation, `FieldElement64`, is intended for x64_64 platforms, /// The backend-specific type `FieldElement64` should not be used
/// which have the `MUL` instructions taking 64-bit inputs and producing 128-bit /// outside of the `curve25519_dalek::field` module.
/// outputs. On other platforms, this implementation is not recommended. On
/// Haswell and newer, the BMI2 instruction set provides `MULX` and friends,
/// which gives even better performance. This implementation requires Rust's
/// `u128`, which is not yet stable.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct FieldElement64(pub (crate) [u64; 5]); pub struct FieldElement64(pub (crate) [u64; 5]);
impl Debug for FieldElement64 { impl Debug for FieldElement64 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "FieldElement64: {:?}", &self.0[..]) write!(f, "FieldElement64({:?})", &self.0[..])
} }
} }
@ -247,6 +231,17 @@ impl FieldElement64 {
/// canonical. /// canonical.
/// ///
pub fn from_bytes(bytes: &[u8; 32]) -> FieldElement64 { pub fn from_bytes(bytes: &[u8; 32]) -> FieldElement64 {
let load8 = |input: &[u8]| -> u64 {
(input[0] as u64)
| ((input[1] as u64) << 8)
| ((input[2] as u64) << 16)
| ((input[3] as u64) << 24)
| ((input[4] as u64) << 32)
| ((input[5] as u64) << 40)
| ((input[6] as u64) << 48)
| ((input[7] as u64) << 56)
};
let low_51_bit_mask = (1u64 << 51) - 1; let low_51_bit_mask = (1u64 << 51) - 1;
FieldElement64( FieldElement64(
// load bits [ 0, 64), no shift // load bits [ 0, 64), no shift

26
src/backend/u64/mod.rs Normal file
View file

@ -0,0 +1,26 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! The `u64` backend uses `u64`s and a `(u64, u64) -> u128` multiplier.
//!
//! On x86_64, the idiom `(x as u128) * (y as u128)` lowers to `MUL`
//! instructions taking 64-bit inputs and producing 128-bit outputs. On
//! other platforms, this implementation is not recommended.
//!
//! On Haswell and newer, the BMI2 extension provides `MULX`, and on
//! Broadwell and newer, the ADX extension provides `ADCX` and `ADOX`
//! (allowing the CPU to compute two carry chains in parallel). These
//! will be used if available.
pub mod field;
pub mod scalar;
pub mod constants;

View file

@ -1,19 +1,23 @@
//! Arithmetic mod 2^252 + 27742317777372353535851937790883648493 //! Arithmetic mod \\(2\^{252} + 27742317777372353535851937790883648493\\)
//! with 5 52-bit unsigned limbs. 51-bit limbs would cover the //! with five \\(52\\)-bit unsigned limbs.
//! desired bit range (253 bits), but isn't large enough to reduce
//! a 512 bit number with Montgomery multiplication, so 52 bits is
//! used instead
//! //!
//! To see that this is safe for intermediate results, note that //! \\(51\\)-bit limbs would cover the desired bit range (\\(253\\)
//! the largest limb in a 5 by 5 product of 52-bit limbs will be //! bits), but isn't large enough to reduce a \\(512\\)-bit number with
//! Montgomery multiplication, so \\(52\\) bits is used instead. To see
//! that this is safe for intermediate results, note that the largest
//! limb in a \\(5\times 5\\) product of \\(52\\)-bit limbs will be
//!
//! ```text
//! (0xfffffffffffff^2) * 5 = 0x4ffffffffffff60000000000005 (107 bits). //! (0xfffffffffffff^2) * 5 = 0x4ffffffffffff60000000000005 (107 bits).
//! ```
use core::fmt::Debug; use core::fmt::Debug;
use core::ops::{Index, IndexMut}; use core::ops::{Index, IndexMut};
use constants; use constants;
/// The `Scalar64` struct represents an element in ℤ/lℤ as 5 52-bit limbs /// The `Scalar64` struct represents an element in
/// \\(\mathbb Z / \ell \mathbb Z\\) as 5 \\(52\\)-bit limbs.
#[derive(Copy,Clone)] #[derive(Copy,Clone)]
pub struct Scalar64(pub [u64; 5]); pub struct Scalar64(pub [u64; 5]);

View file

@ -8,9 +8,7 @@
// - Isis Agora Lovecruft <isis@patternsinthevoid.net> // - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca> // - Henry de Valence <hdevalence@hdevalence.ca>
//! This module contains various constants (such as curve parameters //! This module contains various constants, such as the Ristretto and Ed25519 basepoints.
//! and useful field elements like `sqrt(-1)`), as well as
//! lookup tables of pre-computed points.
//! //!
//! Most of the constants are given with //! Most of the constants are given with
//! `LONG_DESCRIPTIVE_UPPER_CASE_NAMES`, but they can be brought into //! `LONG_DESCRIPTIVE_UPPER_CASE_NAMES`, but they can be brought into
@ -18,7 +16,7 @@
//! //!
//! ``` //! ```
//! use curve25519_dalek::constants; //! use curve25519_dalek::constants;
//! use curve25519_dalek::edwards::IsIdentity; //! use curve25519_dalek::traits::IsIdentity;
//! //!
//! let B = &constants::RISTRETTO_BASEPOINT_TABLE; //! let B = &constants::RISTRETTO_BASEPOINT_TABLE;
//! let l = &constants::BASEPOINT_ORDER; //! let l = &constants::BASEPOINT_ORDER;
@ -30,14 +28,15 @@
#![allow(non_snake_case)] #![allow(non_snake_case)]
use edwards::CompressedEdwardsY; use edwards::CompressedEdwardsY;
use ristretto::{RistrettoPoint, RistrettoBasepointTable}; use ristretto::RistrettoPoint;
use montgomery::CompressedMontgomeryU; use montgomery::CompressedMontgomeryU;
use scalar::Scalar; use scalar::Scalar;
#[cfg(feature="radix_51")] #[cfg(feature="radix_51")]
pub use constants_64bit::*; pub use backend::u64::constants::*;
#[cfg(not(feature="radix_51"))] #[cfg(not(feature="radix_51"))]
pub use constants_32bit::*; pub use backend::u32::constants::*;
/// Basepoint has y = 4/5. /// Basepoint has y = 4/5.
/// ///
@ -63,38 +62,51 @@ pub const RISTRETTO_BASEPOINT_POINT: RistrettoPoint = RistrettoPoint(ED25519_BAS
/// `BASEPOINT_ORDER` is the order of base point, i.e. `l = 2^252 + /// `BASEPOINT_ORDER` is the order of base point, i.e. `l = 2^252 +
/// 27742317777372353535851937790883648493`, in little-endian bytes. /// 27742317777372353535851937790883648493`, in little-endian bytes.
pub const BASEPOINT_ORDER: Scalar = Scalar([ pub const BASEPOINT_ORDER: Scalar = Scalar{
bytes: [
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
]); ],
};
/// `BASEPOINT_ORDER_MINUS_1` is the order of base point minus one, i.e. `l-1`, in little-endian bytes. /// `BASEPOINT_ORDER_MINUS_1` is the order of base point minus one, i.e. `l-1`, in little-endian bytes.
pub const BASEPOINT_ORDER_MINUS_1: Scalar = Scalar([ pub const BASEPOINT_ORDER_MINUS_1: Scalar = Scalar{
bytes: [
0xec, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xec, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
]); ],
};
/// `BASEPOINT_ORDER_MINUS_2` is the order of base point minus two, i.e. `l-2`, in little-endian bytes. /// `BASEPOINT_ORDER_MINUS_2` is the order of base point minus two, i.e. `l-2`, in little-endian bytes.
pub const BASEPOINT_ORDER_MINUS_2: Scalar = Scalar([ pub const BASEPOINT_ORDER_MINUS_2: Scalar = Scalar{
bytes: [
0xeb, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xeb, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
]); ],
};
// Precomputed basepoint table is generated into a file by build.rs
#[cfg(feature="precomputed_tables")]
include!(concat!(env!("OUT_DIR"), "/basepoint_table.rs"));
#[cfg(feature="precomputed_tables")]
use ristretto::RistrettoBasepointTable;
/// The Ed25519 basepoint, as a RistrettoPoint /// The Ed25519 basepoint, as a RistrettoPoint
#[cfg(feature="precomputed_tables")]
pub const RISTRETTO_BASEPOINT_TABLE: RistrettoBasepointTable pub const RISTRETTO_BASEPOINT_TABLE: RistrettoBasepointTable
= RistrettoBasepointTable(ED25519_BASEPOINT_TABLE); = RistrettoBasepointTable(ED25519_BASEPOINT_TABLE);
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use field::FieldElement; use field::FieldElement;
use edwards::IsIdentity; use traits::{IsIdentity, ValidityCheck};
use edwards::ValidityCheck;
use constants; use constants;
#[test] #[test]
@ -129,7 +141,7 @@ mod test {
#[test] #[test]
#[cfg(feature="radix_51")] #[cfg(feature="radix_51")]
fn sqrt_minus_aplus2() { fn sqrt_minus_aplus2() {
use field_64bit::FieldElement64; use backend::u64::field::FieldElement64;
let minus_aplus2 = -&FieldElement64([486664,0,0,0,0]); let minus_aplus2 = -&FieldElement64([486664,0,0,0,0]);
let sqrt = constants::SQRT_MINUS_APLUS2; let sqrt = constants::SQRT_MINUS_APLUS2;
let sq = &sqrt * &sqrt; let sq = &sqrt * &sqrt;
@ -141,8 +153,8 @@ mod test {
#[test] #[test]
#[cfg(not(feature="radix_51"))] #[cfg(not(feature="radix_51"))]
fn sqrt_minus_aplus2() { fn sqrt_minus_aplus2() {
use field_32bit::FieldElement32; use backend::u32::field::FieldElement32;
let minus_aplus2 = FieldElement32([-486664,0,0,0,0,0,0,0,0,0]); let minus_aplus2 = -&FieldElement32([486664,0,0,0,0,0,0,0,0,0]);
let sqrt = constants::SQRT_MINUS_APLUS2; let sqrt = constants::SQRT_MINUS_APLUS2;
let sq = &sqrt * &sqrt; let sq = &sqrt * &sqrt;
assert_eq!(sq, minus_aplus2); assert_eq!(sq, minus_aplus2);
@ -171,9 +183,9 @@ mod test {
#[cfg(not(feature="radix_51"))] #[cfg(not(feature="radix_51"))]
#[test] #[test]
fn test_d_vs_ratio() { fn test_d_vs_ratio() {
use field_32bit::FieldElement32; use backend::u32::field::FieldElement32;
let a = FieldElement32([-121665,0,0,0,0,0,0,0,0,0]); let a = -&FieldElement32([121665,0,0,0,0,0,0,0,0,0]);
let b = FieldElement32([ 121666,0,0,0,0,0,0,0,0,0]); let b = FieldElement32([121666,0,0,0,0,0,0,0,0,0]);
let d = &a * &b.invert(); let d = &a * &b.invert();
let d2 = &d + &d; let d2 = &d + &d;
assert_eq!(d, constants::EDWARDS_D); assert_eq!(d, constants::EDWARDS_D);
@ -184,7 +196,7 @@ mod test {
#[cfg(feature="radix_51")] #[cfg(feature="radix_51")]
#[test] #[test]
fn test_d_vs_ratio() { fn test_d_vs_ratio() {
use field_64bit::FieldElement64; use backend::u64::field::FieldElement64;
let a = -&FieldElement64([121665,0,0,0,0]); let a = -&FieldElement64([121665,0,0,0,0]);
let b = FieldElement64([121666,0,0,0,0]); let b = FieldElement64([121666,0,0,0,0]);
let d = &a * &b.invert(); let d = &a * &b.invert();

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

503
src/curve_models/mod.rs Normal file
View file

@ -0,0 +1,503 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! This module contains internal curve representations which are not part
//! of the public API.
//!
//! # Curve representations
//!
//! Internally, we use several different models for the curve. Here
//! is a sketch of the relationship between the models, following [a
//! post][smith-moderncrypto]
//! by Ben Smith on the `moderncrypto` mailing list. This is also briefly
//! discussed in section 2.5 of [_Montgomery curves and their
//! arithmetic_][costello-smith-2017] by Costello and Smith.
//!
//! Begin with the affine equation for the curve,
//! $$
//! -x\^2 + y\^2 = 1 + dx\^2y\^2.
//! $$
//! Next, pass to the projective closure \\(\mathbb P\^1 \times \mathbb
//! P\^1 \\) by setting \\(x=X/Z\\), \\(y=Y/T.\\) Clearing denominators
//! gives the model
//! $$
//! -X\^2T\^2 + Y\^2Z\^2 = Z\^2T\^2 + dX\^2Y\^2.
//! $$
//! In `curve25519-dalek`, this is represented as the `CompletedPoint`
//! struct.
//! To map from \\(\mathbb P\^1 \times \mathbb P\^1 \\), a product of
//! two lines, to \\(\mathbb P\^3\\), we use the [Segre
//! embedding](https://en.wikipedia.org/wiki/Segre_embedding)
//! $$
//! \sigma : ((X:Z),(Y:T)) \mapsto (XY:XT:ZY:ZT).
//! $$
//! Using coordinates \\( (W_0:W_1:W_2:W_3) \\) for \\(\mathbb P\^3\\),
//! the image \\(\sigma (\mathbb P\^1 \times \mathbb P\^1) \\) is the
//! surface defined by \\( W_0 W_3 = W_1 W_2 \\), and under \\(
//! \sigma\\), the equation above becomes
//! $$
//! -W\_1\^2 + W\_2\^2 = W\_3\^2 + dW\_0\^2,
//! $$
//! so that the curve is given by the pair of equations
//! $$
//! \begin{aligned}
//! -W\_1\^2 + W\_2\^2 &= W\_3\^2 + dW\_0\^2, \\\\
//! W_0 W_3 &= W_1 W_2.
//! \end{aligned}
//! $$
//! Up to variable naming, this is exactly the "extended" curve model
//! introduced in [_Twisted Edwards Curves
//! Revisited_][hisil-wong-carter-dawson-2008] by Hisil, Wong, Carter,
//! and Dawson. In `curve25519-dalek`, it is represented as the
//! `ExtendedPoint` struct. We can map from \\(\mathbb P\^3 \\) to
//! \\(\mathbb P\^2 \\) by sending \\( (W\_0:W\_1:W\_2:W\_3) \\) to \\(
//! (W\_1:W\_2:W\_3) \\). Notice that
//! $$
//! \frac {W\_1} {W\_3} = \frac {XT} {ZT} = \frac X Z = x,
//! $$
//! and
//! $$
//! \frac {W\_2} {W\_3} = \frac {YZ} {ZT} = \frac Y T = y,
//! $$
//! so this is the same as if we had started with the affine model
//! and passed to \\( \mathbb P\^2 \\) by setting \\( x = W\_1 / W\_3
//! \\), \\(y = W\_2 / W\_3 \\).
//! Up to variable naming, this is the projective representation
//! introduced in in [_Twisted Edwards
//! Curves_][bernstein-birkner-joye-lange-peters-2008] by Bernstein,
//! Birkner, Joye, Lange, and Peters. In `curve25519-dalek`, it is
//! represented by the `ProjectivePoint` struct.
//!
//! # Passing between curve models
//!
//! Although the \\( \mathbb P\^3 \\) model provides faster addition
//! formulas, the \\( \mathbb P\^2 \\) model provides faster doubling
//! formulas. Hisil, Wong, Carter, and Dawson therefore suggest mixing
//! coordinate systems for scalar multiplication, attributing the idea
//! to [a 1998 paper][cohen-miyaji-ono-1998] of Cohen, Miyagi, and Ono.
//!
//! Their suggestion is to vary the formulas used by context, using a
//! \\( \mathbb P\^2 \rightarrow \mathbb P\^2 \\) doubling formula when
//! a doubling is followed
//! by another doubling, a \\( \mathbb P\^2 \rightarrow \mathbb P\^3 \\)
//! doubling formula when a doubling is followed by an addition, and
//! computing point additions using a \\( \mathbb P\^3 \times \mathbb P\^3
//! \rightarrow \mathbb P\^2 \\) formula.
//!
//! The `ref10` reference implementation of [Ed25519][ed25519], by
//! Bernstein, Duif, Lange, Schwabe, and Yang, tweaks
//! this strategy, factoring the addition formulas through the
//! completion \\( \mathbb P\^1 \times \mathbb P\^1 \\), so that the
//! output of an addition or doubling always lies in \\( \mathbb P\^1 \times
//! \mathbb P\^1\\), and the choice of which formula to use is replaced
//! by a choice of whether to convert the result to \\( \mathbb P\^2 \\)
//! or \\(\mathbb P\^2 \\). However, this tweak is not described in
//! their paper, only in their software.
//!
//! Our naming for the `CompletedPoint` (\\(\mathbb P\^1 \times \mathbb
//! P\^1 \\)), `ProjectivePoint` (\\(\mathbb P\^2 \\)), and
//! `ExtendedPoint` (\\(\mathbb P\^3 \\)) structs follows the naming in
//! Adam Langley's [Golang ed25519][agl-ed25519] implementation, which
//! `curve25519-dalek` was originally derived from.
//!
//! Finally, to accelerate readditions, we use two cached point formats
//! in "Niels coordinates", named for Niels Duif,
//! one for the affine model and one for the \\( \mathbb P\^3 \\) model:
//!
//! * `AffineNielsPoint`: \\( (y+x, y-x, 2dxy) \\)
//! * `ProjectiveNielsPoint`: \\( (Y+X, Y-X, Z, 2dXY) \\)
//!
//! [smith-moderncrypto]: https://moderncrypto.org/mail-archive/curves/2016/000807.html
//! [costello-smith-2017]: https://eprint.iacr.org/2017/212
//! [hisil-wong-carter-dawson-2008]: https://www.iacr.org/archive/asiacrypt2008/53500329/53500329.pdf
//! [bernstein-birkner-joye-lange-peters-2008]: https://eprint.iacr.org/2008/013
//! [cohen-miyaji-ono-1998]: https://link.springer.com/content/pdf/10.1007%2F3-540-49649-1_6.pdf
//! [ed25519]: https://eprint.iacr.org/2011/368
//! [agl-ed25519]: https://github.com/agl/ed25519
#![allow(non_snake_case)]
use core::fmt::Debug;
use core::ops::{Add, Sub, Neg};
use constants;
use field::FieldElement;
use edwards::ExtendedPoint;
use subtle::ConditionallyAssignable;
use traits::ValidityCheck;
// ------------------------------------------------------------------------
// Internal point representations
// ------------------------------------------------------------------------
/// A `ProjectivePoint` is a point \\((X:Y:Z)\\) on the \\(\mathbb
/// P\^2\\) model of the curve.
/// A point \\((x,y)\\) in the affine model corresponds to
/// \\((x:y:1)\\).
///
/// More details on the relationships between the different curve models
/// can be found in the module-level documentation.
#[derive(Copy, Clone)]
pub struct ProjectivePoint {
pub X: FieldElement,
pub Y: FieldElement,
pub Z: FieldElement,
}
/// A `CompletedPoint` is a point \\(((X:Z), (Y:T))\\) on the \\(\mathbb
/// P\^1 \times \mathbb P\^1 \\) model of the curve.
/// A point (x,y) in the affine model corresponds to \\( ((x:1),(y:1))
/// \\).
///
/// More details on the relationships between the different curve models
/// can be found in the module-level documentation.
#[derive(Copy, Clone)]
#[allow(missing_docs)]
pub struct CompletedPoint {
pub X: FieldElement,
pub Y: FieldElement,
pub Z: FieldElement,
pub T: FieldElement,
}
/// A pre-computed point in the affine model for the curve, represented as
/// \\((y+x, y-x, 2dxy)\\) in "Niels coordinates".
///
/// More details on the relationships between the different curve models
/// can be found in the module-level documentation.
// Safe to derive Eq because affine coordinates.
#[derive(Copy, Clone, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct AffineNielsPoint {
pub y_plus_x: FieldElement,
pub y_minus_x: FieldElement,
pub xy2d: FieldElement,
}
/// A pre-computed point on the \\( \mathbb P\^3 \\) model for the
/// curve, represented as \\((Y+X, Y-X, Z, 2dXY)\\) in "Niels coordinates".
///
/// More details on the relationships between the different curve models
/// can be found in the module-level documentation.
#[derive(Copy, Clone)]
pub struct ProjectiveNielsPoint {
pub Y_plus_X: FieldElement,
pub Y_minus_X: FieldElement,
pub Z: FieldElement,
pub T2d: FieldElement,
}
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
use traits::Identity;
impl Identity for ProjectivePoint {
fn identity() -> ProjectivePoint {
ProjectivePoint{
X: FieldElement::zero(),
Y: FieldElement::one(),
Z: FieldElement::one(),
}
}
}
impl Identity for ProjectiveNielsPoint {
fn identity() -> ProjectiveNielsPoint {
ProjectiveNielsPoint{
Y_plus_X: FieldElement::one(),
Y_minus_X: FieldElement::one(),
Z: FieldElement::one(),
T2d: FieldElement::zero(),
}
}
}
impl Identity for AffineNielsPoint {
fn identity() -> AffineNielsPoint {
AffineNielsPoint{
y_plus_x: FieldElement::one(),
y_minus_x: FieldElement::one(),
xy2d: FieldElement::zero(),
}
}
}
// ------------------------------------------------------------------------
// Validity checks (for debugging, not CT)
// ------------------------------------------------------------------------
impl ValidityCheck for ProjectivePoint {
fn is_valid(&self) -> bool {
// Curve equation is -x^2 + y^2 = 1 + d*x^2*y^2,
// homogenized as (-X^2 + Y^2)*Z^2 = Z^4 + d*X^2*Y^2
let XX = self.X.square();
let YY = self.Y.square();
let ZZ = self.Z.square();
let ZZZZ = ZZ.square();
let lhs = &(&YY - &XX) * &ZZ;
let rhs = &ZZZZ + &(&constants::EDWARDS_D * &(&XX * &YY));
lhs == rhs
}
}
// ------------------------------------------------------------------------
// Constant-time assignment
// ------------------------------------------------------------------------
impl ConditionallyAssignable for ProjectiveNielsPoint {
fn conditional_assign(&mut self, other: &ProjectiveNielsPoint, choice: u8) {
self.Y_plus_X.conditional_assign(&other.Y_plus_X, choice);
self.Y_minus_X.conditional_assign(&other.Y_minus_X, choice);
self.Z.conditional_assign(&other.Z, choice);
self.T2d.conditional_assign(&other.T2d, choice);
}
}
impl ConditionallyAssignable for AffineNielsPoint {
fn conditional_assign(&mut self, other: &AffineNielsPoint, choice: u8) {
// PreComputedGroupElementCMove()
self.y_plus_x.conditional_assign(&other.y_plus_x, choice);
self.y_minus_x.conditional_assign(&other.y_minus_x, choice);
self.xy2d.conditional_assign(&other.xy2d, choice);
}
}
// ------------------------------------------------------------------------
// Point conversions
// ------------------------------------------------------------------------
impl ProjectivePoint {
/// Convert this point from the \\( \mathbb P\^2 \\) model to the
/// \\( \mathbb P\^3 \\) model.
///
/// This costs \\(3 \mathrm M + 1 \mathrm S\\).
pub fn to_extended(&self) -> ExtendedPoint {
ExtendedPoint{
X: &self.X * &self.Z,
Y: &self.Y * &self.Z,
Z: self.Z.square(),
T: &self.X * &self.Y,
}
}
}
impl CompletedPoint {
/// Convert this point from the \\( \mathbb P\^1 \times \mathbb P\^1
/// \\) model to the \\( \mathbb P\^2 \\) model.
///
/// This costs \\(3 \mathrm M \\).
pub fn to_projective(&self) -> ProjectivePoint {
ProjectivePoint{
X: &self.X * &self.T,
Y: &self.Y * &self.Z,
Z: &self.Z * &self.T,
}
}
/// Convert this point from the \\( \mathbb P\^1 \times \mathbb P\^1
/// \\) model to the \\( \mathbb P\^3 \\) model.
///
/// This costs \\(4 \mathrm M \\).
pub fn to_extended(&self) -> ExtendedPoint {
ExtendedPoint{
X: &self.X * &self.T,
Y: &self.Y * &self.Z,
Z: &self.Z * &self.T,
T: &self.X * &self.Y,
}
}
}
// ------------------------------------------------------------------------
// Doubling
// ------------------------------------------------------------------------
impl ProjectivePoint {
/// Double this point: return self + self
pub fn double(&self) -> CompletedPoint { // Double()
let XX = self.X.square();
let YY = self.Y.square();
let ZZ2 = self.Z.square2();
let X_plus_Y = &self.X + &self.Y;
let X_plus_Y_sq = X_plus_Y.square();
let YY_plus_XX = &YY + &XX;
let YY_minus_XX = &YY - &XX;
CompletedPoint{
X: &X_plus_Y_sq - &YY_plus_XX,
Y: YY_plus_XX,
Z: YY_minus_XX,
T: &ZZ2 - &YY_minus_XX
}
}
}
// ------------------------------------------------------------------------
// Addition and Subtraction
// ------------------------------------------------------------------------
// XXX(hdevalence) These were doc(hidden) so they don't appear in the
// public API docs.
// However, that prevents them being used with --document-private-items,
// so comment out the doc(hidden) for now until this is resolved
//
// upstream rust issue: https://github.com/rust-lang/rust/issues/46380
//#[doc(hidden)]
impl<'a, 'b> Add<&'b ProjectiveNielsPoint> for &'a ExtendedPoint {
type Output = CompletedPoint;
fn add(self, other: &'b ProjectiveNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PP = &Y_plus_X * &other.Y_plus_X;
let MM = &Y_minus_X * &other.Y_minus_X;
let TT2d = &self.T * &other.T2d;
let ZZ = &self.Z * &other.Z;
let ZZ2 = &ZZ + &ZZ;
CompletedPoint{
X: &PP - &MM,
Y: &PP + &MM,
Z: &ZZ2 + &TT2d,
T: &ZZ2 - &TT2d
}
}
}
//#[doc(hidden)]
impl<'a, 'b> Sub<&'b ProjectiveNielsPoint> for &'a ExtendedPoint {
type Output = CompletedPoint;
fn sub(self, other: &'b ProjectiveNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PM = &Y_plus_X * &other.Y_minus_X;
let MP = &Y_minus_X * &other.Y_plus_X;
let TT2d = &self.T * &other.T2d;
let ZZ = &self.Z * &other.Z;
let ZZ2 = &ZZ + &ZZ;
CompletedPoint{
X: &PM - &MP,
Y: &PM + &MP,
Z: &ZZ2 - &TT2d,
T: &ZZ2 + &TT2d
}
}
}
//#[doc(hidden)]
impl<'a, 'b> Add<&'b AffineNielsPoint> for &'a ExtendedPoint {
type Output = CompletedPoint;
fn add(self, other: &'b AffineNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PP = &Y_plus_X * &other.y_plus_x;
let MM = &Y_minus_X * &other.y_minus_x;
let Txy2d = &self.T * &other.xy2d;
let Z2 = &self.Z + &self.Z;
CompletedPoint{
X: &PP - &MM,
Y: &PP + &MM,
Z: &Z2 + &Txy2d,
T: &Z2 - &Txy2d
}
}
}
//#[doc(hidden)]
impl<'a, 'b> Sub<&'b AffineNielsPoint> for &'a ExtendedPoint {
type Output = CompletedPoint;
fn sub(self, other: &'b AffineNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PM = &Y_plus_X * &other.y_minus_x;
let MP = &Y_minus_X * &other.y_plus_x;
let Txy2d = &self.T * &other.xy2d;
let Z2 = &self.Z + &self.Z;
CompletedPoint{
X: &PM - &MP,
Y: &PM + &MP,
Z: &Z2 - &Txy2d,
T: &Z2 + &Txy2d
}
}
}
// ------------------------------------------------------------------------
// Negation
// ------------------------------------------------------------------------
impl<'a> Neg for &'a ProjectiveNielsPoint {
type Output = ProjectiveNielsPoint;
fn neg(self) -> ProjectiveNielsPoint {
ProjectiveNielsPoint{
Y_plus_X: self.Y_minus_X,
Y_minus_X: self.Y_plus_X,
Z: self.Z,
T2d: -(&self.T2d),
}
}
}
impl<'a> Neg for &'a AffineNielsPoint {
type Output = AffineNielsPoint;
fn neg(self) -> AffineNielsPoint {
AffineNielsPoint{
y_plus_x: self.y_minus_x,
y_minus_x: self.y_plus_x,
xy2d: -(&self.xy2d)
}
}
}
// ------------------------------------------------------------------------
// Debug traits
// ------------------------------------------------------------------------
impl Debug for ProjectivePoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "ProjectivePoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?}\n}}",
&self.X, &self.Y, &self.Z)
}
}
impl Debug for CompletedPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "CompletedPoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?},\n\tT: {:?}\n}}",
&self.X, &self.Y, &self.Z, &self.T)
}
}
impl Debug for AffineNielsPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "AffineNielsPoint{{\n\ty_plus_x: {:?},\n\ty_minus_x: {:?},\n\txy2d: {:?}\n}}",
&self.y_plus_x, &self.y_minus_x, &self.xy2d)
}
}
impl Debug for ProjectiveNielsPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "ProjectiveNielsPoint{{\n\tY_plus_X: {:?},\n\tY_minus_X: {:?},\n\tZ: {:?},\n\tT2d: {:?}\n}}",
&self.Y_plus_X, &self.Y_minus_X, &self.Z, &self.T2d)
}
}

File diff suppressed because it is too large Load diff

View file

@ -8,15 +8,19 @@
// - Isis Agora Lovecruft <isis@patternsinthevoid.net> // - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca> // - Henry de Valence <hdevalence@hdevalence.ca>
//! Field arithmetic for ℤ/(2²⁵⁵-19). //! Field arithmetic modulo \\(p = 2\^{255} - 19\\).
//! //!
//! Partially based on Adam Langley's curve25519-donna and (Golang) //! The `curve25519_dalek::field` module provides a type alias
//! ed25519 implementations, with other techniques inspired by Mike //! `curve25519_dalek::field::FieldElement` to a field element type
//! Hamburg's code. //! defined in the `backend` module; either `FieldElement64` or
//! `FieldElement32`.
//! //!
//! This module re-exports either the 32-bit or 64-bit implementation, //! Field operations defined in terms of machine
//! and implements functions that are generic with respect to the //! operations, such as field multiplication or squaring, are defined in
//! basic operations, such as inverses and square roots. //! the backend implementation.
//!
//! Field operations defined in terms of other field operations, such as
//! field inversion or square roots, are defined here.
use core::cmp::{Eq, PartialEq}; use core::cmp::{Eq, PartialEq};
@ -27,17 +31,27 @@ use subtle::ConditionallyNegatable;
use subtle::Equal; use subtle::Equal;
use constants; use constants;
use backend;
/// A `FieldElement` represents an element of the field GF(2^255 - 19).
#[cfg(feature="radix_51")] #[cfg(feature="radix_51")]
pub type FieldElement = FieldElement64; pub use backend::u64::field::*;
/// A `FieldElement` represents an element of the field GF(2^255 - 19). /// A `FieldElement` represents an element of the field
#[cfg(not(feature="radix_51"))] /// \\( \mathbb Z / (2\^{255} - 19)\\).
pub type FieldElement = FieldElement32; ///
/// The `FieldElement` type is an alias for one of the platform-specific
/// implementations.
#[cfg(feature="radix_51")] #[cfg(feature="radix_51")]
pub use field_64bit::*; pub type FieldElement = backend::u64::field::FieldElement64;
#[cfg(not(feature="radix_51"))] #[cfg(not(feature="radix_51"))]
pub use field_32bit::*; pub use backend::u32::field::*;
/// A `FieldElement` represents an element of the field
/// \\( \mathbb Z / (2\^{255} - 19)\\).
///
/// The `FieldElement` type is an alias for one of the platform-specific
/// implementations.
#[cfg(not(feature="radix_51"))]
pub type FieldElement = backend::u32::field::FieldElement32;
impl Eq for FieldElement {} impl Eq for FieldElement {}
impl PartialEq for FieldElement { impl PartialEq for FieldElement {
@ -404,29 +418,6 @@ mod test {
assert_eq!(without_highbit_set, with_highbit_set); assert_eq!(without_highbit_set, with_highbit_set);
} }
#[cfg(not(feature="radix_51"))]
static B_LIMBS_RADIX_25_5: FieldElement32 = FieldElement32(
[-5652623, 8034020, 8266223, -13556020, -5672552,
-5582839, -12603138, 15161929, -16418207, 13296296]);
#[cfg(not(feature="radix_51"))]
#[test]
fn from_bytes_vs_radix_25_5_limb_constants() {
let test_elt = FieldElement::from_bytes(&B_BYTES);
assert_eq!(test_elt.0, B_LIMBS_RADIX_25_5.0);
}
#[cfg(not(feature="radix_51"))]
#[test]
fn radix_25_5_limb_constants_to_bytes_vs_byte_constants() {
let test_bytes = B_LIMBS_RADIX_25_5.to_bytes();
for i in 0..31 {
assert!(test_bytes[i] == B_BYTES[i]);
}
// Check that high bit is set to zero in to_bytes
assert!(test_bytes[31] == (B_BYTES[31] & 127u8));
}
#[test] #[test]
fn conditional_negate() { fn conditional_negate() {
let one = FieldElement::one(); let one = FieldElement::one();

View file

@ -1,565 +0,0 @@
// -*- mode: rust; coding: utf-8; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! Field arithmetic for ℤ/(2²⁵⁵-19), using 32-bit arithmetic with
//! 64-bit products.
//!
//! Based on Adam Langley's curve25519-donna and (Golang) ed25519
//! implementations.
//!
//! This implementation is intended for platforms that can multiply
//! 32-bit inputs to produce 64-bit outputs.
//!
//! This implementation is not preferred for use on x86_64, since the
//! 64-bit implementation is both much simpler and much faster.
//! However, that implementation requires Rust's `u128`, which is not
//! yet stable.
use core::fmt::Debug;
use core::ops::{Add, AddAssign};
use core::ops::{Sub, SubAssign};
use core::ops::{Mul, MulAssign};
use core::ops::Neg;
use subtle::ConditionallyAssignable;
use utils::{load3, load4};
/// A `FieldElement32` represents an element of the field GF(2^255 - 19).
///
/// In the 32-bit implementation, a `FieldElement32` is represented in
/// radix 2^25.5 as ten `i32`s, so that an element t, entries
/// t[0],...,t[9], represents the integer t[0]+2^26 t[1]+2^51
/// t[2]+2^77 t[3]+2^102 t[4]+...+2^230 t[9].
///
/// The coefficients t[i] are allowed to grow between multiplications.
///
/// XXX document by how much
///
/// # Warning
///
/// You almost certainly do not want to use `FieldElement32` directly. Consider
/// using `curve25519_dalek::field::FieldElement`, which will automatically
/// select between `FieldElement32` and `FieldElement64` depending on whether
/// curve25519-dalek was compiled with `--features="nightly"`.
///
/// This implementation, `FieldElement32`, is intended for platforms that can
/// multiply 32-bit inputs to produce 64-bit outputs, and is not preferred for
/// use on x86_64, since the 64-bit implementation is both much simpler and much
/// faster. However, the `FieldElement64` implementation requires Rust's
/// `u128`, which is not yet stable.
#[derive(Copy, Clone)]
pub struct FieldElement32(pub (crate) [i32; 10]);
impl Debug for FieldElement32 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "FieldElement32: {:?}", &self.0[..])
}
}
impl<'b> AddAssign<&'b FieldElement32> for FieldElement32 {
fn add_assign(&mut self, _rhs: &'b FieldElement32) {
for i in 0..10 {
self.0[i] += _rhs.0[i];
}
}
}
impl<'a, 'b> Add<&'b FieldElement32> for &'a FieldElement32 {
type Output = FieldElement32;
fn add(self, _rhs: &'b FieldElement32) -> FieldElement32 {
let mut output = *self;
output += _rhs;
output
}
}
impl<'b> SubAssign<&'b FieldElement32> for FieldElement32 {
fn sub_assign(&mut self, _rhs: &'b FieldElement32) {
for i in 0..10 {
self.0[i] -= _rhs.0[i];
}
}
}
impl<'a, 'b> Sub<&'b FieldElement32> for &'a FieldElement32 {
type Output = FieldElement32;
fn sub(self, _rhs: &'b FieldElement32) -> FieldElement32 {
let mut output = *self;
output -= _rhs;
output
}
}
impl<'b> MulAssign<&'b FieldElement32> for FieldElement32 {
fn mul_assign(&mut self, _rhs: &'b FieldElement32) {
let result = (self as &FieldElement32) * _rhs;
self.0 = result.0;
}
}
impl<'a, 'b> Mul<&'b FieldElement32> for &'a FieldElement32 {
type Output = FieldElement32;
fn mul(self, _rhs: &'b FieldElement32) -> FieldElement32 {
// Notes preserved from ed25519.go (presumably originally from ref10):
//
// Calculates h = f * g. Can overlap h with f or g.
//
// # Preconditions
//
// * |f[i]| bounded by 1.1*2^26, 1.1*2^25, 1.1*2^26, 1.1*2^25, etc.
// * |g[i]| bounded by 1.1*2^26, 1.1*2^25, 1.1*2^26, 1.1*2^25, etc.
//
// # Postconditions
//
// * |h| bounded by 1.1*2^25, 1.1*2^24, 1.1*2^25, 1.1*2^24, etc.
//
// ## Notes on implementation strategy
//
// * Using schoolbook multiplication.
// * Karatsuba would save a little in some cost models.
//
// * Most multiplications by 2 and 19 are 32-bit precomputations;
// cheaper than 64-bit postcomputations.
//
// * There is one remaining multiplication by 19 in the carry chain;
// one *19 precomputation can be merged into this,
// but the resulting data flow is considerably less clean.
//
// * There are 12 carries below.
// 10 of them are 2-way parallelizable and vectorizable.
// Can get away with 11 carries, but then data flow is much deeper.
//
// * With tighter constraints on inputs can squeeze carries into int32.
let f0 = self.0[0] as i64;
let f1 = self.0[1] as i64;
let f2 = self.0[2] as i64;
let f3 = self.0[3] as i64;
let f4 = self.0[4] as i64;
let f5 = self.0[5] as i64;
let f6 = self.0[6] as i64;
let f7 = self.0[7] as i64;
let f8 = self.0[8] as i64;
let f9 = self.0[9] as i64;
let f1_2 = (2 * self.0[1]) as i64;
let f3_2 = (2 * self.0[3]) as i64;
let f5_2 = (2 * self.0[5]) as i64;
let f7_2 = (2 * self.0[7]) as i64;
let f9_2 = (2 * self.0[9]) as i64;
let g0 = _rhs.0[0] as i64;
let g1 = _rhs.0[1] as i64;
let g2 = _rhs.0[2] as i64;
let g3 = _rhs.0[3] as i64;
let g4 = _rhs.0[4] as i64;
let g5 = _rhs.0[5] as i64;
let g6 = _rhs.0[6] as i64;
let g7 = _rhs.0[7] as i64;
let g8 = _rhs.0[8] as i64;
let g9 = _rhs.0[9] as i64;
let g1_19 = (19 * _rhs.0[1]) as i64; /* 1.4*2^29 */
let g2_19 = (19 * _rhs.0[2]) as i64; /* 1.4*2^30; still ok */
let g3_19 = (19 * _rhs.0[3]) as i64;
let g4_19 = (19 * _rhs.0[4]) as i64;
let g5_19 = (19 * _rhs.0[5]) as i64;
let g6_19 = (19 * _rhs.0[6]) as i64;
let g7_19 = (19 * _rhs.0[7]) as i64;
let g8_19 = (19 * _rhs.0[8]) as i64;
let g9_19 = (19 * _rhs.0[9]) as i64;
let h0 = f0*g0 + f1_2*g9_19 + f2*g8_19 + f3_2*g7_19 + f4*g6_19 + f5_2*g5_19 + f6*g4_19 + f7_2*g3_19 + f8*g2_19 + f9_2*g1_19;
let h1 = f0*g1 + f1*g0 + f2*g9_19 + f3*g8_19 + f4*g7_19 + f5*g6_19 + f6*g5_19 + f7*g4_19 + f8*g3_19 + f9*g2_19;
let h2 = f0*g2 + f1_2*g1 + f2*g0 + f3_2*g9_19 + f4*g8_19 + f5_2*g7_19 + f6*g6_19 + f7_2*g5_19 + f8*g4_19 + f9_2*g3_19;
let h3 = f0*g3 + f1*g2 + f2*g1 + f3*g0 + f4*g9_19 + f5*g8_19 + f6*g7_19 + f7*g6_19 + f8*g5_19 + f9*g4_19;
let h4 = f0*g4 + f1_2*g3 + f2*g2 + f3_2*g1 + f4*g0 + f5_2*g9_19 + f6*g8_19 + f7_2*g7_19 + f8*g6_19 + f9_2*g5_19;
let h5 = f0*g5 + f1*g4 + f2*g3 + f3*g2 + f4*g1 + f5*g0 + f6*g9_19 + f7*g8_19 + f8*g7_19 + f9*g6_19;
let h6 = f0*g6 + f1_2*g5 + f2*g4 + f3_2*g3 + f4*g2 + f5_2*g1 + f6*g0 + f7_2*g9_19 + f8*g8_19 + f9_2*g7_19;
let h7 = f0*g7 + f1*g6 + f2*g5 + f3*g4 + f4*g3 + f5*g2 + f6*g1 + f7*g0 + f8*g9_19 + f9*g8_19;
let h8 = f0*g8 + f1_2*g7 + f2*g6 + f3_2*g5 + f4*g4 + f5_2*g3 + f6*g2 + f7_2*g1 + f8*g0 + f9_2*g9_19;
let h9 = f0*g9 + f1*g8 + f2*g7 + f3*g6 + f4*g5 + f5*g4 + f6*g3 + f7*g2 + f8*g1 + f9*g0;
FieldElement32::reduce([h0, h1, h2, h3, h4, h5, h6, h7, h8, h9])
}
}
impl<'a> Neg for &'a FieldElement32 {
type Output = FieldElement32;
fn neg(self) -> FieldElement32 {
let mut output = *self;
output.negate();
output
}
}
impl ConditionallyAssignable for FieldElement32 {
fn conditional_assign(&mut self, f: &FieldElement32, choice: u8) {
let mask = -(choice as i32);
for i in 0..10 {
self.0[i] ^= mask & (self.0[i] ^ f.0[i]);
}
}
}
impl FieldElement32 {
/// Invert the sign of this field element
pub fn negate(&mut self) {
for i in 0..10 {
self.0[i] = -self.0[i];
}
}
/// Construct zero.
pub fn zero() -> FieldElement32 {
FieldElement32([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ])
}
/// Construct one.
pub fn one() -> FieldElement32 {
FieldElement32([ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ])
}
/// Construct -1.
pub fn minus_one() -> FieldElement32 {
FieldElement32([-1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ])
}
fn reduce(mut h: [i64; 10]) -> FieldElement32 { //FeCombine
let mut c = [0i64; 10];
/*
|h[0]| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38))
i.e. |h[0]| <= 1.2*2^59; narrower ranges for h[2], h[4], h[6], h[8]
|h[1]| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19))
i.e. |h[1]| <= 1.5*2^58; narrower ranges for h[3], h[5], h[7], h[9]
*/
c[0] = (h[0] + (1 << 25)) >> 26;
h[1] += c[0];
h[0] -= c[0] << 26;
c[4] = (h[4] + (1 << 25)) >> 26;
h[5] += c[4];
h[4] -= c[4] << 26;
/* |h[0]| <= 2^25 */
/* |h[4]| <= 2^25 */
/* |h[1]| <= 1.51*2^58 */
/* |h[5]| <= 1.51*2^58 */
c[1] = (h[1] + (1 << 24)) >> 25;
h[2] += c[1];
h[1] -= c[1] << 25;
c[5] = (h[5] + (1 << 24)) >> 25;
h[6] += c[5];
h[5] -= c[5] << 25;
/* |h[1]| <= 2^24; from now on fits into int32 */
/* |h[5]| <= 2^24; from now on fits into int32 */
/* |h[2]| <= 1.21*2^59 */
/* |h[6]| <= 1.21*2^59 */
c[2] = (h[2] + (1 << 25)) >> 26;
h[3] += c[2];
h[2] -= c[2] << 26;
c[6] = (h[6] + (1 << 25)) >> 26;
h[7] += c[6];
h[6] -= c[6] << 26;
/* |h[2]| <= 2^25; from now on fits into int32 unchanged */
/* |h[6]| <= 2^25; from now on fits into int32 unchanged */
/* |h[3]| <= 1.51*2^58 */
/* |h[7]| <= 1.51*2^58 */
c[3] = (h[3] + (1 << 24)) >> 25;
h[4] += c[3];
h[3] -= c[3] << 25;
c[7] = (h[7] + (1 << 24)) >> 25;
h[8] += c[7];
h[7] -= c[7] << 25;
/* |h[3]| <= 2^24; from now on fits into int32 unchanged */
/* |h[7]| <= 2^24; from now on fits into int32 unchanged */
/* |h[4]| <= 1.52*2^33 */
/* |h[8]| <= 1.52*2^33 */
c[4] = (h[4] + (1 << 25)) >> 26;
h[5] += c[4];
h[4] -= c[4] << 26;
c[8] = (h[8] + (1 << 25)) >> 26;
h[9] += c[8];
h[8] -= c[8] << 26;
/* |h[4]| <= 2^25; from now on fits into int32 unchanged */
/* |h[8]| <= 2^25; from now on fits into int32 unchanged */
/* |h[5]| <= 1.01*2^24 */
/* |h[9]| <= 1.51*2^58 */
c[9] = (h[9] + (1 << 24)) >> 25;
h[0] += c[9] * 19;
h[9] -= c[9] << 25;
/* |h[9]| <= 2^24; from now on fits into int32 unchanged */
/* |h[0]| <= 1.8*2^37 */
c[0] = (h[0] + (1 << 25)) >> 26;
h[1] += c[0];
h[0] -= c[0] << 26;
/* |h[0]| <= 2^25; from now on fits into int32 unchanged */
/* |h[1]| <= 1.01*2^24 */
let mut output = FieldElement32([0i32; 10]);
output.0[0] = h[0] as i32;
output.0[1] = h[1] as i32;
output.0[2] = h[2] as i32;
output.0[3] = h[3] as i32;
output.0[4] = h[4] as i32;
output.0[5] = h[5] as i32;
output.0[6] = h[6] as i32;
output.0[7] = h[7] as i32;
output.0[8] = h[8] as i32;
output.0[9] = h[9] as i32;
output
}
/// Load a `FieldElement64` from the low 255 bits of a 256-bit
/// input.
///
/// # Warning
///
/// This function does not check that the input used the canonical
/// representative. It masks the high bit, but it will happily
/// decode 2^255 - 18 to 1. Applications that require a canonical
/// encoding of every field element should decode, re-encode to
/// the canonical encoding, and check that the input was
/// canonical.
///
/// XXX the above applies to the 64-bit implementation; check that
/// it applies here too.
pub fn from_bytes(data: &[u8; 32]) -> FieldElement32 { //FeFromBytes
let mut h = [0i64;10];
h[0] = load4(&data[ 0..]);
h[1] = load3(&data[ 4..]) << 6;
h[2] = load3(&data[ 7..]) << 5;
h[3] = load3(&data[10..]) << 3;
h[4] = load3(&data[13..]) << 2;
h[5] = load4(&data[16..]);
h[6] = load3(&data[20..]) << 7;
h[7] = load3(&data[23..]) << 5;
h[8] = load3(&data[26..]) << 4;
h[9] = (load3(&data[29..]) & 8388607) << 2;
FieldElement32::reduce(h)
}
/// Serialize this `FieldElement64` to a 32-byte array. The
/// encoding is canonical.
pub fn to_bytes(&self) -> [u8; 32] { //FeToBytes
// Comment preserved from ed25519.go (presumably originally from ref10):
//
// # Preconditions
//
// * `|h[i]|` bounded by 1.1*2^25, 1.1*2^24, 1.1*2^25, 1.1*2^24, etc.
//
// # Lemma
//
// Write p = 2^255 - 19 and q = floor(h/p).
//
// Basic claim: q = floor(2^(-255)(h + 19 * 2^-25 h9 + 2^-1)).
//
// # Proof
//
// Have |h|<=p so |q|<=1 so |19^2 * 2^-255 * q| < 1/4.
//
// Also have |h-2^230 * h9| < 2^230 so |19 * 2^-255 * (h-2^230 * h9)| < 1/4.
//
// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9), then 0<y<1.
//
// Write r = h - pq.
//
// Have 0 <= r< = p-1 = 2^255 - 20.
//
// Thus 0 <= r + 19 * 2^-255 * r < r + 19 * 2^-255 * 2^255 <= 2^255 - 1.
//
// Write x = r + 19 * 2^-255 * r + y.
//
// Then 0 < x < 2^255 so floor(2^(-255)x) = 0 so floor(q+2^(-255)x) = q.
//
// Have q+2^(-255)x = 2^-255 * (h + 19 * 2^-25 * h9 + 2^-1),
// so floor(2^-255 * (h + 19 * 2^-25 * h9 + 2^-1)) = q.
//
let mut carry = [0i32; 10];
let mut h: [i32; 10] = self.0;
let mut q:i32 = (19*h[9] + (1 << 24)) >> 25;
q = (h[0] + q) >> 26;
q = (h[1] + q) >> 25;
q = (h[2] + q) >> 26;
q = (h[3] + q) >> 25;
q = (h[4] + q) >> 26;
q = (h[5] + q) >> 25;
q = (h[6] + q) >> 26;
q = (h[7] + q) >> 25;
q = (h[8] + q) >> 26;
q = (h[9] + q) >> 25;
// Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20.
h[0] += 19 * q;
// Goal: Output h-2^255 q, which is between 0 and 2^255-20.
carry[0] = h[0] >> 26;
h[1] += carry[0];
h[0] -= carry[0] << 26;
carry[1] = h[1] >> 25;
h[2] += carry[1];
h[1] -= carry[1] << 25;
carry[2] = h[2] >> 26;
h[3] += carry[2];
h[2] -= carry[2] << 26;
carry[3] = h[3] >> 25;
h[4] += carry[3];
h[3] -= carry[3] << 25;
carry[4] = h[4] >> 26;
h[5] += carry[4];
h[4] -= carry[4] << 26;
carry[5] = h[5] >> 25;
h[6] += carry[5];
h[5] -= carry[5] << 25;
carry[6] = h[6] >> 26;
h[7] += carry[6];
h[6] -= carry[6] << 26;
carry[7] = h[7] >> 25;
h[8] += carry[7];
h[7] -= carry[7] << 25;
carry[8] = h[8] >> 26;
h[9] += carry[8];
h[8] -= carry[8] << 26;
carry[9] = h[9] >> 25;
h[9] -= carry[9] << 25;
// h10 = carry9
// Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20.
// Have h[0]+...+2^230 h[9] between 0 and 2^255-1;
// evidently 2^255 h10-2^255 q = 0.
// Goal: Output h[0]+...+2^230 h[9].
let mut s = [0u8; 32];
s[0] = (h[0] >> 0) as u8;
s[1] = (h[0] >> 8) as u8;
s[2] = (h[0] >> 16) as u8;
s[3] = ((h[0] >> 24) | (h[1] << 2)) as u8;
s[4] = (h[1] >> 6) as u8;
s[5] = (h[1] >> 14) as u8;
s[6] = ((h[1] >> 22) | (h[2] << 3)) as u8;
s[7] = (h[2] >> 5) as u8;
s[8] = (h[2] >> 13) as u8;
s[9] = ((h[2] >> 21) | (h[3] << 5)) as u8;
s[10] = (h[3] >> 3) as u8;
s[11] = (h[3] >> 11) as u8;
s[12] = ((h[3] >> 19) | (h[4] << 6)) as u8;
s[13] = (h[4] >> 2) as u8;
s[14] = (h[4] >> 10) as u8;
s[15] = (h[4] >> 18) as u8;
s[16] = (h[5] >> 0) as u8;
s[17] = (h[5] >> 8) as u8;
s[18] = (h[5] >> 16) as u8;
s[19] = ((h[5] >> 24) | (h[6] << 1)) as u8;
s[20] = (h[6] >> 7) as u8;
s[21] = (h[6] >> 15) as u8;
s[22] = ((h[6] >> 23) | (h[7] << 3)) as u8;
s[23] = (h[7] >> 5) as u8;
s[24] = (h[7] >> 13) as u8;
s[25] = ((h[7] >> 21) | (h[8] << 4)) as u8;
s[26] = (h[8] >> 4) as u8;
s[27] = (h[8] >> 12) as u8;
s[28] = ((h[8] >> 20) | (h[9] << 6)) as u8;
s[29] = (h[9] >> 2) as u8;
s[30] = (h[9] >> 10) as u8;
s[31] = (h[9] >> 18) as u8;
// Check that high bit is cleared
debug_assert!((s[31] & 0b1000_0000u8) == 0u8);
s
}
fn square_inner(&self) -> [i64; 10] {
let f0 = self.0[0] as i64;
let f1 = self.0[1] as i64;
let f2 = self.0[2] as i64;
let f3 = self.0[3] as i64;
let f4 = self.0[4] as i64;
let f5 = self.0[5] as i64;
let f6 = self.0[6] as i64;
let f7 = self.0[7] as i64;
let f8 = self.0[8] as i64;
let f9 = self.0[9] as i64;
let f0_2 = (2 * self.0[0]) as i64;
let f1_2 = (2 * self.0[1]) as i64;
let f2_2 = (2 * self.0[2]) as i64;
let f3_2 = (2 * self.0[3]) as i64;
let f4_2 = (2 * self.0[4]) as i64;
let f5_2 = (2 * self.0[5]) as i64;
let f6_2 = (2 * self.0[6]) as i64;
let f7_2 = (2 * self.0[7]) as i64;
let f5_38 = 38 * f5; // 1.31*2^30
let f6_19 = 19 * f6; // 1.31*2^30
let f7_38 = 38 * f7; // 1.31*2^30
let f8_19 = 19 * f8; // 1.31*2^30
let f9_38 = 38 * f9; // 1.31*2^30
let mut h = [0i64;10];
h[0] = f0*f0 + f1_2*f9_38 + f2_2*f8_19 + f3_2*f7_38 + f4_2*f6_19 + f5*f5_38;
h[1] = f0_2*f1 + f2*f9_38 + f3_2*f8_19 + f4*f7_38 + f5_2*f6_19;
h[2] = f0_2*f2 + f1_2*f1 + f3_2*f9_38 + f4_2*f8_19 + f5_2*f7_38 + f6*f6_19;
h[3] = f0_2*f3 + f1_2*f2 + f4*f9_38 + f5_2*f8_19 + f6*f7_38;
h[4] = f0_2*f4 + f1_2*f3_2 + f2*f2 + f5_2*f9_38 + f6_2*f8_19 + f7*f7_38;
h[5] = f0_2*f5 + f1_2*f4 + f2_2*f3 + f6*f9_38 + f7_2*f8_19;
h[6] = f0_2*f6 + f1_2*f5_2 + f2_2*f4 + f3_2*f3 + f7_2*f9_38 + f8*f8_19;
h[7] = f0_2*f7 + f1_2*f6 + f2_2*f5 + f3_2*f4 + f8*f9_38;
h[8] = f0_2*f8 + f1_2*f7_2 + f2_2*f6 + f3_2*f5_2 + f4*f4 + f9*f9_38;
h[9] = f0_2*f9 + f1_2*f8 + f2_2*f7 + f3_2*f6 + f4_2*f5;
h
}
/// Calculates h = f*f. Can overlap h with f.
///
/// XXX limbs: better to talk about headroom?
///
/// # Preconditions
///
/// * |f[i]| bounded by 1.1*2^26, 1.1*2^25, 1.1*2^26, 1.1*2^25, etc.
///
/// # Postconditions
///
/// * |h[i]| bounded by 1.1*2^25, 1.1*2^24, 1.1*2^25, 1.1*2^24, etc.
pub fn square(&self) -> FieldElement32 {
FieldElement32::reduce(self.square_inner())
}
/// Square this field element and multiply the result by 2.
///
/// XXX explain why square2 exists vs square (overflow)
///
/// # Preconditions
///
/// * |f[i]| bounded by 1.65*2^26, 1.65*2^25, 1.65*2^26, 1.65*2^25, etc.
///
/// # Postconditions
///
/// * |h[i]| bounded by 1.01*2^25, 1.01*2^24, 1.01*2^25, 1.01*2^24, etc.
///
/// # Notes
///
/// See fe_mul.c in ref10 implementation for discussion of implementation
/// strategy.
pub fn square2(&self) -> FieldElement32 {
let mut coeffs = self.square_inner();
for i in 0..self.0.len() {
coeffs[i] += coeffs[i];
}
FieldElement32::reduce(coeffs)
}
}

View file

@ -19,8 +19,7 @@
//! # curve25519-dalek //! # curve25519-dalek
//! //!
//! **A Rust implementation of field and group operations on an Edwards curve //! **A high-performance, pure-Rust implementation of group operations for Ristretto and Curve25519.**
//! over GF(2^255 - 19).**
//! //!
//! **[SPOILER ALERT]** The Twelfth Doctor's first encounter with the Daleks is //! **[SPOILER ALERT]** The Twelfth Doctor's first encounter with the Daleks is
//! in his second full episode, "Into the Dalek". A beleaguered ship of the //! in his second full episode, "Into the Dalek". A beleaguered ship of the
@ -35,22 +34,9 @@
//! hatred of the Daleks. Rusty destroys the other Daleks and departs the //! hatred of the Daleks. Rusty destroys the other Daleks and departs the
//! ship, determined to track down and bring an end to the Dalek race. //! ship, determined to track down and bring an end to the Dalek race.
#[cfg(all(test, feature = "bench"))] //------------------------------------------------------------------------
extern crate test; // External dependencies:
//------------------------------------------------------------------------
// this appears to only be used for serde support right now?
#[cfg(feature = "serde")]
#[macro_use]
extern crate arrayref;
extern crate generic_array;
extern crate digest;
extern crate subtle;
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(all(test, feature = "serde"))]
extern crate serde_cbor;
#[cfg(feature = "std")] #[cfg(feature = "std")]
extern crate core; extern crate core;
@ -61,33 +47,49 @@ extern crate rand;
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
extern crate alloc; extern crate alloc;
// Modules for low-level operations directly on field elements and curve points. #[cfg(all(test, feature = "bench"))]
extern crate test;
pub mod field; // The `Digest` trait is implemented using `generic_array`, so we need it
#[cfg(not(feature="radix_51"))] // too. Hopefully we can eliminate `generic_array` from `Digest` once const
mod field_32bit; // generics land.
#[cfg(feature="radix_51")] extern crate digest;
mod field_64bit; extern crate generic_array;
// Used for traits related to constant-time code.
extern crate subtle;
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(all(test, feature = "serde"))]
extern crate serde_cbor;
//------------------------------------------------------------------------
// curve25519-dalek public modules
//------------------------------------------------------------------------
// Scalar arithmetic mod l = 2^252 + ..., the order of the Ristretto group
pub mod scalar; pub mod scalar;
#[cfg(not(feature="radix_51"))] // Point operations on the Montgomery form of Curve25519
mod scalar_32bit;
#[cfg(feature="radix_51")]
mod scalar_64bit;
pub mod edwards;
pub mod montgomery; pub mod montgomery;
// Point operations on the Edwards form of Curve25519
pub mod edwards;
// Group operations on the Ristretto group
pub mod ristretto; pub mod ristretto;
// Useful constants, like the Ed25519 basepoint
// Other miscelaneous utilities.
pub mod utils;
// Low-level curve and point constants, as well as pre-computed curve group elements.
pub mod constants; pub mod constants;
#[cfg(not(feature="radix_51"))] // External (and internal) traits.
mod constants_32bit; pub mod traits;
#[cfg(feature="radix_51")]
mod constants_64bit; //------------------------------------------------------------------------
// curve25519-dalek internal modules
//------------------------------------------------------------------------
// Finite field arithmetic mod p = 2^255 - 19
pub(crate) mod field;
// Arithmetic backends (using u32, u64, etc) live here
pub(crate) mod backend;
// Internal curve models which are not part of the public API.
pub(crate) mod curve_models;

View file

@ -8,7 +8,7 @@
// - Isis Agora Lovecruft <isis@patternsinthevoid.net> // - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca> // - Henry de Valence <hdevalence@hdevalence.ca>
//! Montgomery arithmetic. //! Group operations for Curve25519, in Montgomery form.
//! //!
//! Apart from the compressed point implementation //! Apart from the compressed point implementation
//! (i.e. `CompressedMontgomeryU`), this module is a "clean room" implementation //! (i.e. `CompressedMontgomeryU`), this module is a "clean room" implementation
@ -38,7 +38,9 @@ use scalar::Scalar;
// XXX Move these to a common "group" module? At the same time, we should // XXX Move these to a common "group" module? At the same time, we should
// XXX probably make a `trait Group` once const generics are implemented in // XXX probably make a `trait Group` once const generics are implemented in
// XXX Rust. —isis // XXX Rust. —isis
use edwards::{Identity, ValidityCheck}; //
// XXX I put these in a `traits` module for now - hdevalence
use traits::{Identity, ValidityCheck};
use subtle::ConditionallyAssignable; use subtle::ConditionallyAssignable;
use subtle::ConditionallySwappable; use subtle::ConditionallySwappable;
@ -426,9 +428,8 @@ impl<'a, 'b> Mul<&'b MontgomeryPoint> for &'a Scalar {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use constants::ED25519_BASEPOINT_TABLE;
use constants::BASE_COMPRESSED_MONTGOMERY; use constants::BASE_COMPRESSED_MONTGOMERY;
use edwards::Identity; use traits::Identity;
use super::*; use super::*;
use rand::OsRng; use rand::OsRng;
@ -484,26 +485,29 @@ mod test {
} }
#[test] #[test]
#[cfg(feature="precomputed_tables")]
fn montgomery_ct_eq_ne() { fn montgomery_ct_eq_ne() {
let mut csprng: OsRng = OsRng::new().unwrap(); let mut csprng: OsRng = OsRng::new().unwrap();
let s1: Scalar = Scalar::random(&mut csprng); let s1: Scalar = Scalar::random(&mut csprng);
let s2: Scalar = Scalar::random(&mut csprng); let s2: Scalar = Scalar::random(&mut csprng);
let p1: MontgomeryPoint = (&s1 * &ED25519_BASEPOINT_TABLE).to_montgomery(); let p1: MontgomeryPoint = (&s1 * &constants::ED25519_BASEPOINT_TABLE).to_montgomery();
let p2: MontgomeryPoint = (&s2 * &ED25519_BASEPOINT_TABLE).to_montgomery(); let p2: MontgomeryPoint = (&s2 * &constants::ED25519_BASEPOINT_TABLE).to_montgomery();
assert_eq!(p1.ct_eq(&p2), 0); assert_eq!(p1.ct_eq(&p2), 0);
} }
#[test] #[test]
#[cfg(feature="precomputed_tables")]
fn montgomery_ct_eq_eq() { fn montgomery_ct_eq_eq() {
let mut csprng: OsRng = OsRng::new().unwrap(); let mut csprng: OsRng = OsRng::new().unwrap();
let s1: Scalar = Scalar::random(&mut csprng); let s1: Scalar = Scalar::random(&mut csprng);
let p1: MontgomeryPoint = (&s1 * &ED25519_BASEPOINT_TABLE).to_montgomery(); let p1: MontgomeryPoint = (&s1 * &constants::ED25519_BASEPOINT_TABLE).to_montgomery();
assert_eq!(p1.ct_eq(&p1), 1); assert_eq!(p1.ct_eq(&p1), 1);
} }
#[test] #[test]
#[cfg(feature="precomputed_tables")]
fn differential_add_matches_edwards_model() { fn differential_add_matches_edwards_model() {
let mut csprng: OsRng = OsRng::new().unwrap(); let mut csprng: OsRng = OsRng::new().unwrap();
@ -523,6 +527,7 @@ mod test {
} }
#[test] #[test]
#[cfg(feature="precomputed_tables")]
fn ladder_matches_scalarmult() { fn ladder_matches_scalarmult() {
let mut csprng: OsRng = OsRng::new().unwrap(); let mut csprng: OsRng = OsRng::new().unwrap();
@ -544,22 +549,10 @@ mod test {
assert_eq!(result.compress(), expected.to_montgomery().compress()); assert_eq!(result.compress(), expected.to_montgomery().compress());
} }
#[test]
#[should_panic(expected = "assertion failed: self[31] <= 127")]
fn ladder_matches_scalarmult_with_scalar_high_bit_set() {
let mut s: Scalar = Scalar::one();
s[31] = 255;
let result: MontgomeryPoint = &BASE_COMPRESSED_MONTGOMERY.decompress() * &s;
let expected: ExtendedPoint = &constants::ED25519_BASEPOINT_TABLE * &s;
assert_eq!(result.compress(), expected.to_montgomery().compress())
}
} }
#[cfg(all(test, feature = "bench"))] #[cfg(all(test, feature = "bench"))]
#[cfg(feature="precomputed_tables")]
mod bench { mod bench {
use rand::OsRng; use rand::OsRng;
use constants::ED25519_BASEPOINT_TABLE; use constants::ED25519_BASEPOINT_TABLE;

View file

@ -400,18 +400,21 @@ use core::ops::{Add, Sub, Neg};
use core::ops::{AddAssign, SubAssign}; use core::ops::{AddAssign, SubAssign};
use core::ops::{Mul, MulAssign}; use core::ops::{Mul, MulAssign};
use edwards;
use edwards::ExtendedPoint;
use edwards::CompletedPoint;
use edwards::EdwardsBasepointTable;
use edwards::Identity;
use scalar::Scalar;
use subtle; use subtle;
use subtle::ConditionallyAssignable; use subtle::ConditionallyAssignable;
use subtle::ConditionallyNegatable; use subtle::ConditionallyNegatable;
use subtle::Equal; use subtle::Equal;
use edwards;
use edwards::ExtendedPoint;
use edwards::EdwardsBasepointTable;
use scalar::Scalar;
use curve_models::CompletedPoint;
use traits::Identity;
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// Compressed points // Compressed points
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@ -424,6 +427,11 @@ pub struct CompressedRistretto(pub [u8; 32]);
/// The result of compressing a `RistrettoPoint`. /// The result of compressing a `RistrettoPoint`.
impl CompressedRistretto { impl CompressedRistretto {
/// Convert this `CompressedRistretto` to its underlying array of bytes.
pub fn to_bytes(&self) -> [u8; 32] {
self.0
}
/// View this `CompressedRistretto` as an array of bytes. /// View this `CompressedRistretto` as an array of bytes.
pub fn as_bytes<'a>(&'a self) -> &'a [u8; 32] { pub fn as_bytes<'a>(&'a self) -> &'a [u8; 32] {
&self.0 &self.0
@ -530,8 +538,9 @@ impl<'de> Deserialize<'de> for RistrettoPoint {
where E: serde::de::Error where E: serde::de::Error
{ {
if v.len() == 32 { if v.len() == 32 {
let arr32 = array_ref!(v, 0, 32); // &[u8;32] from &[u8] let mut arr32 = [0u8; 32];
CompressedRistretto(*arr32) arr32[0..32].copy_from_slice(v);
CompressedRistretto(arr32)
.decompress() .decompress()
.ok_or(serde::de::Error::custom("decompression failed")) .ok_or(serde::de::Error::custom("decompression failed"))
} else { } else {
@ -557,7 +566,7 @@ impl<'de> Deserialize<'de> for RistrettoPoint {
/// `ExtendedPoint`, with custom equality, compression, and /// `ExtendedPoint`, with custom equality, compression, and
/// decompression routines to account for the quotient. /// decompression routines to account for the quotient.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct RistrettoPoint(pub ExtendedPoint); pub struct RistrettoPoint(pub(crate) ExtendedPoint);
impl RistrettoPoint { impl RistrettoPoint {
/// Compress in Ristretto format. /// Compress in Ristretto format.
@ -953,7 +962,7 @@ impl ConditionallyAssignable for RistrettoPoint {
/// # /// #
/// # use subtle::ConditionallyAssignable; /// # use subtle::ConditionallyAssignable;
/// # /// #
/// # use curve25519_dalek::edwards::Identity; /// # use curve25519_dalek::traits::Identity;
/// # use curve25519_dalek::ristretto::RistrettoPoint; /// # use curve25519_dalek::ristretto::RistrettoPoint;
/// # use curve25519_dalek::constants; /// # use curve25519_dalek::constants;
/// # fn main() { /// # fn main() {
@ -1032,8 +1041,7 @@ mod test {
use scalar::Scalar; use scalar::Scalar;
use constants; use constants;
use edwards::CompressedEdwardsY; use edwards::CompressedEdwardsY;
use edwards::Identity; use traits::{Identity, ValidityCheck};
use edwards::ValidityCheck;
use super::*; use super::*;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
@ -1133,6 +1141,7 @@ mod test {
} }
#[test] #[test]
#[cfg(feature="precomputed_tables")]
fn four_torsion_random() { fn four_torsion_random() {
let mut rng = OsRng::new().unwrap(); let mut rng = OsRng::new().unwrap();
let B = &constants::RISTRETTO_BASEPOINT_TABLE; let B = &constants::RISTRETTO_BASEPOINT_TABLE;
@ -1195,6 +1204,7 @@ mod test {
} }
#[test] #[test]
#[cfg(feature="precomputed_tables")]
fn random_roundtrip() { fn random_roundtrip() {
let mut rng = OsRng::new().unwrap(); let mut rng = OsRng::new().unwrap();
let B = &constants::RISTRETTO_BASEPOINT_TABLE; let B = &constants::RISTRETTO_BASEPOINT_TABLE;
@ -1227,6 +1237,7 @@ mod bench {
use super::*; use super::*;
#[bench] #[bench]
#[cfg(feature="precomputed_tables")]
fn decompression(b: &mut Bencher) { fn decompression(b: &mut Bencher) {
let mut rng = OsRng::new().unwrap(); let mut rng = OsRng::new().unwrap();
let B = &constants::RISTRETTO_BASEPOINT_TABLE; let B = &constants::RISTRETTO_BASEPOINT_TABLE;
@ -1236,6 +1247,7 @@ mod bench {
} }
#[bench] #[bench]
#[cfg(feature="precomputed_tables")]
fn compression(b: &mut Bencher) { fn compression(b: &mut Bencher) {
let mut rng = OsRng::new().unwrap(); let mut rng = OsRng::new().unwrap();
let B = &constants::RISTRETTO_BASEPOINT_TABLE; let B = &constants::RISTRETTO_BASEPOINT_TABLE;

View file

@ -10,30 +10,14 @@
// - Henry de Valence <hdevalence@hdevalence.ca> // - Henry de Valence <hdevalence@hdevalence.ca>
// - Brian Smith <brian@briansmith.org> // - Brian Smith <brian@briansmith.org>
//! Arithmetic for scalar multiplication. //! Arithmetic on scalars (integers mod the group order).
//!
//! The Ed25519 basepoint P has prime order
//!
//! l = 2^252 + 27742317777372353535851937790883648493.
//!
//! Thus a multiple `aP` of the basepoint (with a ∈ ℤ) depends only
//! on the value of `a (mod l)`, or equivalently, the image of `a` in
//! the quotient ℤ/lℤ.
//!
//! The `Scalar` struct represents an element in ℤ/lℤ.
//!
//! In contrast to `FieldElement`s, `Scalar`s are stored in
//! memory as bytes, allowing easy access to the bits of the `Scalar`
//! when multiplying a point by a scalar. For efficient arithmetic
//! between two scalars, the `UnpackedScalar` struct (internally
//! either `Scalar32` or `Scalar64`) is stored as limbs.
use core::fmt::Debug; use core::fmt::Debug;
use core::ops::Neg; use core::ops::Neg;
use core::ops::{Add, AddAssign}; use core::ops::{Add, AddAssign};
use core::ops::{Sub, SubAssign}; use core::ops::{Sub, SubAssign};
use core::ops::{Mul, MulAssign}; use core::ops::{Mul, MulAssign};
use core::ops::{Index, IndexMut}; use core::ops::{Index};
use core::cmp::{Eq, PartialEq}; use core::cmp::{Eq, PartialEq};
#[cfg(feature = "std")] #[cfg(feature = "std")]
@ -46,17 +30,116 @@ use subtle::slices_equal;
use subtle::ConditionallyAssignable; use subtle::ConditionallyAssignable;
use subtle::Equal; use subtle::Equal;
/// The `Scalar` struct represents an element in ℤ/lℤ, where use backend;
use constants;
/// An `UnpackedScalar` represents an element of the field GF(l), optimized for speed.
/// ///
/// l = 2^252 + 27742317777372353535851937790883648493 /// This is a type alias for one of the scalar types in the `backend`
/// module.
#[cfg(feature="radix_51")]
type UnpackedScalar = backend::u64::scalar::Scalar64;
/// An `UnpackedScalar` represents an element of the field GF(l), optimized for speed.
/// ///
/// is the order of the basepoint. The `Scalar` is stored as bytes. /// This is a type alias for one of the scalar types in the `backend`
/// module.
#[cfg(not(feature="radix_51"))]
type UnpackedScalar = backend::u32::scalar::Scalar32;
/// The `Scalar` struct holds an integer \\(s < 2\^{255} \\) which
/// represents an element of \\(\mathbb Z / \ell\\).
///
/// Both the Ristretto group and the Ed25519 basepoint have prime order
/// \\( \ell = 2\^{252} + 27742317777372353535851937790883648493 \\).
///
/// The code is intended to be useful with both the Ristretto group
/// (where everything is done modulo \\( \ell \\)), and the X/Ed25519
/// setting, which mandates specific bit-twiddles that are not
/// well-defined modulo \\( \ell \\).
///
/// To create a `Scalar` from a supposedly canonical encoding, use
/// `Scalar::from_canonical_bytes`.
///
/// To create a `Scalar` by reducing a \\(256\\)-bit integer mod \\( \ell \\),
/// use `Scalar::from_bytes_mod_order`.
///
/// To create a `Scalar` by reducing a \\(512\\)-bit integer mod \\( \ell \\),
/// use `Scalar::from_bytes_mod_order_wide`.
///
/// To create a `Scalar` with a specific bit-pattern (e.g., for
/// compatibility with X25519 "clamping"), use `Scalar::from_bits`.
///
/// All arithmetic on `Scalars` is done modulo \\( \ell \\).
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct Scalar(pub [u8; 32]); pub struct Scalar {
/// `bytes` is a little-endian byte encoding of an integer representing a scalar modulo the group order.
///
/// # Invariant
///
/// The integer representing this scalar must be bounded above by \\(2\^{255}\\), or equivalently the high bit of `bytes[31]` must be zero.
///
// XXX This is pub(crate) so we can write literal constants. If const fns were stable, we could make the Scalar constructors const fns and use those instead.
pub(crate) bytes: [u8; 32],
}
impl Scalar {
/// Construct a `Scalar` by reducing a 256-bit little-endian integer
/// modulo the group order \\( \ell \\).
pub fn from_bytes_mod_order(bytes: [u8; 32]) -> Scalar {
// Temporarily allow s_unreduced.bytes > 2^255 ...
let s_unreduced = Scalar{bytes: bytes};
// Then reduce mod the group order and return the reduced representative.
let s = s_unreduced.reduce();
debug_assert_eq!(0u8, s[31] >> 7);
s
}
/// Construct a `Scalar` by reducing a 512-bit little-endian integer
/// modulo the group order \\( \ell \\).
pub fn from_bytes_mod_order_wide(input: &[u8; 64]) -> Scalar {
UnpackedScalar::from_bytes_wide(input).pack()
}
/// Attempt to construct a `Scalar` from a canonical byte representation.
///
/// # Return
///
/// - `Some(s)`, where `s` is the `Scalar` corresponding to `bytes`,
/// if `bytes` is a canonical byte representation;
/// - `None` if `bytes` is not a canonical byte representation.
pub fn from_canonical_bytes(bytes: [u8; 32]) -> Option<Scalar> {
// Check that the high bit is not set
if (bytes[31] >> 7) != 0u8 { return None; }
let candidate = Scalar::from_bits(bytes);
if candidate.is_canonical() {
Some(candidate)
} else {
None
}
}
/// Construct a `Scalar` from the low 255 bits of a 256-bit integer.
///
/// This function is intended for applications like X25519 which
/// require specific bit-patterns when performing scalar
/// multiplication.
pub fn from_bits(bytes: [u8; 32]) -> Scalar {
let mut s = Scalar{bytes: bytes};
// Ensure that s < 2^255 by masking the high bit
s.bytes[31] &= 0b0111_1111;
s
}
}
impl Debug for Scalar { impl Debug for Scalar {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "Scalar: {:?}", &self.0[..]) write!(f, "Scalar{{\n\tbytes: {:?},\n}}", &self.bytes)
} }
} }
@ -73,7 +156,7 @@ impl PartialEq for Scalar {
/// ///
/// True if they are equal, and false otherwise. /// True if they are equal, and false otherwise.
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
slices_equal(&self.0, &other.0) == 1u8 slices_equal(&self.bytes, &other.bytes) == 1u8
} }
} }
@ -84,67 +167,62 @@ impl Equal for Scalar {
/// ///
/// `1u8` if they are equal, and `0u8` otherwise. /// `1u8` if they are equal, and `0u8` otherwise.
fn ct_eq(&self, other: &Self) -> u8 { fn ct_eq(&self, other: &Self) -> u8 {
slices_equal(&self.0, &other.0) slices_equal(&self.bytes, &other.bytes)
} }
} }
impl Index<usize> for Scalar { impl Index<usize> for Scalar {
type Output = u8; type Output = u8;
/// Index the bytes of the representative for this `Scalar`. Mutation is not permitted.
fn index(&self, _index: usize) -> &u8 { fn index(&self, _index: usize) -> &u8 {
&(self.0[_index]) &(self.bytes[_index])
}
}
impl IndexMut<usize> for Scalar {
fn index_mut(&mut self, _index: usize) -> &mut u8 {
&mut (self.0[_index])
} }
} }
impl<'b> MulAssign<&'b Scalar> for Scalar { impl<'b> MulAssign<&'b Scalar> for Scalar {
fn mul_assign(&mut self, _rhs: &'b Scalar) { fn mul_assign(&mut self, _rhs: &'b Scalar) {
*self = Scalar::mul(self, _rhs) *self = UnpackedScalar::mul(&self.unpack(), &_rhs.unpack()).pack();
} }
} }
impl<'a, 'b> Mul<&'b Scalar> for &'a Scalar { impl<'a, 'b> Mul<&'b Scalar> for &'a Scalar {
type Output = Scalar; type Output = Scalar;
fn mul(self, _rhs: &'b Scalar) -> Scalar { fn mul(self, _rhs: &'b Scalar) -> Scalar {
Scalar::mul(self, _rhs) UnpackedScalar::mul(&self.unpack(), &_rhs.unpack()).pack()
} }
} }
impl<'b> AddAssign<&'b Scalar> for Scalar { impl<'b> AddAssign<&'b Scalar> for Scalar {
fn add_assign(&mut self, _rhs: &'b Scalar) { fn add_assign(&mut self, _rhs: &'b Scalar) {
*self = Scalar::add(self, _rhs); *self = UnpackedScalar::add(&self.unpack(), &_rhs.unpack()).pack();
} }
} }
impl<'a, 'b> Add<&'b Scalar> for &'a Scalar { impl<'a, 'b> Add<&'b Scalar> for &'a Scalar {
type Output = Scalar; type Output = Scalar;
fn add(self, _rhs: &'b Scalar) -> Scalar { fn add(self, _rhs: &'b Scalar) -> Scalar {
Scalar::add(self, _rhs) UnpackedScalar::add(&self.unpack(), &_rhs.unpack()).pack()
} }
} }
impl<'b> SubAssign<&'b Scalar> for Scalar { impl<'b> SubAssign<&'b Scalar> for Scalar {
fn sub_assign(&mut self, _rhs: &'b Scalar) { fn sub_assign(&mut self, _rhs: &'b Scalar) {
*self = Scalar::sub(self, _rhs); *self = UnpackedScalar::sub(&self.unpack(), &_rhs.unpack()).pack();
} }
} }
impl<'a, 'b> Sub<&'b Scalar> for &'a Scalar { impl<'a, 'b> Sub<&'b Scalar> for &'a Scalar {
type Output = Scalar; type Output = Scalar;
fn sub(self, _rhs: &'b Scalar) -> Scalar { fn sub(self, _rhs: &'b Scalar) -> Scalar {
Scalar::sub(self, _rhs) UnpackedScalar::sub(&self.unpack(), &_rhs.unpack()).pack()
} }
} }
impl<'a> Neg for &'a Scalar { impl<'a> Neg for &'a Scalar {
type Output = Scalar; type Output = Scalar;
fn neg(self) -> Scalar { fn neg(self) -> Scalar {
Scalar::sub(&Scalar::zero(), self) &Scalar::zero() - self
} }
} }
@ -157,10 +235,8 @@ impl ConditionallyAssignable for Scalar {
/// # use curve25519_dalek::scalar::Scalar; /// # use curve25519_dalek::scalar::Scalar;
/// # use subtle::ConditionallyAssignable; /// # use subtle::ConditionallyAssignable;
/// # fn main() { /// # fn main() {
/// let a = Scalar([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /// let a = Scalar::from_bits([0u8;32]);
/// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); /// let b = Scalar::from_bits([1u8;32]);
/// let b = Scalar([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/// 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]);
/// let mut t = a; /// let mut t = a;
/// t.conditional_assign(&b, 0u8); /// t.conditional_assign(&b, 0u8);
/// assert!(t[0] == a[0]); /// assert!(t[0] == a[0]);
@ -178,7 +254,7 @@ impl ConditionallyAssignable for Scalar {
// if choice = 1u8, mask = (-1i8) as u8 = 11111111 // if choice = 1u8, mask = (-1i8) as u8 = 11111111
let mask = -(choice as i8) as u8; let mask = -(choice as i8) as u8;
for i in 0..32 { for i in 0..32 {
self[i] ^= mask & (self[i] ^ other[i]); self.bytes[i] ^= mask & (self.bytes[i] ^ other.bytes[i]);
} }
} }
} }
@ -193,7 +269,7 @@ impl Serialize for Scalar {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer where S: Serializer
{ {
serializer.serialize_bytes(self.as_bytes()) serializer.serialize_bytes(self.reduce().as_bytes())
} }
} }
@ -208,15 +284,25 @@ impl<'de> Deserialize<'de> for Scalar {
type Value = Scalar; type Value = Scalar;
fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
formatter.write_str("a 32-byte scalar value") formatter.write_str("a canonically-encoded 32-byte scalar value")
} }
fn visit_bytes<E>(self, v: &[u8]) -> Result<Scalar, E> fn visit_bytes<E>(self, v: &[u8]) -> Result<Scalar, E>
where E: serde::de::Error where E: serde::de::Error
{ {
if v.len() == 32 { if v.len() == 32 {
// array_ref turns &[u8] into &[u8;32] let mut bytes = [0u8;32];
Ok(Scalar(*array_ref!(v, 0, 32))) bytes.copy_from_slice(v);
static ERRMSG: &'static str = "encoding was not canonical";
Scalar::from_canonical_bytes(bytes)
.ok_or(
serde::de::Error::invalid_value(
serde::de::Unexpected::Bytes(v),
&ERRMSG,
)
)
} else { } else {
Err(serde::de::Error::invalid_length(v.len(), &self)) Err(serde::de::Error::invalid_length(v.len(), &self))
} }
@ -227,18 +313,6 @@ impl<'de> Deserialize<'de> for Scalar {
} }
} }
/// An `UnpackedScalar` represents an element of the field GF(l), optimized for speed.
#[cfg(feature="radix_51")]
type UnpackedScalar = Scalar64;
#[cfg(feature="radix_51")]
use scalar_64bit::*;
/// An `UnpackedScalar` represents an element of the field GF(l), optimized for speed.
#[cfg(not(feature="radix_51"))]
type UnpackedScalar = Scalar32;
#[cfg(not(feature="radix_51"))]
use scalar_32bit::*;
impl Scalar { impl Scalar {
/// Return a `Scalar` chosen uniformly at random using a user-provided RNG. /// Return a `Scalar` chosen uniformly at random using a user-provided RNG.
/// ///
@ -253,7 +327,7 @@ impl Scalar {
pub fn random<T: Rng>(rng: &mut T) -> Self { pub fn random<T: Rng>(rng: &mut T) -> Self {
let mut scalar_bytes = [0u8; 64]; let mut scalar_bytes = [0u8; 64];
rng.fill_bytes(&mut scalar_bytes); rng.fill_bytes(&mut scalar_bytes);
Scalar::reduce(&scalar_bytes) Scalar::from_bytes_mod_order_wide(&scalar_bytes)
} }
/// Hash a slice of bytes into a scalar. /// Hash a slice of bytes into a scalar.
@ -298,32 +372,41 @@ impl Scalar {
// XXX this seems clumsy // XXX this seems clumsy
let mut output = [0u8; 64]; let mut output = [0u8; 64];
output.copy_from_slice(hash.result().as_slice()); output.copy_from_slice(hash.result().as_slice());
Scalar::reduce(&output) Scalar::from_bytes_mod_order_wide(&output)
}
/// Convert this `Scalar` to its underlying sequence of bytes.
pub fn to_bytes(&self) -> [u8; 32] {
self.bytes
} }
/// View this `Scalar` as a sequence of bytes. /// View this `Scalar` as a sequence of bytes.
pub fn as_bytes(&self) -> &[u8; 32] { pub fn as_bytes(&self) -> &[u8; 32] {
&self.0 &self.bytes
} }
/// Construct the additive identity /// Construct the scalar \\( 0 \\).
pub fn zero() -> Self { pub fn zero() -> Self {
Scalar([0u8; 32]) Scalar { bytes: [0u8; 32]}
} }
/// Construct the multiplicative identity /// Construct the scalar \\( 1 \\).
pub fn one() -> Self { pub fn one() -> Self {
Scalar([ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Scalar {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) bytes: [
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
}
} }
/// Construct a scalar from the given `u64`. /// Construct a scalar from the given `u64`.
pub fn from_u64(x: u64) -> Scalar { pub fn from_u64(x: u64) -> Scalar {
let mut s = Scalar::zero(); let mut s_bytes = [0u8; 32];
for i in 0..8 { for i in 0..8 {
s[i] = (x >> (i*8)) as u8; s_bytes[i] = (x >> (i*8)) as u8;
} }
s Scalar{ bytes: s_bytes }
} }
/// Compute the multiplicative inverse of this scalar. /// Compute the multiplicative inverse of this scalar.
@ -332,28 +415,31 @@ impl Scalar {
} }
/// Get the bits of the scalar. /// Get the bits of the scalar.
pub fn bits(&self) -> [i8; 256] { pub(crate) fn bits(&self) -> [i8; 256] {
let mut bits = [0i8; 256]; let mut bits = [0i8; 256];
for i in 0..256 { for i in 0..256 {
// As i runs from 0..256, the bottom 3 bits index the bit, // As i runs from 0..256, the bottom 3 bits index the bit,
// while the upper bits index the byte. // while the upper bits index the byte.
bits[i] = ((self.0[i>>3] >> (i&7)) & 1u8) as i8; bits[i] = ((self.bytes[i>>3] >> (i&7)) & 1u8) as i8;
} }
bits bits
} }
/// Compute a width-5 "Non-Adjacent Form" of this scalar. /// Compute a width-5 "Non-Adjacent Form" of this scalar.
/// ///
/// A width-`w` NAF of a positive integer `k` is an expression /// A width-\\(w\\) NAF of a positive integer \\(k\\) is an expression
/// `k = sum(k[i]*2^i for i in range(l))`, where each nonzero /// $$
/// coefficient `k[i]` is odd and bounded by `|k[i]| < 2^(w-1)`, /// k = \sum_{i=0}\^n k\_i 2\^i,
/// `k[l-1]` is nonzero, and at most one of any `w` consecutive /// $$
/// where each nonzero
/// coefficient \\(k\_i\\) is odd and bounded by \\(|k\_i| < 2\^{w-1}\\),
/// \\(k\_{n-1}\\) is nonzero, and at most one of any \\(w\\) consecutive
/// coefficients is nonzero. (Hankerson, Menezes, Vanstone; def 3.32). /// coefficients is nonzero. (Hankerson, Menezes, Vanstone; def 3.32).
/// ///
/// Intuitively, this is like a binary expansion, except that we /// Intuitively, this is like a binary expansion, except that we
/// allow some coefficients to grow up to `2^(w-1)` so that the /// allow some coefficients to grow up to \\(2\^{w-1}\\) so that the
/// nonzero coefficients are as sparse as possible. /// nonzero coefficients are as sparse as possible.
pub fn non_adjacent_form(&self) -> [i8; 256] { pub(crate) fn non_adjacent_form(&self) -> [i8; 256] {
// Step 1: write out bits of the scalar // Step 1: write out bits of the scalar
let mut naf = self.bits(); let mut naf = self.bits();
@ -389,16 +475,13 @@ impl Scalar {
naf naf
} }
/// Write this scalar in radix 16, with coefficients in `[-8,8)`, /// Write this scalar in radix 16, with coefficients in \\([-8,8)\\),
/// i.e., compute `a_i` such that /// i.e., compute \\(a\_i\\) such that
/// /// $$
/// a = a_0 + a_1*16^1 + ... + a_63*16^63, /// a = a\_0 + a\_1 16\^1 + \cdots + a_{63} 16\^{63},
/// /// $$
/// with `-8 ≤ a_i < 8` for `0 ≤ i < 63` and `-8 ≤ a_63 ≤ 8`. /// with \\(-8 \leq a_i < 8\\) for \\(0 \leq i < 63\\) and \\(-8 \leq a_63 \leq 8\\).
/// pub(crate) fn to_radix_16(&self) -> [i8; 64] {
/// Precondition: self[31] <= 127. This is the case whenever
/// `self` is reduced.
pub fn to_radix_16(&self) -> [i8; 64] {
debug_assert!(self[31] <= 127); debug_assert!(self[31] <= 127);
let mut output = [0i8; 64]; let mut output = [0i8; 64];
@ -427,41 +510,46 @@ impl Scalar {
output output
} }
/// Unpack this `Scalar` to an `UnpackedScalar` /// Unpack this `Scalar` to an `UnpackedScalar` for faster arithmetic.
pub fn unpack(&self) -> UnpackedScalar { pub(crate) fn unpack(&self) -> UnpackedScalar {
UnpackedScalar::from_bytes(&self.0) UnpackedScalar::from_bytes(&self.bytes)
} }
/// Compute `a + b` (mod l) /// Reduce this `Scalar` modulo \\(\ell\\).
pub fn add(a: &Scalar, b: &Scalar) -> Scalar { pub fn reduce(&self) -> Scalar {
UnpackedScalar::add(&a.unpack(), &b.unpack()).pack() let x = self.unpack();
let xR = UnpackedScalar::mul_internal(&x, &constants::R);
let x_mod_l = UnpackedScalar::montgomery_reduce(&xR);
x_mod_l.pack()
} }
/// Compute `a - b` (mod l). /// Check whether this `Scalar` is the canonical representative mod \\(\ell\\).
pub fn sub(a: &Scalar, b: &Scalar) -> Scalar { ///
UnpackedScalar::sub(&a.unpack(), &b.unpack()).pack() /// This is intended for uses like input validation, where variable-time code is acceptable.
} ///
/// ```
/// Compute `a * b` (mod l). /// # extern crate curve25519_dalek;
pub fn mul(a: &Scalar, b: &Scalar) -> Scalar { /// # extern crate subtle;
UnpackedScalar::mul(&a.unpack(), &b.unpack()).pack() /// # use curve25519_dalek::scalar::Scalar;
} /// # use subtle::ConditionallyAssignable;
/// # fn main() {
/// Compute `(a * b) + c` (mod l). /// // 2^255 - 1, since `from_bits` clears the high bit
pub fn multiply_add(a: &Scalar, b: &Scalar, c: &Scalar) -> Scalar { /// let _2_255_minus_1 = Scalar::from_bits([0xff;32]);
UnpackedScalar::add(&UnpackedScalar::mul(&a.unpack(), &b.unpack()), &c.unpack()).pack() /// assert!(!_2_255_minus_1.is_canonical());
} ///
/// let reduced = _2_255_minus_1.reduce();
/// Reduce a 512-bit little endian number mod l /// assert!(reduced.is_canonical());
pub fn reduce(input: &[u8; 64]) -> Scalar { /// # }
UnpackedScalar::from_bytes_wide(input).pack() /// ```
pub fn is_canonical(&self) -> bool {
*self == self.reduce()
} }
} }
impl UnpackedScalar { impl UnpackedScalar {
/// Pack the limbs of this `UnpackedScalar` into a `Scalar`. /// Pack the limbs of this `UnpackedScalar` into a `Scalar`.
fn pack(&self) -> Scalar { fn pack(&self) -> Scalar {
Scalar(self.to_bytes()) Scalar{ bytes: self.to_bytes() }
} }
/// Compute the multiplicative inverse of this scalar. /// Compute the multiplicative inverse of this scalar.
@ -529,48 +617,81 @@ mod test {
use constants; use constants;
/// x = 2238329342913194256032495932344128051776374960164957527413114840482143558222 /// x = 2238329342913194256032495932344128051776374960164957527413114840482143558222
pub static X: Scalar = Scalar( pub static X: Scalar = Scalar{
[0x4e, 0x5a, 0xb4, 0x34, 0x5d, 0x47, 0x08, 0x84, bytes: [
0x4e, 0x5a, 0xb4, 0x34, 0x5d, 0x47, 0x08, 0x84,
0x59, 0x13, 0xb4, 0x64, 0x1b, 0xc2, 0x7d, 0x52, 0x59, 0x13, 0xb4, 0x64, 0x1b, 0xc2, 0x7d, 0x52,
0x52, 0xa5, 0x85, 0x10, 0x1b, 0xcc, 0x42, 0x44, 0x52, 0xa5, 0x85, 0x10, 0x1b, 0xcc, 0x42, 0x44,
0xd4, 0x49, 0xf4, 0xa8, 0x79, 0xd9, 0xf2, 0x04]); 0xd4, 0x49, 0xf4, 0xa8, 0x79, 0xd9, 0xf2, 0x04,
],
};
/// 1/x = 6859937278830797291664592131120606308688036382723378951768035303146619657244 /// 1/x = 6859937278830797291664592131120606308688036382723378951768035303146619657244
pub static XINV: Scalar = Scalar( pub static XINV: Scalar = Scalar{
[0x1c, 0xdc, 0x17, 0xfc, 0xe0, 0xe9, 0xa5, 0xbb, bytes: [
0x1c, 0xdc, 0x17, 0xfc, 0xe0, 0xe9, 0xa5, 0xbb,
0xd9, 0x24, 0x7e, 0x56, 0xbb, 0x01, 0x63, 0x47, 0xd9, 0x24, 0x7e, 0x56, 0xbb, 0x01, 0x63, 0x47,
0xbb, 0xba, 0x31, 0xed, 0xd5, 0xa9, 0xbb, 0x96, 0xbb, 0xba, 0x31, 0xed, 0xd5, 0xa9, 0xbb, 0x96,
0xd5, 0x0b, 0xcd, 0x7a, 0x3f, 0x96, 0x2a, 0x0f]); 0xd5, 0x0b, 0xcd, 0x7a, 0x3f, 0x96, 0x2a, 0x0f,
],
};
/// y = 2592331292931086675770238855846338635550719849568364935475441891787804997264 /// y = 2592331292931086675770238855846338635550719849568364935475441891787804997264
pub static Y: Scalar = Scalar( pub static Y: Scalar = Scalar{
[0x90, 0x76, 0x33, 0xfe, 0x1c, 0x4b, 0x66, 0xa4, bytes: [
0x90, 0x76, 0x33, 0xfe, 0x1c, 0x4b, 0x66, 0xa4,
0xa2, 0x8d, 0x2d, 0xd7, 0x67, 0x83, 0x86, 0xc3, 0xa2, 0x8d, 0x2d, 0xd7, 0x67, 0x83, 0x86, 0xc3,
0x53, 0xd0, 0xde, 0x54, 0x55, 0xd4, 0xfc, 0x9d, 0x53, 0xd0, 0xde, 0x54, 0x55, 0xd4, 0xfc, 0x9d,
0xe8, 0xef, 0x7a, 0xc3, 0x1f, 0x35, 0xbb, 0x05]); 0xe8, 0xef, 0x7a, 0xc3, 0x1f, 0x35, 0xbb, 0x05,
],
};
/// z = 5033871415930814945849241457262266927579821285980625165479289807629491019013 /// z = 5033871415930814945849241457262266927579821285980625165479289807629491019013
pub static Z: Scalar = Scalar( pub static Z: Scalar = Scalar{
[0x05, 0x9d, 0x3e, 0x0b, 0x09, 0x26, 0x50, 0x3d, bytes: [
0x05, 0x9d, 0x3e, 0x0b, 0x09, 0x26, 0x50, 0x3d,
0xa3, 0x84, 0xa1, 0x3c, 0x92, 0x7a, 0xc2, 0x06, 0xa3, 0x84, 0xa1, 0x3c, 0x92, 0x7a, 0xc2, 0x06,
0x41, 0x98, 0xcf, 0x34, 0x3a, 0x24, 0xd5, 0xb7, 0x41, 0x98, 0xcf, 0x34, 0x3a, 0x24, 0xd5, 0xb7,
0xeb, 0x33, 0x6a, 0x2d, 0xfc, 0x11, 0x21, 0x0b]); 0xeb, 0x33, 0x6a, 0x2d, 0xfc, 0x11, 0x21, 0x0b,
],
};
/// w = 3486911242272497535104403593250518247409663771668155364040899665266216860804 /// w = 3486911242272497535104403593250518247409663771668155364040899665266216860804
static W: Scalar = Scalar( static W: Scalar = Scalar{
[0x84, 0xfc, 0xbc, 0x4f, 0x78, 0x12, 0xa0, 0x06, bytes: [
0x84, 0xfc, 0xbc, 0x4f, 0x78, 0x12, 0xa0, 0x06,
0xd7, 0x91, 0xd9, 0x7a, 0x3a, 0x27, 0xdd, 0x1e, 0xd7, 0x91, 0xd9, 0x7a, 0x3a, 0x27, 0xdd, 0x1e,
0x21, 0x43, 0x45, 0xf7, 0xb1, 0xb9, 0x56, 0x7a, 0x21, 0x43, 0x45, 0xf7, 0xb1, 0xb9, 0x56, 0x7a,
0x81, 0x30, 0x73, 0x44, 0x96, 0x85, 0xb5, 0x07]); 0x81, 0x30, 0x73, 0x44, 0x96, 0x85, 0xb5, 0x07,
],
};
/// x*y = 5690045403673944803228348699031245560686958845067437804563560795922180092780 /// x*y = 5690045403673944803228348699031245560686958845067437804563560795922180092780
static X_TIMES_Y: Scalar = Scalar( static X_TIMES_Y: Scalar = Scalar{
[0x6c, 0x33, 0x74, 0xa1, 0x89, 0x4f, 0x62, 0x21, bytes: [
0x6c, 0x33, 0x74, 0xa1, 0x89, 0x4f, 0x62, 0x21,
0x0a, 0xaa, 0x2f, 0xe1, 0x86, 0xa6, 0xf9, 0x2c, 0x0a, 0xaa, 0x2f, 0xe1, 0x86, 0xa6, 0xf9, 0x2c,
0xe0, 0xaa, 0x75, 0xc2, 0x77, 0x95, 0x81, 0xc2, 0xe0, 0xaa, 0x75, 0xc2, 0x77, 0x95, 0x81, 0xc2,
0x95, 0xfc, 0x08, 0x17, 0x9a, 0x73, 0x94, 0x0c]); 0x95, 0xfc, 0x08, 0x17, 0x9a, 0x73, 0x94, 0x0c,
],
};
static A_SCALAR: Scalar = Scalar([ /// sage: l = 2^252 + 27742317777372353535851937790883648493
/// sage: big = 2^256 - 1
/// sage: repr((big % l).digits(256))
static CANONICAL_2_256_MINUS_1: Scalar = Scalar{
bytes: [
28, 149, 152, 141, 116, 49, 236, 214,
112, 207, 125, 115, 244, 91, 239, 198,
254, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 15,
],
};
static A_SCALAR: Scalar = Scalar{
bytes: [
0x1a, 0x0e, 0x97, 0x8a, 0x90, 0xf6, 0x62, 0x2d, 0x1a, 0x0e, 0x97, 0x8a, 0x90, 0xf6, 0x62, 0x2d,
0x37, 0x47, 0x02, 0x3f, 0x8a, 0xd8, 0x26, 0x4d, 0x37, 0x47, 0x02, 0x3f, 0x8a, 0xd8, 0x26, 0x4d,
0xa7, 0x58, 0xaa, 0x1b, 0x88, 0xe0, 0x40, 0xd1, 0xa7, 0x58, 0xaa, 0x1b, 0x88, 0xe0, 0x40, 0xd1,
0x58, 0x9e, 0x7b, 0x7f, 0x23, 0x76, 0xef, 0x09]); 0x58, 0x9e, 0x7b, 0x7f, 0x23, 0x76, 0xef, 0x09,
],
};
static A_NAF: [i8; 256] = static A_NAF: [i8; 256] =
[0,13,0,0,0,0,0,0,0,7,0,0,0,0,0,0,-9,0,0,0,0,-11,0,0,0,0,3,0,0,0,0,1, [0,13,0,0,0,0,0,0,0,7,0,0,0,0,0,0,-9,0,0,0,0,-11,0,0,0,0,3,0,0,0,0,1,
@ -591,19 +712,19 @@ mod test {
// LE bytes of 6432735165214683820902750800207468552549813371247423777071615116673864412038 // LE bytes of 6432735165214683820902750800207468552549813371247423777071615116673864412038
let c_bytes = [134, 171, 119, 216, 180, 128, 178, 62, 171, 132, 32, 62, 34, 119, 104, 193, 47, 215, 181, 250, 14, 207, 172, 93, 75, 207, 211, 103, 144, 204, 56, 14]; let c_bytes = [134, 171, 119, 216, 180, 128, 178, 62, 171, 132, 32, 62, 34, 119, 104, 193, 47, 215, 181, 250, 14, 207, 172, 93, 75, 207, 211, 103, 144, 204, 56, 14];
let a = Scalar(a_bytes); let a = Scalar::from_bytes_mod_order(a_bytes);
let b = Scalar(b_bytes); let b = Scalar::from_bytes_mod_order(b_bytes);
let c = Scalar(c_bytes); let c = Scalar::from_bytes_mod_order(c_bytes);
let mut tmp = [0u8; 64]; let mut tmp = [0u8; 64];
// also_a = (a mod l) // also_a = (a mod l)
tmp[0..32].copy_from_slice(&a_bytes[..]); tmp[0..32].copy_from_slice(&a_bytes[..]);
let also_a = Scalar::reduce(&tmp); let also_a = Scalar::from_bytes_mod_order_wide(&tmp);
// also_b = (b mod l) // also_b = (b mod l)
tmp[0..32].copy_from_slice(&b_bytes[..]); tmp[0..32].copy_from_slice(&b_bytes[..]);
let also_b = Scalar::reduce(&tmp); let also_b = Scalar::from_bytes_mod_order_wide(&tmp);
let expected_c = &a * &b; let expected_c = &a * &b;
let also_expected_c = &also_a * &also_b; let also_expected_c = &also_a * &also_b;
@ -636,9 +757,7 @@ mod test {
#[test] #[test]
fn scalar_multiply_by_one() { fn scalar_multiply_by_one() {
let one = Scalar::one(); let test_scalar = &X * &Scalar::one();
let zero = Scalar::zero();
let test_scalar = Scalar::multiply_add(&X, &one, &zero);
for i in 0..32 { for i in 0..32 {
assert!(test_scalar[i] == X[i]); assert!(test_scalar[i] == X[i]);
} }
@ -646,8 +765,7 @@ mod test {
#[test] #[test]
fn impl_add() { fn impl_add() {
let mut two = Scalar::zero(); two[0] = 2; let two = Scalar::from_u64(2);
let two = two;
let one = Scalar::one(); let one = Scalar::one();
let should_be_two = &one + &one; let should_be_two = &one + &one;
assert_eq!(should_be_two, two); assert_eq!(should_be_two, two);
@ -666,17 +784,9 @@ mod test {
assert_eq!(should_be_X_times_Y, X_TIMES_Y); assert_eq!(should_be_X_times_Y, X_TIMES_Y);
} }
#[test]
fn scalar_multiply_add() {
let test_scalar = Scalar::multiply_add(&X, &Y, &Z);
for i in 0..32 {
assert!(test_scalar[i] == W[i]);
}
}
#[test] #[test]
fn square() { fn square() {
let expected = Scalar::multiply_add(&X, &X, &Scalar::zero()); let expected = &X * &X;
let actual = X.unpack().square().pack(); let actual = X.unpack().square().pack();
for i in 0..32 { for i in 0..32 {
assert!(expected[i] == actual[i]); assert!(expected[i] == actual[i]);
@ -684,7 +794,13 @@ mod test {
} }
#[test] #[test]
fn scalar_reduce() { fn reduce() {
let biggest = Scalar::from_bytes_mod_order([0xff; 32]);
assert_eq!(biggest, CANONICAL_2_256_MINUS_1);
}
#[test]
fn from_bytes_mod_order_wide() {
let mut bignum = [0u8; 64]; let mut bignum = [0u8; 64];
// set bignum = x + 2^256x // set bignum = x + 2^256x
for i in 0..32 { for i in 0..32 {
@ -693,11 +809,15 @@ mod test {
} }
// 3958878930004874126169954872055634648693766179881526445624823978500314864344 // 3958878930004874126169954872055634648693766179881526445624823978500314864344
// = x + 2^256x (mod l) // = x + 2^256x (mod l)
let reduced = Scalar([216, 154, 179, 139, 210, 121, 2, 71, let reduced = Scalar{
bytes: [
216, 154, 179, 139, 210, 121, 2, 71,
69, 99, 158, 216, 23, 173, 63, 100, 69, 99, 158, 216, 23, 173, 63, 100,
204, 0, 91, 50, 219, 153, 57, 249, 204, 0, 91, 50, 219, 153, 57, 249,
28, 82, 31, 197, 100, 165, 192, 8]); 28, 82, 31, 197, 100, 165, 192, 8,
let test_red = Scalar::reduce(&bignum); ],
};
let test_red = Scalar::from_bytes_mod_order_wide(&bignum);
for i in 0..32 { for i in 0..32 {
assert!(test_red[i] == reduced[i]); assert!(test_red[i] == reduced[i]);
} }
@ -731,9 +851,8 @@ mod test {
assert_eq!(should_be_unpacked.0, unpacked.0); assert_eq!(should_be_unpacked.0, unpacked.0);
} }
#[test] #[test]
fn montgomery_reduce_matches_reduce() { fn montgomery_reduce_matches_from_bytes_mod_order_wide() {
let mut bignum = [0u8; 64]; let mut bignum = [0u8; 64];
// set bignum = x + 2^256x // set bignum = x + 2^256x
@ -743,14 +862,18 @@ mod test {
} }
// x + 2^256x (mod l) // x + 2^256x (mod l)
// = 3958878930004874126169954872055634648693766179881526445624823978500314864344 // = 3958878930004874126169954872055634648693766179881526445624823978500314864344
let expected = Scalar([216, 154, 179, 139, 210, 121, 2, 71, let expected = Scalar{
bytes: [
216, 154, 179, 139, 210, 121, 2, 71,
69, 99, 158, 216, 23, 173, 63, 100, 69, 99, 158, 216, 23, 173, 63, 100,
204, 0, 91, 50, 219, 153, 57, 249, 204, 0, 91, 50, 219, 153, 57, 249,
28, 82, 31, 197, 100, 165, 192, 8]); 28, 82, 31, 197, 100, 165, 192, 8
let reduced = Scalar::reduce(&bignum); ],
};
let reduced = Scalar::from_bytes_mod_order_wide(&bignum);
// The reduced scalar should match the expected // The reduced scalar should match the expected
assert_eq!(reduced.0, expected.0); assert_eq!(reduced.bytes, expected.bytes);
// (x + 2^256x) * R // (x + 2^256x) * R
let interim = UnpackedScalar::mul_internal(&UnpackedScalar::from_bytes_wide(&bignum), let interim = UnpackedScalar::mul_internal(&UnpackedScalar::from_bytes_wide(&bignum),
@ -763,12 +886,30 @@ mod test {
assert_eq!(montgomery_reduced.0, expected.unpack().0) assert_eq!(montgomery_reduced.0, expected.unpack().0)
} }
#[cfg(feature = "serde")] #[test]
use serde_cbor; fn canonical_decoding() {
// canonical encoding of 1667457891
let canonical_bytes = [99, 99, 99, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,];
// encoding of
// 7265385991361016183439748078976496179028704920197054998554201349516117938192
// = 28380414028753969466561515933501938171588560817147392552250411230663687203 (mod l)
// non_canonical because unreduced mod l
let non_canonical_bytes_because_unreduced = [16; 32];
// encoding with high bit set, to check that the parser isn't pre-masking the high bit
let non_canonical_bytes_because_highbit = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128];
assert!( Scalar::from_canonical_bytes(canonical_bytes).is_some() );
assert!( Scalar::from_canonical_bytes(non_canonical_bytes_because_unreduced).is_none() );
assert!( Scalar::from_canonical_bytes(non_canonical_bytes_because_highbit).is_none() );
}
#[test] #[test]
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
fn serde_cbor_scalar_roundtrip() { fn serde_cbor_scalar_roundtrip() {
// XXX remove serde_cbor
use serde_cbor;
let output = serde_cbor::to_vec(&X).unwrap(); let output = serde_cbor::to_vec(&X).unwrap();
let parsed: Scalar = serde_cbor::from_slice(&output).unwrap(); let parsed: Scalar = serde_cbor::from_slice(&output).unwrap();
assert_eq!(parsed, X); assert_eq!(parsed, X);
@ -783,6 +924,13 @@ mod bench {
use super::*; use super::*;
use super::test::{X}; use super::test::{X};
#[bench]
fn reduce(b: &mut Bencher) {
let unreduced = Scalar::from_bits([0xff; 32]);
b.iter(|| unreduced.reduce());
}
#[bench] #[bench]
fn scalar_random(b: &mut Bencher) { fn scalar_random(b: &mut Bencher) {
let mut csprng: OsRng = OsRng::new().unwrap(); let mut csprng: OsRng = OsRng::new().unwrap();

87
src/traits.rs Normal file
View file

@ -0,0 +1,87 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! Module for common traits.
use core::ops::Neg;
use subtle;
use subtle::ConditionallyAssignable;
use subtle::ConditionallyNegatable;
// ------------------------------------------------------------------------
// Public Traits
// ------------------------------------------------------------------------
/// Trait for getting the identity element of a point type.
pub trait Identity {
/// Returns the identity element of the curve.
/// Can be used as a constructor.
fn identity() -> Self;
}
/// Trait for testing if a curve point is equivalent to the identity point.
pub trait IsIdentity {
/// Return true if this element is the identity element of the curve.
fn is_identity(&self) -> bool;
}
/// Implement generic identity equality testing for a point representations
/// which have constant-time equality testing and a defined identity
/// constructor.
impl<T> IsIdentity for T where T: subtle::Equal + Identity {
fn is_identity(&self) -> bool {
self.ct_eq(&T::identity()) == 1u8
}
}
// ------------------------------------------------------------------------
// Private Traits
// ------------------------------------------------------------------------
/// Trait for checking whether a point is on the curve.
///
/// This trait is only for debugging/testing, since it should be
/// impossible for a `curve25519-dalek` user to construct an invalid
/// point.
pub(crate) trait ValidityCheck {
/// Checks whether the point is on the curve. Not CT.
fn is_valid(&self) -> bool;
}
// This isn't a trait, but it is fully generic...
/// Given precomputed points `[P, 2P, 3P, ..., 8P]`, as well as `-8 ≤
/// x ≤ 8`, compute `x * B` in constant time, i.e., without branching
/// on x or using it as an array index.
pub(crate) fn select_precomputed_point<T>(x: i8, points: &[T; 8]) -> T
where T: Identity + ConditionallyAssignable, for<'a> &'a T: Neg<Output=T>
{
debug_assert!(x >= -8); debug_assert!(x <= 8);
// Compute xabs = |x|
let xmask = x >> 7;
let xabs = (x + xmask) ^ xmask;
// Set t = 0 * P = identity
let mut t = T::identity();
for j in 1..9 {
// Copy `points[j-1] == j*P` onto `t` in constant time if `|x| == j`.
t.conditional_assign(&points[j-1],
subtle::bytes_equal(xabs as u8, j as u8));
}
// Now t == |x| * P.
let neg_mask = (xmask & 1) as u8;
t.conditional_negate(neg_mask);
// Now t == x * P.
t
}

View file

@ -1,44 +0,0 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! Miscellaneous common utility functions.
/// Convert an array of (at least) three bytes into an i64.
#[inline]
//#[allow(dead_code)]
pub fn load3(input: &[u8]) -> i64 {
(input[0] as i64)
| ((input[1] as i64) << 8)
| ((input[2] as i64) << 16)
}
/// Convert an array of (at least) four bytes into an i64.
#[inline]
//#[allow(dead_code)]
pub fn load4(input: &[u8]) -> i64 {
(input[0] as i64)
| ((input[1] as i64) << 8)
| ((input[2] as i64) << 16)
| ((input[3] as i64) << 24)
}
/// Convert an array of (at least) eight bytes into a u64.
#[inline]
//#[allow(dead_code)]
pub fn load8(input: &[u8]) -> u64 {
(input[0] as u64)
| ((input[1] as u64) << 8)
| ((input[2] as u64) << 16)
| ((input[3] as u64) << 24)
| ((input[4] as u64) << 32)
| ((input[5] as u64) << 40)
| ((input[6] as u64) << 48)
| ((input[7] as u64) << 56)
}