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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use crate::{AlgorithmIdentifier, Error, Result, Version};
use core::fmt;
use der::{
asn1::{AnyRef, BitStringRef, ContextSpecific, OctetStringRef},
Decode, DecodeValue, Encode, Header, Reader, Sequence, TagMode, TagNumber,
};
#[cfg(feature = "alloc")]
use der::SecretDocument;
#[cfg(feature = "encryption")]
use {
crate::EncryptedPrivateKeyInfo,
der::zeroize::Zeroizing,
pkcs5::pbes2,
rand_core::{CryptoRng, RngCore},
};
#[cfg(feature = "pem")]
use der::pem::PemLabel;
#[cfg(feature = "subtle")]
use subtle::{Choice, ConstantTimeEq};
const PUBLIC_KEY_TAG: TagNumber = TagNumber::N1;
#[derive(Clone)]
pub struct PrivateKeyInfo<'a> {
pub algorithm: AlgorithmIdentifier<'a>,
pub private_key: &'a [u8],
pub public_key: Option<&'a [u8]>,
}
impl<'a> PrivateKeyInfo<'a> {
pub fn new(algorithm: AlgorithmIdentifier<'a>, private_key: &'a [u8]) -> Self {
Self {
algorithm,
private_key,
public_key: None,
}
}
pub fn version(&self) -> Version {
if self.public_key.is_some() {
Version::V2
} else {
Version::V1
}
}
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn encrypt(
&self,
rng: impl CryptoRng + RngCore,
password: impl AsRef<[u8]>,
) -> Result<SecretDocument> {
let der = Zeroizing::new(self.to_vec()?);
EncryptedPrivateKeyInfo::encrypt(rng, password, der.as_ref())
}
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn encrypt_with_params(
&self,
pbes2_params: pbes2::Parameters<'_>,
password: impl AsRef<[u8]>,
) -> Result<SecretDocument> {
let der = Zeroizing::new(self.to_vec()?);
EncryptedPrivateKeyInfo::encrypt_with(pbes2_params, password, der.as_ref())
}
}
impl<'a> DecodeValue<'a> for PrivateKeyInfo<'a> {
fn decode_value<R: Reader<'a>>(
reader: &mut R,
header: Header,
) -> der::Result<PrivateKeyInfo<'a>> {
reader.read_nested(header.length, |reader| {
let version = Version::decode(reader)?;
let algorithm = reader.decode()?;
let private_key = OctetStringRef::decode(reader)?.into();
let public_key = reader
.context_specific::<BitStringRef<'_>>(PUBLIC_KEY_TAG, TagMode::Implicit)?
.map(|bs| {
bs.as_bytes()
.ok_or_else(|| der::Tag::BitString.value_error())
})
.transpose()?;
if version.has_public_key() != public_key.is_some() {
return Err(reader.error(
der::Tag::ContextSpecific {
constructed: true,
number: PUBLIC_KEY_TAG,
}
.value_error()
.kind(),
));
}
while !reader.is_finished() {
reader.decode::<ContextSpecific<AnyRef<'_>>>()?;
}
Ok(Self {
algorithm,
private_key,
public_key,
})
})
}
}
impl<'a> Sequence<'a> for PrivateKeyInfo<'a> {
fn fields<F, T>(&self, f: F) -> der::Result<T>
where
F: FnOnce(&[&dyn Encode]) -> der::Result<T>,
{
f(&[
&u8::from(self.version()),
&self.algorithm,
&OctetStringRef::new(self.private_key)?,
&self
.public_key
.map(|pk| {
BitStringRef::from_bytes(pk).map(|value| ContextSpecific {
tag_number: PUBLIC_KEY_TAG,
tag_mode: TagMode::Implicit,
value,
})
})
.transpose()?,
])
}
}
impl<'a> TryFrom<&'a [u8]> for PrivateKeyInfo<'a> {
type Error = Error;
fn try_from(bytes: &'a [u8]) -> Result<Self> {
Ok(Self::from_der(bytes)?)
}
}
impl<'a> fmt::Debug for PrivateKeyInfo<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PrivateKeyInfo")
.field("version", &self.version())
.field("algorithm", &self.algorithm)
.field("public_key", &self.public_key)
.finish_non_exhaustive()
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl TryFrom<PrivateKeyInfo<'_>> for SecretDocument {
type Error = Error;
fn try_from(private_key: PrivateKeyInfo<'_>) -> Result<SecretDocument> {
SecretDocument::try_from(&private_key)
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl TryFrom<&PrivateKeyInfo<'_>> for SecretDocument {
type Error = Error;
fn try_from(private_key: &PrivateKeyInfo<'_>) -> Result<SecretDocument> {
Ok(Self::encode_msg(private_key)?)
}
}
#[cfg(feature = "pem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
impl PemLabel for PrivateKeyInfo<'_> {
const PEM_LABEL: &'static str = "PRIVATE KEY";
}
#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl<'a> ConstantTimeEq for PrivateKeyInfo<'a> {
fn ct_eq(&self, other: &Self) -> Choice {
let public_fields_eq =
self.algorithm == other.algorithm && self.public_key == other.public_key;
self.private_key.ct_eq(other.private_key) & Choice::from(public_fields_eq as u8)
}
}
#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl<'a> Eq for PrivateKeyInfo<'a> {}
#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl<'a> PartialEq for PrivateKeyInfo<'a> {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
}