리셋 되지 말자

[websocket] Sec-WebSocket-Key 변환 본문

websocket

[websocket] Sec-WebSocket-Key 변환

kyeongjun-dev 2020. 4. 12. 01:48
def handshake(client):
    request = client.recv(2048)
    p=re.compile('Sec-WebSocket-Key: (.*)\\r')
    m = p.search(request.decode())

    #key = m.group(1)+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
    key = 'dGhlIHNhbXBsZSBub25jZQ=='+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
    h=hashlib.sha1()
    h.update(key.encode())

    #sh1_key = hashlib.sha1().digest()
    base64_key = base64.b64encode(h.digest())
    print(base64_key.decode())

    response = "HTTP/1.1 101 Switching Protocols\r\n"+\
           "Upgrade: websocket\r\n"+\
           "Connection: Upgrade\r\n"+\
           "Sec-WebSocket-Accept: %s\r\n"+\
           "\r\n"

client로부터 정보를 받고, 정규식으로 Sec-WebSocket-Key만 추출한다.

https://developer.mozilla.org/ko/docs/WebSockets/Writing_WebSocket_servers 사이트에 예제인

'dGhlIHNhbXBsZSBub25jZQ=='+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11' 을 key로 하여, sha1 및 base64encode 한다.

결과로 's3pPLMBiTxaQ9kYGzzhZRbK+xOo=' 가 나왔다. 성공!! ㅠㅠㅠㅠㅠㅠㅠㅠ

Comments