sec1/
private_key.rs
1#[cfg(feature = "alloc")]
9pub(crate) mod document;
10
11use crate::{EcParameters, Error};
12use core::fmt;
13use der::{
14 asn1::{BitString, ContextSpecific, OctetString},
15 Decodable, Decoder, Encodable, Sequence, Tag, TagMode, TagNumber,
16};
17
18const VERSION: u8 = 1;
28
29const EC_PARAMETERS_TAG: TagNumber = TagNumber::new(0);
31
32const PUBLIC_KEY_TAG: TagNumber = TagNumber::new(1);
34
35#[derive(Clone)]
58pub struct EcPrivateKey<'a> {
59 pub private_key: &'a [u8],
61
62 pub parameters: Option<EcParameters>,
64
65 pub public_key: Option<&'a [u8]>,
67}
68
69impl<'a> Decodable<'a> for EcPrivateKey<'a> {
70 fn decode(decoder: &mut Decoder<'a>) -> der::Result<Self> {
71 decoder.sequence(|decoder| {
72 if decoder.uint8()? != VERSION {
73 return Err(der::Tag::Integer.value_error());
74 }
75
76 let private_key = decoder.octet_string()?.as_bytes();
77 let parameters = decoder.context_specific(EC_PARAMETERS_TAG, TagMode::Explicit)?;
78 let public_key = decoder
79 .context_specific::<BitString<'_>>(PUBLIC_KEY_TAG, TagMode::Explicit)?
80 .map(|bs| bs.as_bytes().ok_or_else(|| Tag::BitString.value_error()))
81 .transpose()?;
82
83 Ok(EcPrivateKey {
84 private_key,
85 parameters,
86 public_key,
87 })
88 })
89 }
90}
91
92impl<'a> Sequence<'a> for EcPrivateKey<'a> {
93 fn fields<F, T>(&self, f: F) -> der::Result<T>
94 where
95 F: FnOnce(&[&dyn Encodable]) -> der::Result<T>,
96 {
97 f(&[
98 &VERSION,
99 &OctetString::new(self.private_key)?,
100 &self.parameters.as_ref().map(|params| ContextSpecific {
101 tag_number: EC_PARAMETERS_TAG,
102 tag_mode: TagMode::Explicit,
103 value: *params,
104 }),
105 &self
106 .public_key
107 .map(|pk| {
108 BitString::from_bytes(pk).map(|value| ContextSpecific {
109 tag_number: PUBLIC_KEY_TAG,
110 tag_mode: TagMode::Explicit,
111 value,
112 })
113 })
114 .transpose()?,
115 ])
116 }
117}
118
119impl<'a> TryFrom<&'a [u8]> for EcPrivateKey<'a> {
120 type Error = Error;
121
122 fn try_from(bytes: &'a [u8]) -> Result<EcPrivateKey<'a>, Error> {
123 Ok(Self::from_der(bytes)?)
124 }
125}
126
127impl<'a> fmt::Debug for EcPrivateKey<'a> {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 f.debug_struct("EcPrivateKey")
130 .field("parameters", &self.parameters)
131 .field("public_key", &self.public_key)
132 .finish_non_exhaustive()
133 }
134}