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

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;
using XFESystem.Tls;

namespace XFESystem.NativeRuntime.Application.Security;

internal static unsafe class NativeTlsSecurity
{
    [DllImport("xfe_pal", EntryPoint = "xfe_runtime_random_fill")]
    private static extern int FillNative(byte* destination, uint length);
    [DllImport("xfe_pal", EntryPoint = "xfe_runtime_random_capabilities")]
    private static extern uint CapabilitiesNative();
    [DllImport("xfe_pal", EntryPoint = "xfe_runtime_utc_filetime")]
    private static extern ulong UtcFileTimeNative();

    internal static readonly ITlsSecurityContext Context = new TlsPlatformSecurityContext(ReadUtc, Fill);
    internal static uint Capabilities => CapabilitiesNative();
    internal static DateTime ReadUtc()
    {
        ulong value = UtcFileTimeNative();
        if (value == 0 || value > long.MaxValue) throw new InvalidOperationException("HTTPS requires a live firmware UTC clock.");
        DateTime utc = DateTime.FromFileTimeUtc((long)value);
        if (utc.Year < 2024) throw new InvalidOperationException("The firmware UTC clock is unavailable or predates the supported epoch.");
        return utc;
    }
    internal static void Fill(Span<byte> destination)
    {
        if (destination.Length > 1_048_576) throw new ArgumentOutOfRangeException(nameof(destination));
        fixed (byte* pointer = destination)
            if (FillNative(pointer, (uint)destination.Length) != 1)
            {
                destination.Clear();
                throw new InvalidOperationException("No healthy CPU cryptographic random source is available; HTTPS is refused.");
            }
    }
    internal static uint Random32()
    {
        Span<byte> bytes = stackalloc byte[4]; Fill(bytes);
        return (uint)(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24);
    }
}