Guides

Browser-to-browser file transfer with WebRTC and E2E encryption

How a file gets from a phone to a computer inside the browser, who can read it on the way, and what to ask a vendor before you trust it.

By BeamFieldPublished 8 min read
View as Markdown

Three ways to move a file between two browsers

A visitor is filling in a claim form on a laptop, and the photo they need is on their phone. The file can travel in only three ways, and what separates them is who can read it on the way.

RouteHow it worksWho can read the file
Upload, then downloadThe phone uploads to a server, the computer downloads from itThe server operator, while the file is stored, unless it was encrypted before upload
RelayA server forwards bytes between two connections and stores nothingThe relay operator, while the bytes pass, unless they are encrypted end to end
Direct peer-to-peerThe two browsers connect to each otherOnly the two browsers, provided nobody tampered with the connection setup

TLS does not change the first two rows: HTTPS protects each hop, but the server sits at the end of both and handles the file in the clear. The third row carries a condition, the subject of most of this guide.

WebRTC in plain terms

WebRTC is the browser technology behind video calls, and it also carries arbitrary data (MDN overview). Four terms matter:

  • Signaling is the exchange needed before the browsers can talk directly: a session description (SDP) and a list of network addresses. WebRTC does not define how these messages travel, so every product runs its own signaling server.
  • ICE (RFC 8445) collects candidate addresses on each side, tests the pairs and keeps one that works.
  • STUN tells a browser which public address it has from outside its router. It sees an IP address and a port, not the file.
  • TURN (RFC 8656) is the fallback when no direct path exists: both browsers send their packets to a relay, which forwards them.

A data channel is a message pipe on top of that connection, defined in RFC 8831 as SCTP carried inside DTLS. By default it delivers messages reliably and in order, like a WebSocket between two browsers.

const pc = new RTCPeerConnection({
  iceServers: [{ urls: "stun:stun.example.org:3478" }],
});
const channel = pc.createDataChannel("file", { ordered: true });
channel.binaryType = "arraybuffer";

const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
// Send pc.localDescription through the signaling server.

What WebRTC encrypts by itself, and where that stops

Encryption is not optional in WebRTC: RFC 8827 requires every data channel to be secured with DTLS, the datagram variant of TLS. The handshake runs directly between the two browsers, so a network observer or a relay sees only ciphertext.

The weak point is how each browser knows it is talking to the right peer. Its certificate is self-signed, so no authority vouches for it. Its fingerprint (a hash) goes into the session description instead, and those descriptions travel through the signaling server. A malicious or compromised signaling server can swap in its own fingerprints, sit in the middle and decrypt everything, unnoticed. RFC 8826 says so in section 4.3.2: the calling service can mount a man-in-the-middle attack unless the endpoints are authenticated independently.

So "peer-to-peer and encrypted with DTLS" means encrypted against the network, not encrypted against the vendor. To cover the vendor, the two browsers need a secret the signaling server never sees.

Adding end-to-end encryption with the Web Crypto API

The fix is a second layer of encryption, applied by the page before data enters the channel. Browsers provide the primitives in crypto.subtle. A sound design has five parts:

  • AES-GCM. An authenticated mode (NIST SP 800-38D): decryption fails if a single bit of the ciphertext was changed, so it protects integrity as well as confidentiality.
  • One key per transfer. A random 256-bit key is generated in the browser for each handoff, then discarded.
  • Chunking. The file is cut into pieces of 16 to 64 KiB, each encrypted separately, so a large file never sits in memory as one block.
  • A unique nonce per chunk. GCM fails badly if a key is used twice with the same nonce (the iv parameter). MDN is blunt: never reuse an IV with the same key. With a single-transfer key, a 96-bit nonce built from a chunk counter is simple and safe. If both devices send, or one key covers several files, the direction and file number belong in the nonce too.
  • Authenticated metadata. The receiver derives each nonce from its own counter, so a reordered or replayed chunk fails to decrypt. A "last chunk" flag passed as additionalData is authenticated without being encrypted, which prevents silent truncation. File name, type and size travel in an encrypted first message, not in signaling.
const key = await crypto.subtle.generateKey(
  { name: "AES-GCM", length: 256 },
  true, // extractable: exported into the QR code
  ["encrypt", "decrypt"],
);

async function encryptChunk(key, index, isLast, plaintext) {
  const iv = new Uint8Array(12); // 96-bit nonce
  new DataView(iv.buffer).setUint32(8, index); // chunk counter
  const additionalData = new Uint8Array([isLast ? 1 : 0]);
  const ciphertext = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv, additionalData },
    key,
    plaintext,
  );
  return new Uint8Array(ciphertext); // ciphertext + 16-byte tag
}

Getting the key to the phone without showing it to the server

The key is created on the computer and has to reach the phone. The QR code offers a channel the server cannot observe: the screen and the camera.

The usual technique puts the key in the fragment of the URL in the QR code, the part after #. RFC 9110 specifies that the target of an HTTP request excludes the fragment, which is reserved for client-side processing, and MDN states the consequence: the fragment is not sent to the server.

