MDN self-hosted library · e01.org

RTCDtlsTransport: getRemoteCertificates() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
async function getRemoteFingerprint(dtlsTransport) {
  const certs = dtlsTransport.getRemoteCertificates();
  if (certs.length === 0) {
    return null;
  }

  // Hash the raw DER-encoded certificate with SHA-256
  const digest = await crypto.subtle.digest("SHA-256", certs[0]);

  // Format as colon-separated hex, matching the SDP a=fingerprint convention
  return Array.from(new Uint8Array(digest))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join(":");
}

// Call after the DTLS handshake is complete
pc.addEventListener("connectionstatechange", async () => {
  if (pc.connectionState === "connected") {
    const sender = pc.getSenders()[0];
    if (!sender?.transport) return;

    const fingerprint = await getRemoteFingerprint(sender.transport);
    if (!fingerprint) return;
    const stored = localStorage.getItem("remote-peer-fingerprint");

    if (!stored) {
      localStorage.setItem("remote-peer-fingerprint", fingerprint);
    } else if (stored !== fingerprint) {
      console.error("Certificate mismatch — closing connection");
      pc.close();
    }
  }
});