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

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers.Binary;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Chat;

/// <summary>The native client's 20-byte IRC challenge response, for the recorded game build.</summary>
internal static class NativeIrcAuthentication
{
    private static readonly Lazy<(string Build, byte[] Key)> Protocol = new(() =>
    {
        var data = Assets.Json("irc-auth.json");
        return (data.Value<string>("BuildLabel")!, Convert.FromBase64String(data.Value<string>("KeyBase64")!));
    });

    public static bool Supports(string build) => build.Split('/')[0] == Protocol.Value.Build;

    public static bool Verify(string credential, ChatIdentity identity, uint challenge)
    {
        if (!Supports(identity.Build) || credential.Length != 40 || !credential.All(Uri.IsHexDigit)) return false;
        var received = Convert.FromHexString(credential);
        var seed = BinaryPrimitives.ReadUInt32BigEndian(received);
        if (seed > int.MaxValue) return false;
        var key = Protocol.Value.Key;
        var serverSplit = (int)((challenge & int.MaxValue) % key.Length);
        var clientSplit = (int)(seed % key.Length);
        var session = Encoding.UTF8.GetBytes($"accountId={identity.Id}&nonce={identity.Nonce.ToString(CultureInfo.InvariantCulture)}");
        ReadOnlyMemory<byte>[] pieces = [key.AsMemory(0, serverSplit), key.AsMemory(serverSplit), session,
            key.AsMemory(0, clientSplit), key.AsMemory(clientSplit)];
        // MD5 is required by the game's wire protocol; this is not password storage.
        // Alternate seventeen pieces between two contexts, then XOR the final digests.
        using var first = IncrementalHash.CreateHash(HashAlgorithmName.MD5);
        using var second = IncrementalHash.CreateHash(HashAlgorithmName.MD5);
        for (var i = 0; i < 17; i++) (i % 2 == 0 ? first : second).AppendData(pieces[i % pieces.Length].Span);
        var a = first.GetHashAndReset(); var b = second.GetHashAndReset();
        for (var i = 0; i < a.Length; i++) a[i] ^= b[i];
        return CryptographicOperations.FixedTimeEquals(received.AsSpan(4), a);
    }
}