const hex = new URLSearchParams(location.hash.slice(1)).get("k") ?? ""; // "#k=..."
if (!/^[0-9a-f]{64}$/.test(hex)) throw new Error("Missing or malformed key");
const rawKey = Uint8Array.from(hex.match(/../g), (pair) => parseInt(pair, 16));

const key = await crypto.subtle.importKey("raw", rawKey, "AES-GCM", false, ["encrypt", "decrypt"]);
history.replaceState(null, "", location.pathname + location.search); // drop the key

The limits:

  • The page's own JavaScript can read the fragment. That is how the scheme works, and also its weakness: the server that delivers the script could deliver one that sends the key home. End-to-end encryption in a web page is only as trustworthy as the script that performs it.
  • Script integrity therefore matters. Ask whether third-party scripts run on the page that reads the key, and whether a strict Content-Security-Policy limits which scripts may run and where the page may send data.
  • The fragment stays in the phone's browser history unless the page removes it (last line above).
  • Anyone who photographs the QR code has the key. Short-lived sessions limit the damage.

What a TURN relay sees

When ICE finds no direct path, traffic goes through a TURN relay, which sees the IP addresses of both devices, the timing and the volume of data. It does not see the content: the DTLS session runs between the two browsers, so the relay forwards ciphertext. RFC 8656 itself advises applications that want end-to-end security to encrypt what they send.

Practical limits

  • File size and backpressure. send() queues data without waiting for the network, and throws once the buffer is full. Read the file slice by slice, watch bufferedAmount, pause above a ceiling and resume on the bufferedamountlow event.
  • Mobile browsers suspend background pages. If the visitor switches apps or the screen locks, the phone may freeze the page and the connection times out. The interface should say so and fail cleanly.
  • Restrictive corporate networks. Firewalls that block UDP defeat direct connections. TURN can run over TCP or TLS for that reason, but some networks block that too, so the ordinary file picker must stay available.
  • Secure context. crypto.subtle exists only on pages served over HTTPS (or from localhost). On plain HTTP it is undefined, and a well-built product then refuses to send.

Worked example: BeamField

BeamField applies this design to one case. It adds a "Use phone" button beside an existing <input type="file">. The visitor scans a QR code, and the phone sends the file to the desktop browser over a WebRTC data channel.

  • Every file is encrypted end to end with AES-256-GCM. One 256-bit key is created per handoff in the visitor's browser, carried in the fragment of the QR code's URL and never sent to BeamField. On HTTPS, the browser refuses to transfer without it.
  • Signaling runs over TLS, with separate access tokens for the computer and the phone, stored only as hashes. Sessions expire after ten minutes.
  • BeamField's servers store no files, no file names and no IP addresses.
  • When the two browsers cannot connect directly, the encrypted traffic passes through a relay that sees IP addresses and encrypted bytes only.
  • The service is hosted in the European Union.

Details are in the trust centre, and you can try the handoff in the integration lab.

Questions to ask any vendor

  1. Can your servers read the file at any point? If not, what prevents it technically?
  2. Where is the key generated, how does it reach the second device, and does it ever appear in a request to your servers?
  3. Which algorithm and mode do you use, is there one key per transfer, and how are nonces built?
  4. What does the page do when encryption is unavailable: refuse, or send anyway?
  5. Which scripts run on the page that holds the key, and which Content-Security-Policy applies?
  6. What do the signaling server and the relay log, for how long, and who operates the relays?
  7. Is a data processing agreement available, and who are the sub-processors?

The GDPR angle in brief

  • Data minimisation (Article 5(1)(c)). A vendor that never receives the readable file collects less than an upload service.
  • The provider is normally a processor. It handles personal data on behalf of the site that embeds the feature, so a contract under Article 28 is needed. The EDPB guidelines on controllers and processors explain how to qualify the roles.
  • Some personal data remains. IP addresses are personal data, and signaling and relay servers must handle them to route traffic, even if they do not store them. Session descriptions contain network addresses too, and timestamps and session identifiers are metadata to record.

End-to-end encryption narrows what the vendor can access. It does not change your own obligations once the document lands in your form.

FAQ

Is WebRTC end-to-end encrypted by default?

It is encrypted between the two browsers with DTLS. However, the fingerprints that authenticate the peers pass through the signaling server, which could intercept the connection if compromised. An application-level key the server never sees closes that gap.

Can the server see the key in the QR code?

Not if the key is in the URL fragment, which browsers leave out of HTTP requests. The page's JavaScript can read it, though, so the integrity of that script is the thing to review.

Does a TURN relay weaken the encryption?

No. It changes the route, not the protection. The relay sees both IP addresses and forwards bytes it cannot decrypt.

How does BeamField handle the key?

BeamField creates one 256-bit AES-GCM key per handoff in the visitor's browser and carries it in the QR code's URL fragment, so its servers never receive it. See the trust centre and the data processing agreement, or browse all guides.

More guides