-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathp384.rs
124 lines (97 loc) · 2.81 KB
/
p384.rs
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
// SPDX-FileCopyrightText: 2022 Profian Inc. <opensource@profian.com>
// SPDX-License-Identifier: Apache-2.0 OR MIT
#![cfg(feature = "p384")]
use p384::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use p384::{EncodedPoint, FieldBytes, PublicKey, SecretKey};
use jose_jwa::{Algorithm, Algorithm::Signing, Signing as S};
use super::Error;
use super::KeyInfo;
use crate::{Ec, EcCurves};
impl KeyInfo for PublicKey {
fn strength(&self) -> usize {
24
}
fn is_supported(&self, algo: &Algorithm) -> bool {
matches!(algo, Signing(S::Es384))
}
}
impl KeyInfo for SecretKey {
fn strength(&self) -> usize {
24
}
fn is_supported(&self, algo: &Algorithm) -> bool {
matches!(algo, Signing(S::Es384))
}
}
impl From<&PublicKey> for Ec {
fn from(pk: &PublicKey) -> Self {
let ep = pk.to_encoded_point(false);
Self {
crv: EcCurves::P384,
x: ep.x().expect("unreachable").to_vec().into(),
y: ep.y().expect("unreachable").to_vec().into(),
d: None,
}
}
}
impl From<PublicKey> for Ec {
fn from(sk: PublicKey) -> Self {
(&sk).into()
}
}
impl TryFrom<&Ec> for PublicKey {
type Error = Error;
fn try_from(value: &Ec) -> Result<Self, Self::Error> {
if value.crv != EcCurves::P384 {
return Err(Error::AlgMismatch);
}
let mut x = FieldBytes::default();
if value.x.len() != x.len() {
return Err(Error::Invalid);
}
let mut y = FieldBytes::default();
if value.y.len() != y.len() {
return Err(Error::Invalid);
}
x.copy_from_slice(&value.x);
y.copy_from_slice(&value.y);
let ep = EncodedPoint::from_affine_coordinates(&x, &y, false);
Option::from(Self::from_encoded_point(&ep)).ok_or(Error::Invalid)
}
}
impl TryFrom<Ec> for PublicKey {
type Error = Error;
fn try_from(value: Ec) -> Result<Self, Self::Error> {
(&value).try_into()
}
}
impl From<&SecretKey> for Ec {
fn from(sk: &SecretKey) -> Self {
let mut key: Self = sk.public_key().into();
key.d = Some(sk.to_bytes().to_vec().into());
key
}
}
impl From<SecretKey> for Ec {
fn from(sk: SecretKey) -> Self {
(&sk).into()
}
}
impl TryFrom<&Ec> for SecretKey {
type Error = Error;
fn try_from(value: &Ec) -> Result<Self, Self::Error> {
if value.crv != EcCurves::P384 {
return Err(Error::AlgMismatch);
}
if let Some(d) = value.d.as_ref() {
return Self::from_slice(d).map_err(|_| Error::Invalid);
}
Err(Error::NotPrivate)
}
}
impl TryFrom<Ec> for SecretKey {
type Error = Error;
fn try_from(value: Ec) -> Result<Self, Self::Error> {
(&value).try_into()
}
}