是否存在在Lua中生成服务器响应密钥的现有功能?这是python中的解决方案:websocket handshake problem
我确实捕获了两个关键数字,计算了空格,捕获了第三个字符串,并希望其余部分位于现有函数中...
答案 0 :(得分:2)
如果需要较旧的握手(协议0),您可以使用以下代码从两个密钥获取握手值:
md5 = require 'md5'
function getnumbers(str)
local num = ""
str:gsub('%d', function(d) num = num .. d end)
return tonumber(num)
end
function countspaces(str)
return select(2, str:gsub(' ', ' '))
end
function to32bitint(i)
return string.char(i/256^3 % 256, i/256^2 % 256, i/256 % 256, i % 256)
end
function websocketresponse(key1, key2, end8)
local n1, s1 = getnumbers(key1), countspaces(key1)
local n2, s2 = getnumbers(key2), countspaces(key2)
local cat = to32bitint(n1/s1) .. to32bitint(n2/s2) .. ending8
return md5.sum(cat)
end
websocket_key1 = "18x 6]8vM;54 *(5: { U1]8 z [ 8"
websocket_key2 = "1_ tx7X d < nw 334J702) 7]o}` 0"
ending8 = "Tm[K T2u"
print(websocketresponse(websocket_key1, websocket_key2, ending8))
--> fQJ,fN/4F4!~K~MH
这与the protocol draft中给出的示例产生的值相同。此示例使用MD5库来计算校验和,并在LuaForWindows中编译。
WebSocket协议版本6的实现要简单得多:
crypto = require 'crypto'
mime = require 'mime'
function websocketresponse6(key)
local magic = key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
return (mime.b64(crypto.digest('sha1', magic, true)))
end
key6 = "x3JJHMbDL1EzLkh9GBhXDw=="
print(websocketresponse6(key6))
--> HSmrc0sMlYUkAGmm5OPpG2HaGWk=
答案 1 :(得分:0)