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
#[cfg(feature = "alloc")]
pub(crate) mod document;
use crate::{EcParameters, Error};
use core::fmt;
use der::{
asn1::{BitString, ContextSpecific, OctetString},
Decodable, Decoder, Encodable, Sequence, Tag, TagMode, TagNumber,
};
const VERSION: u8 = 1;
const EC_PARAMETERS_TAG: TagNumber = TagNumber::new(0);
const PUBLIC_KEY_TAG: TagNumber = TagNumber::new(1);
#[derive(Clone)]
pub struct EcPrivateKey<'a> {
pub private_key: &'a [u8],
pub parameters: Option<EcParameters>,
pub public_key: Option<&'a [u8]>,
}
impl<'a> Decodable<'a> for EcPrivateKey<'a> {
fn decode(decoder: &mut Decoder<'a>) -> der::Result<Self> {
decoder.sequence(|decoder| {
if decoder.uint8()? != VERSION {
return Err(der::Tag::Integer.value_error());
}
let private_key = decoder.octet_string()?.as_bytes();
let parameters = decoder.context_specific(EC_PARAMETERS_TAG, TagMode::Explicit)?;
let public_key = decoder
.context_specific::<BitString<'_>>(PUBLIC_KEY_TAG, TagMode::Explicit)?
.map(|bs| bs.as_bytes().ok_or_else(|| Tag::BitString.value_error()))
.transpose()?;
Ok(EcPrivateKey {
private_key,
parameters,
public_key,
})
})
}
}
impl<'a> Sequence<'a> for EcPrivateKey<'a> {
fn fields<F, T>(&self, f: F) -> der::Result<T>
where
F: FnOnce(&[&dyn Encodable]) -> der::Result<T>,
{
f(&[
&VERSION,
&OctetString::new(self.private_key)?,
&self.parameters.as_ref().map(|params| ContextSpecific {
tag_number: EC_PARAMETERS_TAG,
tag_mode: TagMode::Explicit,
value: *params,
}),
&self
.public_key
.map(|pk| {
BitString::from_bytes(pk).map(|value| ContextSpecific {
tag_number: PUBLIC_KEY_TAG,
tag_mode: TagMode::Explicit,
value,
})
})
.transpose()?,
])
}
}
impl<'a> TryFrom<&'a [u8]> for EcPrivateKey<'a> {
type Error = Error;
fn try_from(bytes: &'a [u8]) -> Result<EcPrivateKey<'a>, Error> {
Ok(Self::from_der(bytes)?)
}
}
impl<'a> fmt::Debug for EcPrivateKey<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EcPrivateKey")
.field("parameters", &self.parameters)
.field("public_key", &self.public_key)
.finish_non_exhaustive()
}
}