XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

LumaTunnel

【WinUI】LumaTunnel 是一个面向个人多设备的 Windows 代理系统。客户端在本机提供 HTTP/HTTPS CONNECT 与 SOCKS5 TCP 代理,并通过一个受信任 TLS 证书保护的 WSS 会话,将多个 TCP 流复用到自建 Windows Server 节点。

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Security.Cryptography;

namespace LumaTunnel.Server.Core.Security;

public static class TokenUtilities
{
    public static string CreateDeviceToken() => Base64UrlEncode(RandomNumberGenerator.GetBytes(32));

    public static string CreatePairingCode() => Base64UrlEncode(RandomNumberGenerator.GetBytes(16));

    public static string Hash(string value)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(value);
        return Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value)));
    }

    public static bool FixedTimeHashEquals(string value, string expectedHash)
    {
        if (string.IsNullOrWhiteSpace(value) || expectedHash.Length != 64)
            return false;

        Span<byte> actual = stackalloc byte[32];
        Span<byte> expected = stackalloc byte[32];
        SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value), actual);
        if (!TryDecodeHex(expectedHash, expected))
            return false;

        return CryptographicOperations.FixedTimeEquals(actual, expected);
    }

    private static string Base64UrlEncode(byte[] bytes) =>
        Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');

    private static bool TryDecodeHex(ReadOnlySpan<char> value, Span<byte> destination)
    {
        if (value.Length != destination.Length * 2)
            return false;

        for (var i = 0; i < destination.Length; i++)
        {
            var high = HexValue(value[i * 2]);
            var low = HexValue(value[(i * 2) + 1]);
            if (high < 0 || low < 0)
                return false;
            destination[i] = (byte)((high << 4) | low);
        }

        return true;
    }

    private static int HexValue(char value) => value switch
    {
        >= '0' and <= '9' => value - '0',
        >= 'a' and <= 'f' => value - 'a' + 10,
        >= 'A' and <= 'F' => value - 'A' + 10,
        _ => -1
    };
}