-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathpkcs8.rs
More file actions
203 lines (170 loc) · 6.82 KB
/
pkcs8.rs
File metadata and controls
203 lines (170 loc) · 6.82 KB
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
//! PKCS#8 encoding support.
//!
//! When the `pkcs8` feature of this crate is enabled, the [`DecodePrivateKey`] trait is impl'd for
//! [`DecapsulationKey`], and the [`DecodePublicKey`] trait is impl'd for [`EncapsulationKey`].
//!
//! When both the `pkcs8` and `alloc` features are enabled, the [`EncodePrivateKey`] trait is
//! impl'd for [`DecapsulationKey`], and the [`EncodePublicKey`] trait is impl'd for
//! [`EncapsulationKey`].
#![cfg(feature = "pkcs8")]
pub use ::pkcs8::{DecodePrivateKey, DecodePublicKey, spki::AssociatedAlgorithmIdentifier};
pub use const_oid::AssociatedOid;
#[cfg(feature = "alloc")]
pub use ::pkcs8::{EncodePrivateKey, EncodePublicKey};
use crate::{
MlKem512Params, MlKem768Params, MlKem1024Params,
kem::{DecapsulationKey, EncapsulationKey},
param::{EncapsulationKeySize, KemParams},
pke::EncryptionKey,
};
use ::pkcs8::{
der::{
AnyRef, Reader, SliceReader, TagNumber,
asn1::{ContextSpecific, OctetStringRef},
},
spki,
};
use hybrid_array::Array;
#[cfg(feature = "alloc")]
use {
crate::EncodedSizeUser,
::pkcs8::der::{Encode, TagMode, asn1::BitStringRef},
};
/// Tag number for the seed value.
const SEED_TAG_NUMBER: TagNumber = TagNumber(0);
/// ML-KEM seed serialized as ASN.1.
type SeedString<'a> = ContextSpecific<&'a OctetStringRef>;
impl AssociatedOid for MlKem512Params {
const OID: ::pkcs8::ObjectIdentifier = const_oid::db::fips203::ID_ALG_ML_KEM_512;
}
impl AssociatedOid for MlKem768Params {
const OID: ::pkcs8::ObjectIdentifier = const_oid::db::fips203::ID_ALG_ML_KEM_768;
}
impl AssociatedOid for MlKem1024Params {
const OID: ::pkcs8::ObjectIdentifier = const_oid::db::fips203::ID_ALG_ML_KEM_1024;
}
impl AssociatedAlgorithmIdentifier for MlKem512Params {
type Params = ::pkcs8::der::AnyRef<'static>;
const ALGORITHM_IDENTIFIER: spki::AlgorithmIdentifier<Self::Params> =
spki::AlgorithmIdentifier {
oid: Self::OID,
parameters: None,
};
}
impl AssociatedAlgorithmIdentifier for MlKem768Params {
type Params = ::pkcs8::der::AnyRef<'static>;
const ALGORITHM_IDENTIFIER: spki::AlgorithmIdentifier<Self::Params> =
spki::AlgorithmIdentifier {
oid: Self::OID,
parameters: None,
};
}
impl AssociatedAlgorithmIdentifier for MlKem1024Params {
type Params = ::pkcs8::der::AnyRef<'static>;
const ALGORITHM_IDENTIFIER: spki::AlgorithmIdentifier<Self::Params> =
spki::AlgorithmIdentifier {
oid: Self::OID,
parameters: None,
};
}
impl<P> AssociatedAlgorithmIdentifier for EncapsulationKey<P>
where
P: KemParams + AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
type Params = P::Params;
const ALGORITHM_IDENTIFIER: spki::AlgorithmIdentifier<Self::Params> = P::ALGORITHM_IDENTIFIER;
}
#[cfg(feature = "alloc")]
impl<P> pkcs8::EncodePublicKey for EncapsulationKey<P>
where
P: KemParams + AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
/// Serialize the given `EncapsulationKey` into DER format.
/// Returns a `Document` which wraps the DER document in case of success.
fn to_public_key_der(&self) -> spki::Result<pkcs8::Document> {
let public_key = self.to_bytes();
let subject_public_key = BitStringRef::new(0, &public_key)?;
::pkcs8::SubjectPublicKeyInfo {
algorithm: P::ALGORITHM_IDENTIFIER,
subject_public_key,
}
.try_into()
}
}
impl<P> TryFrom<::pkcs8::SubjectPublicKeyInfoRef<'_>> for EncapsulationKey<P>
where
P: KemParams + AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
type Error = spki::Error;
/// Deserialize the encapsulation key from DER format found in `spki.subject_public_key`.
/// Returns an `EncapsulationKey` containing `ek_{pke}` and `h` in case of success.
fn try_from(spki: ::pkcs8::SubjectPublicKeyInfoRef<'_>) -> Result<Self, spki::Error> {
if spki.algorithm.oid != P::ALGORITHM_IDENTIFIER.oid {
return Err(spki::Error::OidUnknown {
oid: P::ALGORITHM_IDENTIFIER.oid,
});
}
let bitstring_of_encapsulation_key = spki.subject_public_key;
let enc_key = match bitstring_of_encapsulation_key.as_bytes() {
Some(bytes) => {
let arr: Array<u8, EncapsulationKeySize<P>> = match bytes.try_into() {
Ok(array) => array,
Err(_) => return Err(spki::Error::KeyMalformed),
};
EncryptionKey::from_bytes(&arr).map_err(|_| spki::Error::KeyMalformed)?
}
None => return Err(spki::Error::KeyMalformed),
};
Ok(Self::new(enc_key))
}
}
impl<P> AssociatedAlgorithmIdentifier for DecapsulationKey<P>
where
P: KemParams + AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
type Params = P::Params;
const ALGORITHM_IDENTIFIER: spki::AlgorithmIdentifier<Self::Params> = P::ALGORITHM_IDENTIFIER;
}
#[cfg(feature = "alloc")]
impl<P> pkcs8::EncodePrivateKey for DecapsulationKey<P>
where
P: KemParams + AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
/// Serialize the given `DecapsulationKey` into DER format.
/// Returns a `SecretDocument` which wraps the DER document in case of success.
fn to_pkcs8_der(&self) -> ::pkcs8::Result<pkcs8::SecretDocument> {
let seed = self.to_seed().ok_or(pkcs8::Error::KeyMalformed)?;
let seed_der = SeedString {
tag_mode: TagMode::Implicit,
tag_number: SEED_TAG_NUMBER,
value: OctetStringRef::new(&seed)?,
}
.to_der()?;
let private_key = OctetStringRef::new(&seed_der)?;
let private_key_info = pkcs8::PrivateKeyInfoRef::new(P::ALGORITHM_IDENTIFIER, private_key);
pkcs8::SecretDocument::encode_msg(&private_key_info).map_err(pkcs8::Error::Asn1)
}
}
impl<P> TryFrom<::pkcs8::PrivateKeyInfoRef<'_>> for DecapsulationKey<P>
where
P: KemParams + AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
type Error = ::pkcs8::Error;
/// Deserialize the decapsulation key from DER format found in `spki.private_key`.
/// Returns a `DecapsulationKey` containing `dk_{pke}`, `ek`, and `z` in case of success.
fn try_from(private_key_info_ref: ::pkcs8::PrivateKeyInfoRef<'_>) -> Result<Self, Self::Error> {
private_key_info_ref
.algorithm
.assert_algorithm_oid(P::ALGORITHM_IDENTIFIER.oid)?;
let mut reader = SliceReader::new(private_key_info_ref.private_key.as_bytes())?;
let seed_string = SeedString::decode_implicit(&mut reader, SEED_TAG_NUMBER)?
.ok_or(pkcs8::Error::KeyMalformed)?;
let seed = seed_string
.value
.as_bytes()
.try_into()
.map_err(|_| pkcs8::Error::KeyMalformed)?;
reader.finish()?;
Ok(Self::from_seed(seed))
}
}