brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Compute a Sec-WebSocket-Accept value with openssl

Web-Development
~/tips/tip-websockets-sec-websocket-accept-openssl

| openssl dgst -sha1 -binary | openssl base64

Reproduce the Sec-WebSocket-Accept header of a WebSocket handshake from the client key with three openssl steps.

A WebSocket handshake that fails behind a proxy often ends with the client closing the connection and saying very little. One thing you can check by hand is the Sec-WebSocket-Accept header the server sent back.

RFC 6455 defines the value: take the client’s Sec-WebSocket-Key as a string, without base64-decoding it, append the fixed GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, hash that with SHA-1 and base64-encode the 20 raw bytes. With openssl:

printf '%s' 'dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11' \
  | openssl dgst -sha1 -binary | openssl base64

The key in that command is the example key from the RFC. On OpenSSL 3.0.13 it prints s3pPLMBiTxaQ9kYGzzhZRbK+xOo=, which is the accept value the RFC lists for it. For a real handshake, paste the key from the request headers in front of the GUID.

Why it matters: the RFC says a client must fail the connection when the response has no Sec-WebSocket-Accept header or a different value. A proxy or test server that gets it wrong makes the browser give up.

Two details in the command are easy to get wrong. Use printf '%s' instead of echo, because a trailing newline would change the hash. And keep -binary: without it openssl prints a hex digest, and base64 of the hex text is a different string.

Further reading: RFC 6455, section 1.3 opening handshake

More Web-Development tips const ws = new WebSocket("wss://example.com/chat"); curl -si -X OPTIONS \ ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" All Web-Development tips (70) All topics

Link