Skip to main content

tonic/transport/
tls.rs

1/*
2 *
3 * Copyright 2025 gRPC authors.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to
7 * deal in the Software without restriction, including without limitation the
8 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 * sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 */
24
25/// Represents a X509 certificate.
26#[derive(Debug, Clone)]
27pub struct Certificate {
28    pub(crate) pem: Vec<u8>,
29}
30
31/// Represents a private key and X509 certificate.
32#[derive(Debug, Clone)]
33pub struct Identity {
34    pub(crate) cert: Certificate,
35    pub(crate) key: Vec<u8>,
36}
37
38impl Certificate {
39    /// Parse a PEM encoded X509 Certificate.
40    ///
41    /// The provided PEM should include at least one PEM encoded certificate.
42    pub fn from_pem(pem: impl AsRef<[u8]>) -> Self {
43        let pem = pem.as_ref().into();
44        Self { pem }
45    }
46
47    /// Get a immutable reference to underlying certificate
48    pub fn get_ref(&self) -> &[u8] {
49        self.pem.as_slice()
50    }
51
52    /// Get a mutable reference to underlying certificate
53    pub fn get_mut(&mut self) -> &mut [u8] {
54        self.pem.as_mut()
55    }
56
57    /// Consumes `self`, returning the underlying certificate
58    pub fn into_inner(self) -> Vec<u8> {
59        self.pem
60    }
61}
62
63impl AsRef<[u8]> for Certificate {
64    fn as_ref(&self) -> &[u8] {
65        self.pem.as_ref()
66    }
67}
68
69impl AsMut<[u8]> for Certificate {
70    fn as_mut(&mut self) -> &mut [u8] {
71        self.pem.as_mut()
72    }
73}
74
75impl Identity {
76    /// Parse a PEM encoded certificate and private key.
77    ///
78    /// The provided cert must contain at least one PEM encoded certificate.
79    pub fn from_pem(cert: impl AsRef<[u8]>, key: impl AsRef<[u8]>) -> Self {
80        let cert = Certificate::from_pem(cert);
81        let key = key.as_ref().into();
82        Self { cert, key }
83    }
84}