I am writing a TCP socket server application to accept data from an Angular application. Within the server application I want to return a response header to a web-socket request, however in generating the base64 of an hash I get a value that is long (and incorrect), and therefore the handshaking fails.
I am using the TNetCoding
class in the System.NetEncoding
unit to do the encoding. An example is found at https://flixengineering.com/archives/270.
I'm getting something like:
YWRiYzRlYmJiMDkyZmM2MzNjMGJjMGZjNGY0YjQwOTllZjVhNWMxMw==
procedure TServerForm.SendHeader(key: string);
var
hash, ret, encod: string;
const
magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
begin
hash := trim(key) + magic;
ret := GenStrHashSHA1(hash);
encod := TNetEncoding.Base64.Encode(ret);
CliSocket.SendStr('HTTP/1.1 101 Switching Protocols' + #13#10 +
'Upgrade: websocket' + #13#10 +
'Connection: Upgrade' + #13#10 +
'Sec-WebSocket-Accept: ' + encod + #13#10 + #13#10);
Memo2.Lines.Add('Header was sent');
end;
/* Hash Function */
function TServerForm.GenStrHashSHA1(Str: String): String;
var
HashSHA: THashSHA1;
begin
HashSHA := THashSHA1.Create;
HashSHA.GetHashString(Str);
result := HashSHA.GetHashString(Str);
end;
For Example:
Incoming request:
GET / HTTP/1.1
Host: localhost:12345
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://localhost:4200
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Sec-WebSocket-Key: ky8at6EtBZLocDhJU7hMnw==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Hash generated:
c289980eb715b3e19107152dc21f075c9f7bf539
Base64 string generated:
YzI4OTk4MGViNzE1YjNlMTkxMDcxNTJkYzIxZjA3NWM5ZjdiZjUzOQ==
Update: Here is another example:
WebSocket key received:
Nk1L3oS2Q7LHdoGP2Uyn7Q==
Decimal value displayed in debugging:
String generated:
F68FCEE74F044B57E9047395B975A31A6ABEBDD2