spiffe/cert/
mod.rs

1//! Certificate and PrivateKey types and functions.
2
3use crate::cert::errors::{CertificateError, PrivateKeyError};
4use crate::cert::parsing::parse_der_encoded_bytes_as_x509_certificate;
5use pkcs8::PrivateKeyInfo;
6use std::convert::TryFrom;
7use zeroize::Zeroize;
8
9pub mod errors;
10pub(crate) mod parsing;
11
12/// This type contains a single certificate by value.
13///
14/// The certificate is a DER-encoded (binary format) X.509.
15///
16/// When an instance is created, it is checked that the bytes
17/// represent a parseable DER-encoded X.509 certificate.
18#[derive(Debug, Clone, Eq, PartialEq)]
19pub struct Certificate(Vec<u8>);
20
21impl Certificate {
22    /// Returns the content of the certificate as a slice of bytes.
23    pub fn content(&self) -> &[u8] {
24        &self.0
25    }
26
27    pub(crate) fn from_der_bytes(bytes: Vec<u8>) -> Self {
28        Self(bytes)
29    }
30}
31impl AsRef<[u8]> for Certificate {
32    fn as_ref(&self) -> &[u8] {
33        &self.0
34    }
35}
36
37impl TryFrom<&[u8]> for Certificate {
38    type Error = CertificateError;
39
40    fn try_from(der_bytes: &[u8]) -> Result<Self, Self::Error> {
41        parse_der_encoded_bytes_as_x509_certificate(der_bytes)?;
42        Ok(Self(Vec::from(der_bytes)))
43    }
44}
45
46impl TryFrom<Vec<u8>> for Certificate {
47    type Error = CertificateError;
48
49    fn try_from(der_bytes: Vec<u8>) -> Result<Self, Self::Error> {
50        parse_der_encoded_bytes_as_x509_certificate(&der_bytes)?;
51        Ok(Self(der_bytes))
52    }
53}
54
55/// This type contains a private key by value.
56///
57/// The private key is be DER-encoded (binary format) ASN.1 in PKCS#8 format.
58///
59/// The struct is zeroized on drop.
60#[derive(Debug, Clone, Eq, PartialEq, Zeroize)]
61#[zeroize(drop)]
62pub struct PrivateKey(Vec<u8>);
63
64impl PrivateKey {
65    /// Returns the content of the private key as a slice of bytes.
66    pub fn content(&self) -> &[u8] {
67        &self.0
68    }
69}
70
71impl AsRef<[u8]> for PrivateKey {
72    fn as_ref(&self) -> &[u8] {
73        &self.0
74    }
75}
76
77impl TryFrom<&[u8]> for PrivateKey {
78    type Error = PrivateKeyError;
79
80    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
81        // validate that the bytes are a valid private key
82        PrivateKeyInfo::try_from(bytes).map_err(PrivateKeyError::DecodePkcs8)?;
83        Ok(Self(Vec::from(bytes)))
84    }
85}
86
87impl TryFrom<Vec<u8>> for PrivateKey {
88    type Error = PrivateKeyError;
89
90    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
91        // validate that the bytes are a valid private key
92        PrivateKeyInfo::try_from(bytes.as_slice()).map_err(PrivateKeyError::DecodePkcs8)?;
93        Ok(Self(bytes))
94    }
95}