From 3332a5151c6ee93590c1e492387b855981d52c51 Mon Sep 17 00:00:00 2001 From: tottoto Date: Sat, 22 Jun 2024 10:11:26 +0900 Subject: [PATCH] feat(tls): Add utility api to Certificate --- tonic/src/transport/tls.rs | 48 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/tonic/src/transport/tls.rs b/tonic/src/transport/tls.rs index f26bbc8c4..feef8aec3 100644 --- a/tonic/src/transport/tls.rs +++ b/tonic/src/transport/tls.rs @@ -22,9 +22,9 @@ impl Certificate { Self { kind } } - /// Parse a PEM encoded X509 Certificate. + /// Parse a DER encoded X509 Certificate. /// - /// The provided PEM should include at least one PEM encoded certificate. + /// The provided DER should include at least one PEM encoded certificate. pub fn from_der(der: impl AsRef<[u8]>) -> Self { let der = der.as_ref().into(); Self::new(CertKind::Der(der)) @@ -37,6 +37,50 @@ impl Certificate { let pem = pem.as_ref().into(); Self::new(CertKind::Pem(pem)) } + + /// Returns whether this is a DER encoded certificate. + pub fn is_der(&self) -> bool { + matches!(self.kind, CertKind::Der(_)) + } + + /// Returns whether this is a PEM encoded certificate. + pub fn is_pem(&self) -> bool { + matches!(self.kind, CertKind::Pem(_)) + } + + /// Returns the reference to DER encoded certificate. + /// Returns `None` When this is not encoded as DER. + pub fn der(&self) -> Option<&[u8]> { + match &self.kind { + CertKind::Der(der) => Some(der), + _ => None, + } + } + + /// Returns the reference to PEM encoded certificate. + /// Returns `None` When this is not encoded as PEM. + pub fn pem(&self) -> Option<&[u8]> { + match &self.kind { + CertKind::Pem(pem) => Some(pem), + _ => None, + } + } + + /// Turns this value into the DER encoded bytes. + pub fn into_der(self) -> Result, Self> { + match self.kind { + CertKind::Der(der) => Ok(der), + _ => Err(self), + } + } + + /// Turns this value into the PEM encoded bytes. + pub fn into_pem(self) -> Result, Self> { + match self.kind { + CertKind::Pem(pem) => Ok(pem), + _ => Err(self), + } + } } impl Identity {