Skip to content

Commit 3507ce9

Browse files
committed
un-cache sha1
1 parent 6c4a760 commit 3507ce9

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

src/Middleware/WebSockets/src/HandshakeHelpers.cs

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,6 @@ internal static class HandshakeHelpers
3232
(byte)'B', (byte)'0', (byte)'D', (byte)'C', (byte)'8', (byte)'5', (byte)'B', (byte)'1', (byte)'1'
3333
};
3434

35-
[ThreadStatic]
36-
private static SHA1 _algorithm;
37-
3835
// Verify Method, Upgrade, Connection, version, key, etc..
3936
public static bool CheckSupportedWebSocketRequest(string method, IEnumerable<KeyValuePair<string, string>> headers)
4037
{
@@ -112,25 +109,23 @@ public static string CreateResponseKey(string requestKey)
112109
// this concatenated value to obtain a 20-byte value and base64-encoding"
113110
// https://tools.ietf.org/html/rfc6455#section-4.2.2
114111

115-
if (_algorithm == null)
112+
using (var algorithm = SHA1.Create())
116113
{
117-
_algorithm = SHA1.Create();
118-
}
119-
120-
// requestKey is already verified to be small (24 bytes) by 'IsRequestKeyValid()' and everything is 1:1 mapping to UTF8 bytes
121-
// so this can be hardcoded to 60 bytes for the requestKey + static websocket string
122-
Span<byte> mergedBytes = stackalloc byte[60];
123-
Encoding.UTF8.GetBytes(requestKey, mergedBytes);
124-
_encodedWebSocketKey.CopyTo(mergedBytes.Slice(24));
114+
// requestKey is already verified to be small (24 bytes) by 'IsRequestKeyValid()' and everything is 1:1 mapping to UTF8 bytes
115+
// so this can be hardcoded to 60 bytes for the requestKey + static websocket string
116+
Span<byte> mergedBytes = stackalloc byte[60];
117+
Encoding.UTF8.GetBytes(requestKey, mergedBytes);
118+
_encodedWebSocketKey.CopyTo(mergedBytes.Slice(24));
119+
120+
Span<byte> hashedBytes = stackalloc byte[20];
121+
var success = algorithm.TryComputeHash(mergedBytes, hashedBytes, out var written);
122+
if (!success || written != 20)
123+
{
124+
throw new InvalidOperationException("Could not compute the hash for the 'Sec-WebSocket-Accept' header.");
125+
}
125126

126-
Span<byte> hashedBytes = stackalloc byte[20];
127-
var success = _algorithm.TryComputeHash(mergedBytes, hashedBytes, out var written);
128-
if (!success || written != 20)
129-
{
130-
throw new InvalidOperationException("Could not compute the hash for the 'Sec-WebSocket-Accept' header.");
127+
return Convert.ToBase64String(hashedBytes);
131128
}
132-
133-
return Convert.ToBase64String(hashedBytes);
134129
}
135130
}
136131
}

0 commit comments

Comments
 (0)