diff --git a/docs/guide/networking/peer-connection-config.md b/docs/guide/networking/peer-connection-config.md index 0af54cab..2a034deb 100644 --- a/docs/guide/networking/peer-connection-config.md +++ b/docs/guide/networking/peer-connection-config.md @@ -75,6 +75,18 @@ config.cryptoOptions = crypto; `certificates` takes the DTLS certificate a peer connection authenticates with, as an `RTCCertificatePEM`. Without one, WebRTC generates a certificate per connection. A certificate that does not parse makes `createPeerConnection()` and `setConfiguration()` throw. +A connection's certificate decides the DTLS fingerprint in its session description. To keep the same fingerprint across connections, so that a remote peer can recognize this one again, generate a certificate once, store it, and pass it to every connection: + +```java +RTCCertificatePEM certificate = RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA, Duration.ofDays(365)); + +// Store certificate.getPrivateKey() and certificate.getCertificate(), e.g. in a key store. + +config.certificates.add(certificate); +``` + +`generate` makes a self-signed certificate with a new key on the calling thread. `ECDSA` (P-256) takes milliseconds, `RSA` (2048 bits) takes far longer. Without a lifetime, a certificate is valid for 30 days; the lifetime can be at most a year. The private key is a secret: keep it where only your application can read it. + The expiration time passed to its constructor is informational: WebRTC takes it from the certificate. The certificates that `getConfiguration()` and `RTCDtlsTransport.getRemoteCertificates()` return carry that time in `getExpires()`, in milliseconds since the Unix epoch. If it cannot be read, `getExpires()` returns `RTCCertificatePEM.EXPIRES_UNKNOWN` (-1). ## Signaling diff --git a/webrtc-jni/src/main/cpp/include/JNI_RTCCertificatePEM.h b/webrtc-jni/src/main/cpp/include/JNI_RTCCertificatePEM.h new file mode 100644 index 00000000..cf313ffc --- /dev/null +++ b/webrtc-jni/src/main/cpp/include/JNI_RTCCertificatePEM.h @@ -0,0 +1,21 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class dev_onvoid_webrtc_RTCCertificatePEM */ + +#ifndef _Included_dev_onvoid_webrtc_RTCCertificatePEM +#define _Included_dev_onvoid_webrtc_RTCCertificatePEM +#ifdef __cplusplus +extern "C" { +#endif + /* + * Class: dev_onvoid_webrtc_RTCCertificatePEM + * Method: generateCertificate + * Signature: (IJ)Ldev/onvoid/webrtc/RTCCertificatePEM; + */ + JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCCertificatePEM_generateCertificate + (JNIEnv *, jclass, jint, jlong); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCCertificatePEM.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCCertificatePEM.cpp new file mode 100644 index 00000000..5fee168f --- /dev/null +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCCertificatePEM.cpp @@ -0,0 +1,54 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "JNI_RTCCertificatePEM.h" +#include "JavaBoundary.h" +#include "JavaUtils.h" +#include "rtc/RTCCertificatePEM.h" + +#include "rtc_base/rtc_certificate_generator.h" +#include "rtc_base/ssl_identity.h" + +#include +#include + +JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCCertificatePEM_generateCertificate +(JNIEnv * env, jclass, jint keyType, jlong lifetimeMillis) +{ + return jni::CallFromJava(env, [&]() -> jobject { + // The order of RTCCertificateKeyType. + webrtc::KeyParams params = keyType == 1 + ? webrtc::KeyParams::RSA() + : webrtc::KeyParams::ECDSA(webrtc::EC_NIST_P256); + + std::optional expires; + + if (lifetimeMillis > 0) { + expires = static_cast(lifetimeMillis); + } + + // On the calling thread, which the Java side leaves to the application. + webrtc::scoped_refptr certificate = + webrtc::RTCCertificateGenerator::GenerateCertificate(params, expires); + + if (!certificate) { + ThrowJavaException(env, "java/lang/IllegalStateException", "Generating the certificate failed"); + return nullptr; + } + + return jni::RTCCertificatePEM::toJava(env, *certificate).release(); + }); +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCCertificateKeyType.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCCertificateKeyType.java new file mode 100644 index 00000000..bfcb2c81 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCCertificateKeyType.java @@ -0,0 +1,38 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc; + +/** + * The kind of key a certificate made by {@link + * RTCCertificatePEM#generate(RTCCertificateKeyType)} has. + * + * @author Alex Andres + */ +public enum RTCCertificateKeyType { + + /** + * An ECDSA key on the NIST P-256 curve. It is what WebRTC uses by default, + * and is made in a fraction of the time an RSA key takes. + */ + ECDSA, + + /** + * An RSA key of 2048 bits, for peers that do not accept ECDSA. + */ + RSA + +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCCertificatePEM.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCCertificatePEM.java index 3ed64f52..3fe27b17 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCCertificatePEM.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCCertificatePEM.java @@ -16,6 +16,12 @@ package dev.onvoid.webrtc; +import static java.util.Objects.requireNonNull; + +import java.time.Duration; + +import dev.onvoid.webrtc.internal.NativeLoader; + /** * Represents a certificate used to authenticate WebRTC communications. This * class contains PEM strings of an RTCCertificate's private key and @@ -25,6 +31,21 @@ */ public class RTCCertificatePEM { + static { + try { + NativeLoader.loadLibrary("webrtc-java"); + } + catch (Exception e) { + throw new RuntimeException("Load library 'webrtc-java' failed", e); + } + } + + /** + * The longest lifetime of a certificate made by {@link + * #generate(RTCCertificateKeyType, Duration)}, as WebRTC limits it. + */ + public static final Duration MAX_LIFETIME = Duration.ofDays(365); + /** * The value of {@link #getExpires()} for a certificate whose expiration * time cannot be read. No actual expiration time has this value: those @@ -92,4 +113,65 @@ public String getCertificate() { public long getExpires() { return expires; } + + /** + * Generates a new self-signed certificate with a new private key, as + * {@code RTCPeerConnection.generateCertificate} of the WebRTC + * specification does, valid for 30 days. + * + * @param keyType The kind of key to make. + * + * @return The new certificate. + * + * @see #generate(RTCCertificateKeyType, Duration) + */ + public static RTCCertificatePEM generate(RTCCertificateKeyType keyType) { + requireNonNull(keyType, "keyType"); + + return generateCertificate(keyType.ordinal(), 0); + } + + /** + * Generates a new self-signed certificate with a new private key, as + * {@code RTCPeerConnection.generateCertificate} of the WebRTC + * specification does. + *

+ * A peer connection makes a certificate of its own unless {@link + * RTCConfiguration#certificates} has one. Its DTLS fingerprint, which the + * session description carries, therefore changes with every connection. + * An application that keeps a certificate, e.g. in a key store, and + * passes it to every connection keeps the fingerprint, so that a remote + * peer can recognize it again. + *

+ * The key is made on the calling thread. An ECDSA key takes milliseconds, + * an RSA key can take far longer. + * + * @param keyType The kind of key to make. + * @param lifetime How long the certificate is valid from now, at most + * {@link #MAX_LIFETIME}. + * + * @return The new certificate, with its private key. + * + * @throws IllegalArgumentException if the lifetime is not positive or + * longer than {@link #MAX_LIFETIME}. + * @throws IllegalStateException if the certificate could not be made. + */ + public static RTCCertificatePEM generate(RTCCertificateKeyType keyType, Duration lifetime) { + requireNonNull(keyType, "keyType"); + requireNonNull(lifetime, "lifetime"); + + if (lifetime.isNegative() || lifetime.isZero() || lifetime.compareTo(MAX_LIFETIME) > 0) { + throw new IllegalArgumentException("The lifetime must be positive and at most " + + MAX_LIFETIME.toDays() + " days, got " + lifetime); + } + + // At least a millisecond, which 0 would not be. + return generateCertificate(keyType.ordinal(), Math.max(1, lifetime.toMillis())); + } + + /* + * Generates a certificate of the RTCCertificateKeyType with the ordinal, + * valid for the given milliseconds, or the default lifetime for 0. + */ + private static native RTCCertificatePEM generateCertificate(int keyType, long lifetimeMillis); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCCertificateGenerateTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCCertificateGenerateTests.java new file mode 100644 index 00000000..3bcb65f3 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCCertificateGenerateTests.java @@ -0,0 +1,171 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +/** + * Tests the certificates that {@link RTCCertificatePEM#generate} makes. + */ +@Execution(ExecutionMode.SAME_THREAD) +class RTCCertificateGenerateTests extends TestBase { + + @Test + void ecdsaValidFor30Days() throws Exception { + long now = System.currentTimeMillis(); + RTCCertificatePEM certificate = RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA); + + assertTrue(certificate.getCertificate().startsWith("-----BEGIN CERTIFICATE-----")); + assertTrue(certificate.getPrivateKey().contains("PRIVATE KEY"), certificate.getPrivateKey()); + assertEquals("EC", x509(certificate).getPublicKey().getAlgorithm()); + + assertExpires(certificate, now, Duration.ofDays(30)); + } + + @Test + void rsaWithLifetime() throws Exception { + long now = System.currentTimeMillis(); + RTCCertificatePEM certificate = RTCCertificatePEM.generate(RTCCertificateKeyType.RSA, Duration.ofDays(2)); + + assertTrue(certificate.getPrivateKey().contains("PRIVATE KEY"), certificate.getPrivateKey()); + assertEquals("RSA", x509(certificate).getPublicKey().getAlgorithm()); + + assertExpires(certificate, now, Duration.ofDays(2)); + } + + @Test + void eachCertificateNew() { + RTCCertificatePEM first = RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA); + RTCCertificatePEM second = RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA); + + assertNotEquals(first.getPrivateKey(), second.getPrivateKey()); + assertNotEquals(first.getCertificate(), second.getCertificate()); + } + + @Test + void lifetimeChecked() { + assertThrows(IllegalArgumentException.class, + () -> RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA, Duration.ZERO)); + assertThrows(IllegalArgumentException.class, + () -> RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA, Duration.ofSeconds(-1))); + assertThrows(IllegalArgumentException.class, + () -> RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA, + RTCCertificatePEM.MAX_LIFETIME.plusSeconds(1))); + assertThrows(NullPointerException.class, () -> RTCCertificatePEM.generate(null)); + + long now = System.currentTimeMillis(); + + assertExpires(RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA, RTCCertificatePEM.MAX_LIFETIME), + now, RTCCertificatePEM.MAX_LIFETIME); + } + + @Test + void certificateKeepsFingerprint() throws Exception { + RTCCertificatePEM certificate = RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA); + + String first = fingerprint(certificate); + String second = fingerprint(certificate); + + assertEquals(first, second); + // A connection without one makes a certificate of its own. + assertNotEquals(first, fingerprint(null)); + } + + @Test + void certificateReadBack() { + RTCCertificatePEM certificate = RTCCertificatePEM.generate(RTCCertificateKeyType.ECDSA); + RTCConfiguration config = new RTCConfiguration(); + config.certificates.add(certificate); + + RTCPeerConnection connection = factory.createPeerConnection(config, candidate -> { }); + + try { + List certificates = connection.getConfiguration().certificates; + + assertEquals(1, certificates.size()); + assertEquals(certificate.getCertificate(), certificates.get(0).getCertificate()); + assertEquals(certificate.getExpires(), certificates.get(0).getExpires()); + } + finally { + connection.close(); + } + } + + /** The DTLS fingerprint in the offer of a connection with the certificate. */ + private String fingerprint(RTCCertificatePEM certificate) throws Exception { + RTCConfiguration config = new RTCConfiguration(); + + if (certificate != null) { + config.certificates.add(certificate); + } + + RTCPeerConnection connection = factory.createPeerConnection(config, candidate -> { }); + + try { + RTCDataChannel channel = connection.createDataChannel("data", new RTCDataChannelInit()); + TestCreateDescObserver offer = new TestCreateDescObserver(); + + connection.createOffer(new RTCOfferOptions(), offer); + + String sdp = offer.get(5, TimeUnit.SECONDS).sdp; + channel.dispose(); + + for (String line : sdp.split("\r\n")) { + if (line.startsWith("a=fingerprint:")) { + return line; + } + } + + throw new AssertionError("No fingerprint in " + sdp); + } + finally { + connection.close(); + } + } + + private static X509Certificate x509(RTCCertificatePEM certificate) throws Exception { + byte[] pem = certificate.getCertificate().getBytes(StandardCharsets.US_ASCII); + + return (X509Certificate) CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(pem)); + } + + private static void assertExpires(RTCCertificatePEM certificate, long now, Duration lifetime) { + long expires = certificate.getExpires(); + long expected = now + lifetime.toMillis(); + + // Read from the certificate in whole seconds. + assertTrue(Math.abs(expires - expected) < TimeUnit.MINUTES.toMillis(1), + "Expires " + expires + ", expected about " + expected); + } + +}