interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / ed25519 / src / pkcs8.rs

356 lines · 10357 bytes Raw Blame History
1//! PKCS#8 private key support.
2//!
3//! Implements Ed25519 PKCS#8 private keys as described in RFC8410 Section 7:
4//! <https://datatracker.ietf.org/doc/html/rfc8410#section-7>
5//!
6//! ## SemVer Notes
7//!
8//! The `pkcs8` module of this crate is exempted from SemVer as it uses a
9//! pre-1.0 dependency (the `pkcs8` crate).
10//!
11//! However, breaking changes to this module will be accompanied by a minor
12//! version bump.
13//!
14//! Please lock to a specific minor version of the `ed25519` crate to avoid
15//! breaking changes when using this module.
16
17pub use pkcs8::{
18 spki, DecodePrivateKey, DecodePublicKey, Error, ObjectIdentifier, PrivateKeyInfo, Result,
19};
20
21#[cfg(feature = "alloc")]
22pub use pkcs8::{spki::EncodePublicKey, EncodePrivateKey};
23
24#[cfg(feature = "alloc")]
25pub use pkcs8::der::{asn1::BitStringRef, Document, SecretDocument};
26
27use core::fmt;
28
29#[cfg(feature = "pem")]
30use {
31 alloc::string::{String, ToString},
32 core::str,
33};
34
35#[cfg(feature = "zeroize")]
36use zeroize::Zeroize;
37
38/// Algorithm [`ObjectIdentifier`] for the Ed25519 digital signature algorithm
39/// (`id-Ed25519`).
40///
41/// <http://oid-info.com/get/1.3.101.112>
42pub const ALGORITHM_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
43
44/// Ed25519 Algorithm Identifier.
45pub const ALGORITHM_ID: pkcs8::AlgorithmIdentifierRef<'static> = pkcs8::AlgorithmIdentifierRef {
46 oid: ALGORITHM_OID,
47 parameters: None,
48};
49
50/// Ed25519 keypair serialized as bytes.
51///
52/// This type is primarily useful for decoding/encoding PKCS#8 private key
53/// files (either DER or PEM) encoded using the following traits:
54///
55/// - [`DecodePrivateKey`]: decode DER or PEM encoded PKCS#8 private key.
56/// - [`EncodePrivateKey`]: encode DER or PEM encoded PKCS#8 private key.
57///
58/// PKCS#8 private key files encoded with PEM begin with:
59///
60/// ```text
61/// -----BEGIN PRIVATE KEY-----
62/// ```
63///
64/// Note that this type operates on raw bytes and performs no validation that
65/// keys represent valid Ed25519 field elements.
66pub struct KeypairBytes {
67 /// Ed25519 secret key.
68 ///
69 /// Little endian serialization of an element of the Curve25519 scalar
70 /// field, prior to "clamping" (i.e. setting/clearing bits to ensure the
71 /// scalar is actually a valid field element)
72 pub secret_key: [u8; Self::BYTE_SIZE / 2],
73
74 /// Ed25519 public key (if available).
75 ///
76 /// Compressed Edwards-y encoded curve point.
77 pub public_key: Option<PublicKeyBytes>,
78}
79
80impl KeypairBytes {
81 /// Size of an Ed25519 keypair when serialized as bytes.
82 const BYTE_SIZE: usize = 64;
83
84 /// Parse raw keypair from a 64-byte input.
85 pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> Self {
86 let (sk, pk) = bytes.split_at(Self::BYTE_SIZE / 2);
87
88 Self {
89 secret_key: sk.try_into().expect("secret key size error"),
90 public_key: Some(PublicKeyBytes(
91 pk.try_into().expect("public key size error"),
92 )),
93 }
94 }
95
96 /// Serialize as a 64-byte keypair.
97 ///
98 /// # Returns
99 ///
100 /// - `Some(bytes)` if the `public_key` is present.
101 /// - `None` if the `public_key` is absent (i.e. `None`).
102 pub fn to_bytes(&self) -> Option<[u8; Self::BYTE_SIZE]> {
103 if let Some(public_key) = &self.public_key {
104 let mut result = [0u8; Self::BYTE_SIZE];
105 let (sk, pk) = result.split_at_mut(Self::BYTE_SIZE / 2);
106 sk.copy_from_slice(&self.secret_key);
107 pk.copy_from_slice(public_key.as_ref());
108 Some(result)
109 } else {
110 None
111 }
112 }
113}
114
115impl Drop for KeypairBytes {
116 fn drop(&mut self) {
117 #[cfg(feature = "zeroize")]
118 self.secret_key.zeroize()
119 }
120}
121
122#[cfg(feature = "alloc")]
123impl EncodePrivateKey for KeypairBytes {
124 fn to_pkcs8_der(&self) -> Result<SecretDocument> {
125 // Serialize private key as nested OCTET STRING
126 let mut private_key = [0u8; 2 + (Self::BYTE_SIZE / 2)];
127 private_key[0] = 0x04;
128 private_key[1] = 0x20;
129 private_key[2..].copy_from_slice(&self.secret_key);
130
131 let private_key_info = PrivateKeyInfo {
132 algorithm: ALGORITHM_ID,
133 private_key: &private_key,
134 public_key: self.public_key.as_ref().map(|pk| pk.0.as_slice()),
135 };
136
137 let result = SecretDocument::encode_msg(&private_key_info)?;
138
139 #[cfg(feature = "zeroize")]
140 private_key.zeroize();
141
142 Ok(result)
143 }
144}
145
146impl TryFrom<PrivateKeyInfo<'_>> for KeypairBytes {
147 type Error = Error;
148
149 fn try_from(private_key: PrivateKeyInfo<'_>) -> Result<Self> {
150 private_key.algorithm.assert_algorithm_oid(ALGORITHM_OID)?;
151
152 if private_key.algorithm.parameters.is_some() {
153 return Err(Error::ParametersMalformed);
154 }
155
156 // Ed25519 PKCS#8 keys are represented as a nested OCTET STRING
157 // (i.e. an OCTET STRING within an OCTET STRING).
158 //
159 // This match statement checks and removes the inner OCTET STRING
160 // header value:
161 //
162 // - 0x04: OCTET STRING tag
163 // - 0x20: 32-byte length
164 let secret_key = match private_key.private_key {
165 [0x04, 0x20, rest @ ..] => rest.try_into().map_err(|_| Error::KeyMalformed),
166 _ => Err(Error::KeyMalformed),
167 }?;
168
169 let public_key = private_key
170 .public_key
171 .map(|bytes| bytes.try_into().map_err(|_| Error::KeyMalformed))
172 .transpose()?
173 .map(PublicKeyBytes);
174
175 Ok(Self {
176 secret_key,
177 public_key,
178 })
179 }
180}
181
182impl TryFrom<&[u8]> for KeypairBytes {
183 type Error = Error;
184
185 fn try_from(der_bytes: &[u8]) -> Result<Self> {
186 Self::from_pkcs8_der(der_bytes)
187 }
188}
189
190impl fmt::Debug for KeypairBytes {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.debug_struct("KeypairBytes")
193 .field("public_key", &self.public_key)
194 .finish_non_exhaustive()
195 }
196}
197
198#[cfg(feature = "pem")]
199impl str::FromStr for KeypairBytes {
200 type Err = Error;
201
202 fn from_str(pem: &str) -> Result<Self> {
203 Self::from_pkcs8_pem(pem)
204 }
205}
206
207/// Ed25519 public key serialized as bytes.
208///
209/// This type is primarily useful for decoding/encoding SPKI public key
210/// files (either DER or PEM) encoded using the following traits:
211///
212/// - [`DecodePublicKey`]: decode DER or PEM encoded PKCS#8 private key.
213/// - [`EncodePublicKey`]: encode DER or PEM encoded PKCS#8 private key.
214///
215/// SPKI public key files encoded with PEM begin with:
216///
217/// ```text
218/// -----BEGIN PUBLIC KEY-----
219/// ```
220///
221/// Note that this type operates on raw bytes and performs no validation that
222/// public keys represent valid compressed Ed25519 y-coordinates.
223#[derive(Clone, Copy, Eq, PartialEq)]
224pub struct PublicKeyBytes(pub [u8; Self::BYTE_SIZE]);
225
226impl PublicKeyBytes {
227 /// Size of an Ed25519 public key when serialized as bytes.
228 const BYTE_SIZE: usize = 32;
229
230 /// Returns the raw bytes of the public key.
231 pub fn to_bytes(&self) -> [u8; Self::BYTE_SIZE] {
232 self.0
233 }
234}
235
236impl AsRef<[u8; Self::BYTE_SIZE]> for PublicKeyBytes {
237 fn as_ref(&self) -> &[u8; Self::BYTE_SIZE] {
238 &self.0
239 }
240}
241
242#[cfg(feature = "alloc")]
243impl EncodePublicKey for PublicKeyBytes {
244 fn to_public_key_der(&self) -> spki::Result<Document> {
245 pkcs8::SubjectPublicKeyInfoRef {
246 algorithm: ALGORITHM_ID,
247 subject_public_key: BitStringRef::new(0, &self.0)?,
248 }
249 .try_into()
250 }
251}
252
253impl TryFrom<spki::SubjectPublicKeyInfoRef<'_>> for PublicKeyBytes {
254 type Error = spki::Error;
255
256 fn try_from(spki: spki::SubjectPublicKeyInfoRef<'_>) -> spki::Result<Self> {
257 spki.algorithm.assert_algorithm_oid(ALGORITHM_OID)?;
258
259 if spki.algorithm.parameters.is_some() {
260 return Err(spki::Error::KeyMalformed);
261 }
262
263 spki.subject_public_key
264 .as_bytes()
265 .ok_or(spki::Error::KeyMalformed)?
266 .try_into()
267 .map(Self)
268 .map_err(|_| spki::Error::KeyMalformed)
269 }
270}
271
272impl TryFrom<&[u8]> for PublicKeyBytes {
273 type Error = spki::Error;
274
275 fn try_from(der_bytes: &[u8]) -> spki::Result<Self> {
276 Self::from_public_key_der(der_bytes)
277 }
278}
279
280impl TryFrom<KeypairBytes> for PublicKeyBytes {
281 type Error = spki::Error;
282
283 fn try_from(keypair: KeypairBytes) -> spki::Result<PublicKeyBytes> {
284 PublicKeyBytes::try_from(&keypair)
285 }
286}
287
288impl TryFrom<&KeypairBytes> for PublicKeyBytes {
289 type Error = spki::Error;
290
291 fn try_from(keypair: &KeypairBytes) -> spki::Result<PublicKeyBytes> {
292 keypair.public_key.ok_or(spki::Error::KeyMalformed)
293 }
294}
295
296impl fmt::Debug for PublicKeyBytes {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298 f.write_str("PublicKeyBytes(")?;
299
300 for &byte in self.as_ref() {
301 write!(f, "{:02X}", byte)?;
302 }
303
304 f.write_str(")")
305 }
306}
307
308#[cfg(feature = "pem")]
309impl str::FromStr for PublicKeyBytes {
310 type Err = spki::Error;
311
312 fn from_str(pem: &str) -> spki::Result<Self> {
313 Self::from_public_key_pem(pem)
314 }
315}
316
317#[cfg(feature = "pem")]
318impl ToString for PublicKeyBytes {
319 fn to_string(&self) -> String {
320 self.to_public_key_pem(Default::default())
321 .expect("PEM serialization error")
322 }
323}
324
325#[cfg(feature = "pem")]
326#[cfg(test)]
327mod tests {
328 use super::{KeypairBytes, PublicKeyBytes};
329 use hex_literal::hex;
330
331 const SECRET_KEY_BYTES: [u8; 32] =
332 hex!("D4EE72DBF913584AD5B6D8F1F769F8AD3AFE7C28CBF1D4FBE097A88F44755842");
333
334 const PUBLIC_KEY_BYTES: [u8; 32] =
335 hex!("19BF44096984CDFE8541BAC167DC3B96C85086AA30B6B6CB0C5C38AD703166E1");
336
337 #[test]
338 fn to_bytes() {
339 let valid_keypair = KeypairBytes {
340 secret_key: SECRET_KEY_BYTES,
341 public_key: Some(PublicKeyBytes(PUBLIC_KEY_BYTES)),
342 };
343
344 assert_eq!(
345 valid_keypair.to_bytes().unwrap(),
346 hex!("D4EE72DBF913584AD5B6D8F1F769F8AD3AFE7C28CBF1D4FBE097A88F4475584219BF44096984CDFE8541BAC167DC3B96C85086AA30B6B6CB0C5C38AD703166E1")
347 );
348
349 let invalid_keypair = KeypairBytes {
350 secret_key: SECRET_KEY_BYTES,
351 public_key: None,
352 };
353
354 assert_eq!(invalid_keypair.to_bytes(), None);
355 }
356}