Skip to content

Commit 3332a51

Browse files
committed
feat(tls): Add utility api to Certificate
1 parent 385bf6c commit 3332a51

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

tonic/src/transport/tls.rs

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ impl Certificate {
2222
Self { kind }
2323
}
2424

25-
/// Parse a PEM encoded X509 Certificate.
25+
/// Parse a DER encoded X509 Certificate.
2626
///
27-
/// The provided PEM should include at least one PEM encoded certificate.
27+
/// The provided DER should include at least one PEM encoded certificate.
2828
pub fn from_der(der: impl AsRef<[u8]>) -> Self {
2929
let der = der.as_ref().into();
3030
Self::new(CertKind::Der(der))
@@ -37,6 +37,50 @@ impl Certificate {
3737
let pem = pem.as_ref().into();
3838
Self::new(CertKind::Pem(pem))
3939
}
40+
41+
/// Returns whether this is a DER encoded certificate.
42+
pub fn is_der(&self) -> bool {
43+
matches!(self.kind, CertKind::Der(_))
44+
}
45+
46+
/// Returns whether this is a PEM encoded certificate.
47+
pub fn is_pem(&self) -> bool {
48+
matches!(self.kind, CertKind::Pem(_))
49+
}
50+
51+
/// Returns the reference to DER encoded certificate.
52+
/// Returns `None` When this is not encoded as DER.
53+
pub fn der(&self) -> Option<&[u8]> {
54+
match &self.kind {
55+
CertKind::Der(der) => Some(der),
56+
_ => None,
57+
}
58+
}
59+
60+
/// Returns the reference to PEM encoded certificate.
61+
/// Returns `None` When this is not encoded as PEM.
62+
pub fn pem(&self) -> Option<&[u8]> {
63+
match &self.kind {
64+
CertKind::Pem(pem) => Some(pem),
65+
_ => None,
66+
}
67+
}
68+
69+
/// Turns this value into the DER encoded bytes.
70+
pub fn into_der(self) -> Result<Vec<u8>, Self> {
71+
match self.kind {
72+
CertKind::Der(der) => Ok(der),
73+
_ => Err(self),
74+
}
75+
}
76+
77+
/// Turns this value into the PEM encoded bytes.
78+
pub fn into_pem(self) -> Result<Vec<u8>, Self> {
79+
match self.kind {
80+
CertKind::Pem(pem) => Ok(pem),
81+
_ => Err(self),
82+
}
83+
}
4084
}
4185

4286
impl Identity {

0 commit comments

Comments
 (0)