diff --git a/tonic/src/transport/channel/service/tls.rs b/tonic/src/transport/channel/service/tls.rs index 2d7c18abb..4a1ab7378 100644 --- a/tonic/src/transport/channel/service/tls.rs +++ b/tonic/src/transport/channel/service/tls.rs @@ -9,7 +9,7 @@ use tokio_rustls::{ }; use super::io::BoxedIo; -use crate::transport::service::tls::{load_identity, TlsError, ALPN_H2}; +use crate::transport::service::tls::{TlsError, ALPN_H2}; use crate::transport::tls::{Certificate, Identity}; #[derive(Clone)] @@ -48,7 +48,7 @@ impl TlsConnector { let builder = builder.with_root_certificates(roots); let mut config = match identity { Some(identity) => { - let (client_cert, client_key) = load_identity(identity)?; + let (client_cert, client_key) = identity.parse()?; builder.with_client_auth_cert(client_cert, client_key)? } None => builder.with_no_client_auth(), diff --git a/tonic/src/transport/server/service/tls.rs b/tonic/src/transport/server/service/tls.rs index c96958828..a12a165dd 100644 --- a/tonic/src/transport/server/service/tls.rs +++ b/tonic/src/transport/server/service/tls.rs @@ -7,11 +7,7 @@ use tokio_rustls::{ TlsAcceptor as RustlsAcceptor, }; -use crate::transport::{ - server::Connected, - service::tls::{load_identity, ALPN_H2}, - Certificate, Identity, -}; +use crate::transport::{server::Connected, service::tls::ALPN_H2, Certificate, Identity}; #[derive(Clone)] pub(crate) struct TlsAcceptor { @@ -41,7 +37,7 @@ impl TlsAcceptor { } }; - let (cert, key) = load_identity(identity)?; + let (cert, key) = identity.parse()?; let mut config = builder.with_single_cert(cert, key)?; config.alpn_protocols.push(ALPN_H2.into()); diff --git a/tonic/src/transport/service/tls.rs b/tonic/src/transport/service/tls.rs index 81df6849d..5e49d5120 100644 --- a/tonic/src/transport/service/tls.rs +++ b/tonic/src/transport/service/tls.rs @@ -40,16 +40,14 @@ impl Certificate { } } -pub(crate) fn load_identity( - identity: Identity, -) -> Result<(Vec>, PrivateKeyDer<'static>), TlsError> { - let cert = rustls_pemfile::certs(&mut Cursor::new(identity.cert)) - .collect::, _>>() - .map_err(|_| TlsError::CertificateParseError)?; - - let Ok(Some(key)) = rustls_pemfile::private_key(&mut Cursor::new(identity.key)) else { - return Err(TlsError::PrivateKeyParseError); - }; - - Ok((cert, key)) +impl Identity { + pub(crate) fn parse( + &self, + ) -> Result<(Vec>, PrivateKeyDer<'static>), TlsError> { + let cert = self.cert.parse()?; + let Ok(Some(key)) = rustls_pemfile::private_key(&mut Cursor::new(&self.key)) else { + return Err(TlsError::PrivateKeyParseError); + }; + Ok((cert, key)) + } }