1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
pub use super::scalar::{MaskedScalar, Scalar, SCALAR_LEN};
use crate::{
bssl, error,
limb::{Limb, LIMB_BITS},
};
use core::marker::PhantomData;
#[repr(C)]
pub struct Elem<E: Encoding> {
limbs: [Limb; ELEM_LIMBS],
encoding: PhantomData<E>,
}
pub trait Encoding {}
pub struct T;
impl Encoding for T {}
const ELEM_LIMBS: usize = 5 * 64 / LIMB_BITS;
impl<E: Encoding> Elem<E> {
fn zero() -> Self {
Self {
limbs: Default::default(),
encoding: PhantomData,
}
}
}
impl Elem<T> {
fn negate(&mut self) {
unsafe {
GFp_x25519_fe_neg(self);
}
}
}
pub type EncodedPoint = [u8; ELEM_LEN];
pub const ELEM_LEN: usize = 32;
#[repr(C)]
pub struct ExtPoint {
x: Elem<T>,
y: Elem<T>,
z: Elem<T>,
t: Elem<T>,
}
impl ExtPoint {
pub fn new_at_infinity() -> Self {
Self {
x: Elem::zero(),
y: Elem::zero(),
z: Elem::zero(),
t: Elem::zero(),
}
}
pub fn from_encoded_point_vartime(encoded: &EncodedPoint) -> Result<Self, error::Unspecified> {
let mut point = Self::new_at_infinity();
Result::from(unsafe { GFp_x25519_ge_frombytes_vartime(&mut point, encoded) })
.map(|()| point)
}
pub fn into_encoded_point(self) -> EncodedPoint {
encode_point(self.x, self.y, self.z)
}
pub fn invert_vartime(&mut self) {
self.x.negate();
self.t.negate();
}
}
#[repr(C)]
pub struct Point {
x: Elem<T>,
y: Elem<T>,
z: Elem<T>,
}
impl Point {
pub fn new_at_infinity() -> Self {
Self {
x: Elem::zero(),
y: Elem::zero(),
z: Elem::zero(),
}
}
pub fn into_encoded_point(self) -> EncodedPoint {
encode_point(self.x, self.y, self.z)
}
}
fn encode_point(x: Elem<T>, y: Elem<T>, z: Elem<T>) -> EncodedPoint {
let mut bytes = [0; ELEM_LEN];
let sign_bit: u8 = unsafe {
let mut recip = Elem::zero();
GFp_x25519_fe_invert(&mut recip, &z);
let mut x_over_z = Elem::zero();
GFp_x25519_fe_mul_ttt(&mut x_over_z, &x, &recip);
let mut y_over_z = Elem::zero();
GFp_x25519_fe_mul_ttt(&mut y_over_z, &y, &recip);
GFp_x25519_fe_tobytes(&mut bytes, &y_over_z);
GFp_x25519_fe_isnegative(&x_over_z)
};
bytes[ELEM_LEN - 1] ^= sign_bit << 7;
bytes
}
extern "C" {
fn GFp_x25519_fe_invert(out: &mut Elem<T>, z: &Elem<T>);
fn GFp_x25519_fe_isnegative(elem: &Elem<T>) -> u8;
fn GFp_x25519_fe_mul_ttt(h: &mut Elem<T>, f: &Elem<T>, g: &Elem<T>);
fn GFp_x25519_fe_neg(f: &mut Elem<T>);
fn GFp_x25519_fe_tobytes(bytes: &mut EncodedPoint, elem: &Elem<T>);
fn GFp_x25519_ge_frombytes_vartime(h: &mut ExtPoint, s: &EncodedPoint) -> bssl::Result;
}