Skip to content

Commit

Permalink
feat(tls): Add utility api to Certificate
Browse files Browse the repository at this point in the history
  • Loading branch information
tottoto committed Jun 22, 2024
1 parent 385bf6c commit 3332a51
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions tonic/src/transport/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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<Vec<u8>, 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<Vec<u8>, Self> {
match self.kind {
CertKind::Pem(pem) => Ok(pem),
_ => Err(self),
}
}
}

impl Identity {
Expand Down

0 comments on commit 3332a51

Please sign in to comment.