Skip to main content

RTCCertificate

Struct RTCCertificate 

Source
pub struct RTCCertificate {
    pub dtls_certificate: Certificate,
    pub expires: SystemTime,
}
Expand description

X.509 certificate used to authenticate WebRTC peer-to-peer communications.

RTCCertificate encapsulates a DTLS certificate and its associated private key, providing secure identity verification during the WebRTC connection establishment process. Certificates can be generated on-demand or loaded from persistent storage.

§Certificate Lifetime

Each certificate has an expiration time after which it becomes invalid for use in WebRTC connections. The default lifetime depends on the platform.

§Supported Key Types

  • ECDSA P-256 with SHA-256 (recommended for performance)
  • Ed25519 (recommended for security)
  • RSA with SHA-256 (key generation not available in this implementation)

§Examples

§Generating a new certificate

    let provider = crypto::default_provider()?;
// Generate ECDSA P-256 key pair and certificate
let certificate = RTCCertificate::generate(
    provider.crypto(),
    SignatureScheme::EcdsaP256Sha256,
    CertificateParams::new(vec!["localhost".to_owned()])?,
)?;

// Certificate is ready to use
let fingerprints = certificate.get_fingerprints(provider.crypto())?;
println!("Certificate has {} fingerprint(s)", fingerprints.len());

§Generating with Ed25519

    let provider = crypto::default_provider()?;
// Generate Ed25519 key pair and certificate
let certificate = RTCCertificate::generate(
    provider.crypto(),
    SignatureScheme::Ed25519,
    CertificateParams::new(vec!["localhost".to_owned()])?,
)?;

// Get fingerprints for SDP signaling
let fingerprints = certificate.get_fingerprints(provider.crypto())?;
for fp in fingerprints {
    println!("Fingerprint ({}):\n{}", fp.algorithm, fp.value);
}

§Persisting and loading certificates

// Serialize certificate to PEM format (includes private key)
let pem_string = certificate.serialize_pem()?;

// Save to file or database...
// std::fs::write("cert.pem", &pem_string)?;

// Later, load the certificate back
let loaded_cert = RTCCertificate::from_pem(&pem_string, provider.crypto())?;
assert_eq!(loaded_cert, certificate);

§Using with RTCConfiguration

    let provider = crypto::default_provider()?;
// Generate certificate
let certificate = RTCCertificate::generate(
    provider.crypto(),
    SignatureScheme::EcdsaP256Sha256,
    CertificateParams::new(vec!["localhost".to_owned()])?,
)?;

// Configure peer connection with custom certificate
let peer_connection = RTCPeerConnectionBuilder::new()
    .with_configuration(
        RTCConfigurationBuilder::new()
            .with_certificates(vec![certificate])
            .build()
    )
    .build(Instant::now())?;

§Specifications

Fields§

§dtls_certificate: Certificate

DTLS certificate containing X.509 certificate chain and private key

§expires: SystemTime

Timestamp after which this certificate is no longer valid

Implementations§

Source§

impl RTCCertificate

Source

pub fn generate( crypto: &dyn RTCCrypto, scheme: SignatureScheme, params: CertificateParams, ) -> Result<RTCCertificate, Error>

Generates a self-signed certificate with a provider-owned signing key.

params controls X.509 formatting and validity while provider owns key generation and signing. This keeps certificate formatting independent from the primitive backend.

§Errors

Returns an error if scheme is not supported by crypto, if key generation fails, or if params cannot be encoded into a self-signed certificate.

Source

