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
use std::borrow::Cow;
use std::fmt::{self, Debug, Display, Formatter};
use std::os::raw::c_int;
use boringssl::{self, BoringError};
use util::Sealed;
use Error;
mod inner {
use Error;
use boringssl::{self, CRef};
use util::Sealed;
pub trait PCurve: Sized + Sealed {
fn nid() -> i32;
fn group() -> CRef<'static, boringssl::EC_GROUP> {
CRef::ec_group_new_by_curve_name(Self::nid()).unwrap()
}
fn validate_group(group: CRef<boringssl::EC_GROUP>) -> Result<(), Error>;
}
}
pub trait PCurve: Sized + Copy + Clone + Default + Display + Debug + self::inner::PCurve {}
#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Hash)]
pub struct P256;
#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Hash)]
pub struct P384;
#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Hash)]
pub struct P521;
impl Display for P256 {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "P-256")
}
}
impl Display for P384 {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "P-384")
}
}
impl Display for P521 {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "P-521")
}
}
const NID_P256: i32 = boringssl::NID_X9_62_prime256v1 as i32;
const NID_P384: i32 = boringssl::NID_secp384r1 as i32;
const NID_P521: i32 = boringssl::NID_secp521r1 as i32;
macro_rules! impl_curve {
($name:ident, $str:expr, $nid:ident) => {
impl self::inner::PCurve for $name {
fn nid() -> i32 {
$nid
}
fn validate_group(group: boringssl::CRef<boringssl::EC_GROUP>) -> Result<(), ::Error> {
let nid = group.ec_group_get_curve_name();
if nid != $nid {
return Err(::Error::new(format!(
concat!("unexpected curve: got {}; want ", $str),
nid_name(nid).unwrap(),
)));
}
Ok(())
}
}
impl Sealed for $name {}
impl PCurve for $name {}
};
}
impl_curve!(P256, "P-256", NID_P256);
impl_curve!(P384, "P-384", NID_P384);
impl_curve!(P521, "P-521", NID_P521);
pub enum CurveKind {
P256,
P384,
P521,
}
impl CurveKind {
pub fn from_nid(nid: i32) -> Result<CurveKind, Error> {
match nid {
self::NID_P256 => Ok(CurveKind::P256),
self::NID_P384 => Ok(CurveKind::P384),
self::NID_P521 => Ok(CurveKind::P521),
_ => Err(Error::new(format!("unsupported curve: {}", nid_name(nid).unwrap()))),
}
}
}
fn nid_name(nid: c_int) -> Result<Cow<'static, str>, BoringError> {
Ok(boringssl::ec_curve_nid2nist(nid)?.to_string_lossy())
}