更新于 2024-01-11
public class Accepter
{
private static readonly byte[] salt_ = Encoding.ASCII.GetBytes("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
private static string SHA1(byte[] clearData)
{
using System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
return Convert.ToBase64String(sha1.ComputeHash(clearData));
}
/// <summary>
/// 生成Sec-WebSocket-Accept标头
/// </summary>
/// <param name="secWebSocketKey">客户端发送的Sec-WebSocket-Key标头</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static string Accept(string secWebSocketKey)
{
byte[] clearKey = Encoding.ASCII.GetBytes(secWebSocketKey);
return SHA1([.. clearKey, .. salt_]);
}
}
//测试
Console.WriteLine(Accepter.Accept("D6ek6vlDxp9QYDNFz1avWA=="));
//输出
//3n54130uwt5msP8XRJ6RxWjBg1c=