Video in progress

What are the Sec-WebSocket-Key and Sec-WebSocket-Accept headers in the handshake for? Do they provide security?

The server appends a fixed GUID to Sec-WebSocket-Key, takes the SHA-1, Base64-encodes it, and returns it as Sec-WebSocket-Accept. This is only proof that "the server really understands WebSocket". It is neither authentication nor encryption.

📖 Answer

The calculation looks like this:

String accept = Base64.getEncoder().encodeToString(
    MessageDigest.getInstance("SHA-1").digest(
        (clientKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
            .getBytes(StandardCharsets.US_ASCII)));

The goal is to prevent accidental mix-ups. For example, an ordinary HTTP server or a caching proxy might return 200 even though it doesn't understand the upgrade request. If the client doesn't see the correct Accept value, it rejects the connection. It also rules out serving an old response from a cache, because the key is new every time.

This is where people slip up in interviews: this key gives no confidentiality at all. Anyone can compute it. Checking who is connecting is done with a token, a cookie and an Origin check, and encryption comes from wss:// (TLS).

Spring, Tomcat or Undertow handle these headers for you. You'll never need to write them by hand.