using System.ComponentModel; using System.Runtime.InteropServices; using System.Text; namespace UCVL.VPNPlus; internal static class TokenStore { private const int CryptProtectUiForbidden = 0x1; [StructLayout(LayoutKind.Sequential)] private struct DataBlob { internal int Length; internal IntPtr Data; } [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptProtectData( ref DataBlob input, string description, IntPtr optionalEntropy, IntPtr reserved, IntPtr promptStruct, int flags, out DataBlob output); [DllImport("crypt32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptUnprotectData( ref DataBlob input, IntPtr description, IntPtr optionalEntropy, IntPtr reserved, IntPtr promptStruct, int flags, out DataBlob output); [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr memory); internal static void Save(string token) { AppPaths.EnsureDirectory(); var protectedBytes = Protect(Encoding.UTF8.GetBytes(token)); File.WriteAllBytes(AppPaths.TokenFile, protectedBytes); } internal static string? Load() { try { if (!File.Exists(AppPaths.TokenFile)) { return null; } return Encoding.UTF8.GetString(Unprotect(File.ReadAllBytes(AppPaths.TokenFile))); } catch (Exception exception) { AppPaths.WriteError(exception); Clear(); return null; } } internal static void Clear() { try { if (File.Exists(AppPaths.TokenFile)) { File.Delete(AppPaths.TokenFile); } } catch (Exception exception) { AppPaths.WriteError(exception); } } private static byte[] Protect(byte[] bytes) => Transform(bytes, protect: true); private static byte[] Unprotect(byte[] bytes) => Transform(bytes, protect: false); private static byte[] Transform(byte[] bytes, bool protect) { var inputPointer = Marshal.AllocHGlobal(bytes.Length); Marshal.Copy(bytes, 0, inputPointer, bytes.Length); var input = new DataBlob { Length = bytes.Length, Data = inputPointer }; DataBlob output; try { var succeeded = protect ? CryptProtectData(ref input, "UCVL VPN+ session", IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out output) : CryptUnprotectData(ref input, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out output); if (!succeeded) { throw new Win32Exception(Marshal.GetLastWin32Error()); } try { var result = new byte[output.Length]; Marshal.Copy(output.Data, result, 0, output.Length); return result; } finally { LocalFree(output.Data); } } finally { Marshal.FreeHGlobal(inputPointer); } } }