http – 从“Sec-WebSocket-Key”生成“Sec-WebSocket-Accept”

我跟随rfc6455

Concretely, if as in the example above, the |Sec-WebSocket-Key|
header field had the value “dGhlIHNhbXBsZSBub25jZQ==”, the server
would concatenate the string “258EAFA5-E914-47DA-95CA-C5AB0DC85B11”
to form the string “dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-
C5AB0DC85B11″. The server would then take the SHA-1 hash of this,
giving the value 0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6
0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea. This value is
then base64-encoded (see Section 4 of [RFC4648]), to give the value
“s3pPLMBiTxaQ9kYGzzhZRbK+xOo=”. This value would then be echoed in
the |Sec-WebSocket-Accept| header field.

并且无法生成正确的“Sec-WebSocket-Accept”.

为了理解我在线使用SHA1 hashBase64 Encode的过程.

用于“dGhlIHNhbXBsZSBub25jZQ == 258EAFA5-E914-47DA-95CA-C5AB0DC85B11”的online SHA1 hash给出了正确的结果:“b37a4f2cc0624f1690f64606cf385945b2bec4ea”,如rfc6455中所述.

但是对于输入“b37a4f2cc0624f1690f64606cf385945b2bec4ea”,online Base64 Encode给出了错误的结果“YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ ==”.
结果应为“s3pPLMBiTxaQ9kYGzzhZRbK xOo =”

我究竟做错了什么?

您需要对原始sha1摘要进行base64编码.
您正在编码摘要的十六进制字符串表示形式,它是长度的两倍.

在线工具使用文本,不适用于原始二进制数据,这就是为什么你得到错误的结果.

Python示例:

import hashlib, base64
h = hashlib.sha1("dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
print "hexdigest:", h.hexdigest() # hexadecimal string representation of the digest
print "digest:", h.digest() # raw binary digest
print
print "wrong result:", base64.b64encode(h.hexdigest())
print "right result:", base64.b64encode(h.digest())

这打印:

hexdigest: b37a4f2cc0624f1690f64606cf385945b2bec4ea
digest: ᄈzO,ÀbOミöFÏ8YEᄇᄒÄê

wrong result: YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ==
right result: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
https://stackoverflow.com/questions/35977916/generate-sec-websocket-accept-from-sec-websocket-key

转载注明原文:http – 从“Sec-WebSocket-Key”生成“Sec-WebSocket-Accept”