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
use crate::{error, init, rand};
use untrusted;
pub struct AgreementAlgorithmImpl {
pub curve: &'static Curve,
pub ecdh: fn(out: &mut [u8], private_key: &PrivateKey, peer_public_key: untrusted::Input)
-> Result<(), error::Unspecified>,
}
derive_debug_via_self!(AgreementAlgorithmImpl, self.curve);
impl PartialEq for AgreementAlgorithmImpl {
fn eq(&self, other: &Self) -> bool { self.curve.id == other.curve.id }
}
impl Eq for AgreementAlgorithmImpl {}
pub struct Curve {
pub public_key_len: usize,
pub elem_and_scalar_len: usize,
pub id: CurveID,
check_private_key_bytes: fn(bytes: &[u8]) -> Result<(), error::Unspecified>,
generate_private_key: fn(rng: &rand::SecureRandom) -> Result<PrivateKey, error::Unspecified>,
public_from_private:
fn(public_out: &mut [u8], private_key: &PrivateKey) -> Result<(), error::Unspecified>,
}
derive_debug_via_self!(Curve, self.id);
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CurveID {
Curve25519,
P256,
P384,
}
pub struct KeyPair {
pub private_key: PrivateKey,
pub public_key: [u8; PUBLIC_KEY_MAX_LEN],
}
pub struct PrivateKey {
bytes: [u8; SCALAR_MAX_BYTES],
}
impl PrivateKey {
pub fn generate(
curve: &Curve, rng: &rand::SecureRandom,
) -> Result<PrivateKey, error::Unspecified> {
init::init_once();
(curve.generate_private_key)(rng)
}
pub fn from_bytes(
curve: &Curve, bytes: untrusted::Input,
) -> Result<PrivateKey, error::Unspecified> {
init::init_once();
let bytes = bytes.as_slice_less_safe();
if curve.elem_and_scalar_len != bytes.len() {
return Err(error::Unspecified);
}
(curve.check_private_key_bytes)(bytes)?;
let mut r = PrivateKey {
bytes: [0; SCALAR_MAX_BYTES],
};
r.bytes[..curve.elem_and_scalar_len].copy_from_slice(bytes);
Ok(r)
}
pub fn bytes(&self, curve: &Curve) -> &[u8] { &self.bytes[..curve.elem_and_scalar_len] }
#[inline(always)]
pub fn compute_public_key(
&self, curve: &Curve, out: &mut [u8],
) -> Result<(), error::Unspecified> {
if out.len() != curve.public_key_len {
return Err(error::Unspecified);
}
(curve.public_from_private)(out, self)
}
}
const ELEM_MAX_BITS: usize = 384;
pub const ELEM_MAX_BYTES: usize = (ELEM_MAX_BITS + 7) / 8;
pub const SCALAR_MAX_BYTES: usize = ELEM_MAX_BYTES;
pub const PUBLIC_KEY_MAX_LEN: usize = 1 + (2 * ELEM_MAX_BYTES);
pub const PKCS8_DOCUMENT_MAX_LEN: usize = 40 + SCALAR_MAX_BYTES + PUBLIC_KEY_MAX_LEN;
pub mod curve25519;
pub mod suite_b;