pub fn from_pkcs8( crypto: &dyn RTCCrypto, scheme: SignatureScheme, certificate_chain: Vec<CertificateDer<'static>>, private_key_der: &[u8], expires: SystemTime, ) -> Result<RTCCertificate, Error>

Imports a PKCS#8 private key through provider and associates it with an existing chain.

§Errors

Returns an error if private_key_der is not a valid PKCS#8 key for scheme, or if crypto does not support scheme.

Source

pub fn from_signing_key( certificate_chain: Vec<CertificateDer<'static>>, signing_key: Arc<dyn SigningKey>, expires: SystemTime, ) -> RTCCertificate

Builds a certificate around an application-owned signing key, including HSM/KMS keys.

Source

pub fn generate_from_signing_key( params: CertificateParams, scheme: SignatureScheme, signing_key: Arc<dyn SigningKey>, ) -> Result<RTCCertificate, Error>

Builds a self-signed certificate around an existing provider-owned signing key.

Use this when the key already exists — imported from PKCS#8 with RTCCrypto::import_signing_key, or held by an HSM/KMS — and a fresh self-signed X.509 wrapper is needed. Use generate instead when the provider should create the key too.

§Errors

Returns an error if the key does not match scheme, or if params cannot be encoded into a self-signed certificate.

This is the provider-neutral replacement for the removed from_key_pair.

Source

pub fn from_pem( pem_str: &str, crypto: &dyn RTCCrypto, ) -> Result<RTCCertificate, Error>

Parses a certificate from PEM format string.

Reconstructs an RTCCertificate from its PEM serialization, including the private key. The PEM format must match the output of serialize_pem.

§Format

The PEM string must contain two parts:

  1. An “EXPIRES” block containing the expiration timestamp
  2. The certificate and private key blocks
§Parameters
  • pem_str - PEM-encoded certificate string
§Errors

Returns an error if:

  • The PEM string is malformed or empty
  • The EXPIRES block is missing or invalid
  • The certificate data cannot be parsed
§Examples
// Load certificate from PEM string
let certificate = RTCCertificate::from_pem(&pem_str, provider.crypto())?;

// Certificate is ready to use
let fingerprints = certificate.get_fingerprints(provider.crypto())?;
println!("Loaded certificate with {} fingerprint(s)", fingerprints.len());
Source

pub fn from_existing( dtls_certificate: Certificate, expires: SystemTime, ) -> RTCCertificate

Creates an RTCCertificate from an existing DTLS certificate.

Use this method when you have a pre-existing certificate (e.g., loaded from external storage) that you want to use in WebRTC connections. This is useful for maintaining persistent identity across application restarts.

§Parameters
  • dtls_certificate - The DTLS certificate with private key
  • expires - When this certificate expires
§Note

The statistics ID will be newly generated and will differ from the original certificate if it was previously serialized. Statistics IDs are not persisted during serialization.

§Examples
// Use an externally managed certificate
let expires = SystemTime::now() + Duration::from_secs(86400 * 30); // Exemption: usage in #doctest code
let certificate = RTCCertificate::from_existing(dtls_cert, expires);

// Certificate is ready to use
let fingerprints = certificate.get_fingerprints(provider.crypto())?;
println!("Certificate has {} fingerprint(s)", fingerprints.len());
Source

pub fn serialize_pem(&self) -> Result<String, Error>

Serializes the certificate to PEM format including the private key.

Produces a PEM-encoded string containing both the certificate and its private key in PKCS#8 format. The output can be safely stored and later loaded with from_pem.

§Security Warning

The serialized output contains the private key in plain text. Store it securely and never transmit it over insecure channels or include it in client-side code.

§Format

The output contains:

  1. EXPIRES block - Certificate expiration timestamp
  2. CERTIFICATE block - X.509 certificate in DER format
  3. PRIVATE KEY block - Private key in PKCS#8 format
§Examples
// Serialize for storage
let pem_string = certificate.serialize_pem()?;

// Save to secure storage
// std::fs::write("private/cert.pem", &pem_string)?;

// Later, reload it
let reloaded = RTCCertificate::from_pem(&pem_string, provider.crypto())?;
assert_eq!(certificate, reloaded);
§Errors

Returns an error if the certificate’s private key is not exportable — a key held in an HSM or KMS has no PKCS#8 bytes to serialize.

Source

pub fn get_fingerprints( &self, crypto: &dyn RTCCrypto, ) -> Result<Vec<RTCDtlsFingerprint>, Error>

Returns SHA-256 fingerprints of the certificate chain.

Computes cryptographic fingerprints that uniquely identify this certificate. These fingerprints are used during the WebRTC handshake to verify the remote peer’s identity and are typically exchanged via SDP signaling.

§Format

Each fingerprint is a colon-separated string of hexadecimal byte pairs: "12:34:56:78:9A:BC:DE:F0:..."

§Returns

A vector of fingerprints, one for each certificate in the chain. In most cases, this will contain a single fingerprint for the self-signed certificate.

§Future Enhancement

Currently always uses SHA-256. Future versions may use the digest algorithm from the certificate signature.

§Examples
    let provider = crypto::default_provider()?;
let certificate = RTCCertificate::generate(
    provider.crypto(),
    SignatureScheme::EcdsaP256Sha256,
    CertificateParams::new(vec!["localhost".to_owned()])?,
)?;

// Get fingerprints for SDP
let fingerprints = certificate.get_fingerprints(provider.crypto())?;
for fp in fingerprints {
    println!("a=fingerprint:{} {}", fp.algorithm, fp.value);
}
§Errors

Returns an error if crypto cannot compute the digest used for the DTLS fingerprint.

Trait Implementations§

Source§

impl Clone for RTCCertificate

Source§

fn clone(&self) -> RTCCertificate

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RTCCertificate

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl PartialEq for RTCCertificate

Source§

fn eq(&self, other: &RTCCertificate) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.