tonic/transport/
tls.rs

1/// Represents a X509 certificate.
2#[derive(Debug, Clone)]
3pub struct Certificate {
4    pub(crate) pem: Vec<u8>,
5}
6
7/// Represents a private key and X509 certificate.
8#[cfg(feature = "tls")]
9#[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
10#[derive(Debug, Clone)]
11pub struct Identity {
12    pub(crate) cert: Certificate,
13    pub(crate) key: Vec<u8>,
14}
15
16impl Certificate {
17    /// Parse a PEM encoded X509 Certificate.
18    ///
19    /// The provided PEM should include at least one PEM encoded certificate.
20    pub fn from_pem(pem: impl AsRef<[u8]>) -> Self {
21        let pem = pem.as_ref().into();
22        Self { pem }
23    }
24
25    /// Get a immutable reference to underlying certificate
26    pub fn get_ref(&self) -> &[u8] {
27        &self.pem.as_slice()
28    }
29
30    /// Get a mutable reference to underlying certificate
31    pub fn get_mut(&mut self) -> &mut [u8] {
32        self.pem.as_mut()
33    }
34
35    /// Consumes `self`, returning the underlying certificate
36    pub fn into_inner(self) -> Vec<u8> {
37        self.pem
38    }
39}
40
41impl AsRef<[u8]> for Certificate {
42    fn as_ref(&self) -> &[u8] {
43        self.pem.as_ref()
44    }
45}
46
47#[cfg(feature = "tls")]
48impl Identity {
49    /// Parse a PEM encoded certificate and private key.
50    ///
51    /// The provided cert must contain at least one PEM encoded certificate.
52    pub fn from_pem(cert: impl AsRef<[u8]>, key: impl AsRef<[u8]>) -> Self {
53        let cert = Certificate::from_pem(cert);
54        let key = key.as_ref().into();
55        Self { cert, key }
56    }
57}