-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathecdsa.rs
278 lines (237 loc) · 8.54 KB
/
ecdsa.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
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2023 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use cryptoki::{
mechanism::Mechanism,
object::{Attribute, AttributeType, KeyType, ObjectClass, ObjectHandle},
};
use der::{
asn1::{ObjectIdentifier, OctetString, OctetStringRef},
oid::AssociatedOid,
AnyRef, Decode, Encode,
};
use ecdsa::{
elliptic_curve::{
array::ArraySize,
ops::Invert,
point::PointCompression,
sec1::{FromEncodedPoint, ModulusSize, ToEncodedPoint},
subtle::CtOption,
AffinePoint, CurveArithmetic, FieldBytesSize, PublicKey, Scalar, SecretKey,
},
hazmat::DigestPrimitive,
PrimeCurve, Signature, SignatureSize, VerifyingKey,
};
use signature::{digest::Digest, DigestSigner};
use spki::{
AlgorithmIdentifier, AlgorithmIdentifierRef, AssociatedAlgorithmIdentifier,
SignatureAlgorithmIdentifier,
};
use std::{convert::TryFrom, ops::Add};
use thiserror::Error;
use crate::{CryptokiImport, SessionLike};
pub fn read_key<S: SessionLike, C: SignAlgorithm>(
session: &S,
template: impl Into<Vec<Attribute>>,
) -> Result<PublicKey<C>, Error>
where
FieldBytesSize<C>: ModulusSize,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
{
let mut template = template.into();
template.push(Attribute::Class(ObjectClass::PUBLIC_KEY));
template.push(Attribute::KeyType(KeyType::EC));
template.push(Attribute::EcParams(C::OID.to_der().unwrap()));
let keys = session.find_objects(&template)?;
if let Some(public_key) = keys.first() {
let attribute_pub = session.get_attributes(*public_key, &[AttributeType::EcPoint])?;
let mut ec_point = None;
for attribute in attribute_pub {
match attribute {
Attribute::EcPoint(p) if ec_point.is_none() => {
ec_point = Some(p);
break;
}
_ => {}
}
}
let ec_point = ec_point.ok_or(Error::MissingAttribute(AttributeType::EcPoint))?;
// documented as "DER-encoding of ANSI X9.62 ECPoint value Q"
// https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/pkcs11-spec-v3.1-os.html#_Toc111203418
// https://www.rfc-editor.org/rfc/rfc5480#section-2.2
let ec_point = OctetStringRef::from_der(&ec_point).unwrap();
Ok(PublicKey::<C>::from_sec1_bytes(ec_point.as_bytes())?)
} else {
Err(Error::MissingKey)
}
}
impl<C> CryptokiImport for SecretKey<C>
where
C: PrimeCurve + CurveArithmetic,
Scalar<C>: Invert<Output = CtOption<Scalar<C>>>,
SignatureSize<C>: ArraySize,
C: AssociatedOid,
{
fn put_key<S: SessionLike>(
&self,
session: &S,
template: impl Into<Vec<Attribute>>,
) -> cryptoki::error::Result<ObjectHandle> {
let mut template = template.into();
template.push(Attribute::Class(ObjectClass::PRIVATE_KEY));
template.push(Attribute::KeyType(KeyType::EC));
template.push(Attribute::EcParams(C::OID.to_der().unwrap()));
template.push(Attribute::Value(self.to_bytes().as_slice().to_vec()));
let handle = session.create_object(&template)?;
Ok(handle)
}
}
impl<C> CryptokiImport for PublicKey<C>
where
C: PrimeCurve + CurveArithmetic + PointCompression,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
C: AssociatedOid,
{
fn put_key<S: SessionLike>(
&self,
session: &S,
template: impl Into<Vec<Attribute>>,
) -> cryptoki::error::Result<ObjectHandle> {
let mut template = template.into();
template.push(Attribute::Class(ObjectClass::PUBLIC_KEY));
template.push(Attribute::KeyType(KeyType::EC));
template.push(Attribute::EcParams(C::OID.to_der().unwrap()));
let ec_point = OctetString::new(self.to_sec1_bytes()).unwrap();
template.push(Attribute::EcPoint(ec_point.to_der().unwrap()));
let handle = session.create_object(&template)?;
Ok(handle)
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error("Cryptoki error: {0}")]
Cryptoki(#[from] cryptoki::error::Error),
#[error("Private key missing attribute: {0}")]
MissingAttribute(AttributeType),
#[error("Elliptic curve error: {0}")]
Ecdsa(#[from] ecdsa::elliptic_curve::Error),
#[error("Key not found")]
MissingKey,
}
pub trait SignAlgorithm: PrimeCurve + CurveArithmetic + AssociatedOid + DigestPrimitive {
fn sign_mechanism() -> Mechanism<'static>;
}
macro_rules! impl_sign_algorithm {
($ec:ty) => {
impl SignAlgorithm for $ec {
fn sign_mechanism() -> Mechanism<'static> {
Mechanism::Ecdsa
}
}
};
}
//impl_sign_algorithm!(p224::NistP224);
impl_sign_algorithm!(p256::NistP256);
impl_sign_algorithm!(p384::NistP384);
impl_sign_algorithm!(k256::Secp256k1);
#[derive(signature::Signer)]
pub struct Signer<C: SignAlgorithm, S: SessionLike> {
session: S,
private_key: ObjectHandle,
verifying_key: VerifyingKey<C>,
}
impl<C: SignAlgorithm, S: SessionLike> Signer<C, S>
where
FieldBytesSize<C>: ModulusSize,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
{
pub fn new(session: S, label: &[u8]) -> Result<Self, Error> {
// First we'll lookup a private key with that label.
let template = vec![
Attribute::Label(label.to_vec()),
Attribute::Class(ObjectClass::PRIVATE_KEY),
Attribute::KeyType(KeyType::EC),
Attribute::EcParams(C::OID.to_der().unwrap()),
Attribute::Sign(true),
];
let private_key = session.find_objects(&template)?.remove(0);
let attribute_priv = session.get_attributes(private_key, &[AttributeType::Id])?;
// Second we'll lookup a public key with the same label/ec params/ec point
let mut template = vec![Attribute::Private(false), Attribute::Label(label.to_vec())];
let mut id = None;
for attribute in attribute_priv {
match attribute {
Attribute::Id(i) if id.is_none() => {
template.push(Attribute::Id(i.clone()));
id = Some(i);
}
_ => {}
}
}
id.ok_or(Error::MissingAttribute(AttributeType::Id))?;
let public = read_key(&session, template)?;
let verifying_key = public.into();
Ok(Self {
session,
private_key,
verifying_key,
})
}
pub fn into_session(self) -> S {
self.session
}
}
impl<C: SignAlgorithm, S: SessionLike> AssociatedAlgorithmIdentifier for Signer<C, S>
where
C: AssociatedOid,
{
type Params = ObjectIdentifier;
const ALGORITHM_IDENTIFIER: AlgorithmIdentifier<ObjectIdentifier> =
PublicKey::<C>::ALGORITHM_IDENTIFIER;
}
impl<C: SignAlgorithm, S: SessionLike> signature::Keypair for Signer<C, S> {
type VerifyingKey = VerifyingKey<C>;
fn verifying_key(&self) -> Self::VerifyingKey {
self.verifying_key
}
}
impl<C: SignAlgorithm, S: SessionLike> DigestSigner<C::Digest, Signature<C>> for Signer<C, S>
where
<<C as ecdsa::elliptic_curve::Curve>::FieldBytesSize as Add>::Output: ArraySize,
{
fn try_sign_digest(&self, digest: C::Digest) -> Result<Signature<C>, signature::Error> {
let msg = digest.finalize();
let bytes = self
.session
.sign(&C::sign_mechanism(), self.private_key, &msg)
.map_err(Error::Cryptoki)
.map_err(Box::new)
.map_err(signature::Error::from_source)?;
let signature = Signature::try_from(bytes.as_slice())?;
Ok(signature)
}
}
impl<C: SignAlgorithm, S: SessionLike> SignatureAlgorithmIdentifier for Signer<C, S>
where
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
Signature<C>: AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
type Params = AnyRef<'static>;
const SIGNATURE_ALGORITHM_IDENTIFIER: AlgorithmIdentifierRef<'static> =
Signature::<C>::ALGORITHM_IDENTIFIER;
}
impl<C: SignAlgorithm, S: SessionLike> DigestSigner<C::Digest, ecdsa::der::Signature<C>>
for Signer<C, S>
where
ecdsa::der::MaxSize<C>: ArraySize,
<FieldBytesSize<C> as Add>::Output: Add<ecdsa::der::MaxOverhead> + ArraySize,
Self: DigestSigner<C::Digest, Signature<C>>,
{
fn try_sign_digest(
&self,
digest: C::Digest,
) -> Result<ecdsa::der::Signature<C>, signature::Error> {
DigestSigner::<C::Digest, Signature<C>>::try_sign_digest(self, digest).map(Into::into)
}
}