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
use super::ops;
use crate::{agreement, constant_time, ec, error, rand};
use untrusted;
static CURVE25519: ec::Curve = ec::Curve {
public_key_len: PUBLIC_KEY_LEN,
elem_and_scalar_len: ELEM_AND_SCALAR_LEN,
id: ec::CurveID::Curve25519,
check_private_key_bytes: x25519_check_private_key_bytes,
generate_private_key: x25519_generate_private_key,
public_from_private: x25519_public_from_private,
};
pub static X25519: agreement::Algorithm = agreement::Algorithm {
i: ec::AgreementAlgorithmImpl {
curve: &CURVE25519,
ecdh: x25519_ecdh,
},
};
fn x25519_check_private_key_bytes(bytes: &[u8]) -> Result<(), error::Unspecified> {
debug_assert_eq!(bytes.len(), PRIVATE_KEY_LEN);
Ok(())
}
fn x25519_generate_private_key(
rng: &rand::SecureRandom,
) -> Result<ec::PrivateKey, error::Unspecified> {
let mut result = ec::PrivateKey {
bytes: [0; ec::SCALAR_MAX_BYTES],
};
rng.fill(&mut result.bytes[..PRIVATE_KEY_LEN])?;
Ok(result)
}
fn x25519_public_from_private(
public_out: &mut [u8], private_key: &ec::PrivateKey,
) -> Result<(), error::Unspecified> {
let public_out = slice_as_array_ref_mut!(public_out, PUBLIC_KEY_LEN)?;
let private_key = slice_as_array_ref!(&private_key.bytes[..PRIVATE_KEY_LEN], PRIVATE_KEY_LEN)?;
unsafe {
GFp_x25519_public_from_private(public_out, private_key);
}
Ok(())
}
fn x25519_ecdh(
out: &mut [u8], my_private_key: &ec::PrivateKey, peer_public_key: untrusted::Input,
) -> Result<(), error::Unspecified> {
let out = slice_as_array_ref_mut!(out, SHARED_SECRET_LEN)?;
let my_private_key =
slice_as_array_ref!(&my_private_key.bytes[..PRIVATE_KEY_LEN], PRIVATE_KEY_LEN)?;
let peer_public_key =
slice_as_array_ref!(peer_public_key.as_slice_less_safe(), PUBLIC_KEY_LEN)?;
unsafe {
GFp_x25519_scalar_mult(out, my_private_key, peer_public_key);
}
let zeros: SharedSecret = [0; SHARED_SECRET_LEN];
if constant_time::verify_slices_are_equal(out, &zeros).is_ok() {
return Err(error::Unspecified);
}
Ok(())
}
const ELEM_AND_SCALAR_LEN: usize = ops::ELEM_LEN;
type PrivateKey = [u8; PRIVATE_KEY_LEN];
const PRIVATE_KEY_LEN: usize = ELEM_AND_SCALAR_LEN;
type PublicKey = [u8; PUBLIC_KEY_LEN];
const PUBLIC_KEY_LEN: usize = ELEM_AND_SCALAR_LEN;
type SharedSecret = [u8; SHARED_SECRET_LEN];
const SHARED_SECRET_LEN: usize = ELEM_AND_SCALAR_LEN;
extern "C" {
fn GFp_x25519_public_from_private(public_key_out: &mut PublicKey, private_key: &PrivateKey);
fn GFp_x25519_scalar_mult(
out: &mut ops::EncodedPoint, scalar: &ops::Scalar, point: &ops::EncodedPoint,
);
}