Decompiled source of RememberPassword v1.1.0

BepInEx/plugins/RememberPassword.dll

Decompiled 21 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using ProjectM;
using ProjectM.Network;
using ProjectM.UI;
using Stunlock.Network;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("RememberPassword")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Remembers V Rising dedicated-server join passwords and autofills them on the next Join.")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("RememberPassword")]
[assembly: AssemblyTitle("RememberPassword")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RememberPassword
{
	internal sealed class StoredServer
	{
		[JsonPropertyName("key")]
		public string Key { get; set; } = "";

		[JsonPropertyName("name")]
		public string Name { get; set; } = "";

		[JsonPropertyName("address")]
		public string Address { get; set; } = "";

		[JsonPropertyName("password")]
		public string Password { get; set; } = "";
	}
	internal sealed class StoreFile
	{
		[JsonPropertyName("version")]
		public int Version { get; set; }

		[JsonPropertyName("protected")]
		public bool Protected { get; set; }

		[JsonPropertyName("servers")]
		public List<StoredServer> Servers { get; set; } = new List<StoredServer>();
	}
	internal static class AddressKey
	{
		internal const string SteamIPv4Prefix = "SteamIPv4://";

		private static readonly string[] KnownSchemes = new string[5] { "SteamIPv4://", "Lidgren://", "SteamP2P://", "EosP2P://", "LocalOnly://" };

		internal static string Canonicalize(string raw)
		{
			if (string.IsNullOrWhiteSpace(raw))
			{
				return "";
			}
			raw = raw.Trim();
			string[] knownSchemes = KnownSchemes;
			foreach (string text in knownSchemes)
			{
				if (raw.StartsWith(text, StringComparison.OrdinalIgnoreCase))
				{
					return text + raw.Substring(text.Length).Trim();
				}
			}
			if (raw.IndexOf("://", StringComparison.Ordinal) >= 0)
			{
				return raw;
			}
			if (TrySplitHostPort(raw, out var host, out var port))
			{
				return "SteamIPv4://" + host + ":" + port;
			}
			if (LooksLikeBareIPv4(raw))
			{
				return "SteamIPv4://" + raw + ":9876";
			}
			return raw;
		}

		internal static bool Equivalent(string a, string b)
		{
			string text = Canonicalize(a);
			string b2 = Canonicalize(b);
			if (!string.IsNullOrEmpty(text))
			{
				return string.Equals(text, b2, StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private static bool TrySplitHostPort(string raw, out string host, out string port)
		{
			host = null;
			port = null;
			int num = raw.LastIndexOf(':');
			if (num <= 0 || num == raw.Length - 1)
			{
				return false;
			}
			host = raw.Substring(0, num).Trim();
			port = raw.Substring(num + 1).Trim();
			if (string.IsNullOrEmpty(host) || !ushort.TryParse(port, out var _))
			{
				return false;
			}
			return true;
		}

		private static bool LooksLikeBareIPv4(string raw)
		{
			string[] array = raw.Split('.');
			if (array.Length != 4)
			{
				return false;
			}
			string[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				if (!byte.TryParse(array2[i], out var _))
				{
					return false;
				}
			}
			return true;
		}
	}
	internal static class PasswordProtector
	{
		private static readonly byte[] Entropy = new byte[16]
		{
			82, 80, 45, 86, 82, 49, 46, 49, 45, 102,
			97, 110, 103, 108, 121, 1
		};

		internal static string Protect(string plaintext)
		{
			if (string.IsNullOrEmpty(plaintext))
			{
				return "";
			}
			return Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(plaintext), Entropy, (DataProtectionScope)0));
		}

		internal static bool TryUnprotect(string stored, out string plaintext)
		{
			plaintext = null;
			if (string.IsNullOrEmpty(stored))
			{
				return false;
			}
			try
			{
				byte[] bytes = ProtectedData.Unprotect(Convert.FromBase64String(stored), Entropy, (DataProtectionScope)0);
				plaintext = Encoding.UTF8.GetString(bytes);
				return !string.IsNullOrEmpty(plaintext);
			}
			catch (CryptographicException)
			{
				return false;
			}
			catch (FormatException)
			{
				return false;
			}
		}
	}
	internal static class PasswordStore
	{
		internal const int CurrentFileVersion = 2;

		private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
		{
			WriteIndented = true,
			PropertyNameCaseInsensitive = true
		};

		private static readonly object Sync = new object();

		private static string _path;

		private static StoreFile _data = new StoreFile();

		internal static string FilePath => _path;

		internal static void Initialize()
		{
			_path = Path.Combine(Paths.ConfigPath, "RememberPassword.json");
			Load();
		}

		internal static void Load()
		{
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			lock (Sync)
			{
				try
				{
					if (!File.Exists(_path))
					{
						_data = NewEmptyStore();
						return;
					}
					_data = JsonSerializer.Deserialize<StoreFile>(File.ReadAllText(_path), JsonOptions) ?? NewEmptyStore();
					StoreFile data = _data;
					if (data.Servers == null)
					{
						List<StoredServer> list = (data.Servers = new List<StoredServer>());
					}
					bool flag = _data.Protected || _data.Version >= 2;
					if (flag)
					{
						DecryptRowsInPlace();
					}
					Plugin.Logger.LogInfo((object)($"Loaded {_data.Servers.Count} saved server password(s) from RememberPassword.json" + (flag ? " (DPAPI)." : " (plaintext; will encrypt on next successful save).")));
				}
				catch (Exception ex)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag2 = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(89, 1, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to load RememberPassword.json: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(". Leaving the file on disk until a successful save.");
					}
					logger.LogWarning(val);
					_data = NewEmptyStore();
				}
			}
		}

		internal static bool TryGet(string addressOrKey, out string password)
		{
			password = null;
			lock (Sync)
			{
				StoredServer storedServer = Find(addressOrKey);
				if (storedServer == null || string.IsNullOrEmpty(storedServer.Password))
				{
					return false;
				}
				password = storedServer.Password;
				return true;
			}
		}

		internal static void Save(string addressOrKey, string name, string password)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			if (string.IsNullOrEmpty(password))
			{
				return;
			}
			string text = AddressKey.Canonicalize(addressOrKey);
			if (string.IsNullOrWhiteSpace(text))
			{
				return;
			}
			lock (Sync)
			{
				StoredServer storedServer = Find(text);
				if (storedServer == null)
				{
					storedServer = new StoredServer();
					_data.Servers.Add(storedServer);
				}
				storedServer.Key = text;
				storedServer.Address = text;
				if (!string.IsNullOrWhiteSpace(name))
				{
					storedServer.Name = name.Trim();
				}
				storedServer.Password = password;
				PersistUnlocked();
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(24, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Saved join password for ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Describe(storedServer.Name, storedServer.Address, storedServer.Key));
				}
				logger.LogInfo(val);
			}
		}

		private static StoredServer Find(string addressOrKey)
		{
			if (string.IsNullOrWhiteSpace(addressOrKey))
			{
				return null;
			}
			return _data.Servers.FirstOrDefault((StoredServer s) => AddressKey.Equivalent(s.Key, addressOrKey) || AddressKey.Equivalent(s.Address, addressOrKey));
		}

		private static void PersistUnlocked()
		{
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Expected O, but got Unknown
			try
			{
				string directoryName = Path.GetDirectoryName(_path);
				if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				StoreFile storeFile = new StoreFile
				{
					Version = 2,
					Protected = true,
					Servers = new List<StoredServer>(_data.Servers.Count)
				};
				foreach (StoredServer server in _data.Servers)
				{
					storeFile.Servers.Add(new StoredServer
					{
						Key = server.Key,
						Name = server.Name,
						Address = server.Address,
						Password = (string.IsNullOrEmpty(server.Password) ? "" : PasswordProtector.Protect(server.Password))
					});
				}
				string contents = JsonSerializer.Serialize(storeFile, JsonOptions);
				string text = _path + ".tmp";
				File.WriteAllText(text, contents);
				if (File.Exists(_path))
				{
					File.Replace(text, _path, _path + ".bak");
				}
				else
				{
					File.Move(text, _path);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(39, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to write RememberPassword.json: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogWarning(val);
				try
				{
					if (File.Exists(_path + ".tmp"))
					{
						File.Delete(_path + ".tmp");
					}
				}
				catch
				{
				}
			}
		}

		private static void DecryptRowsInPlace()
		{
			foreach (StoredServer server in _data.Servers)
			{
				if (!string.IsNullOrEmpty(server.Password))
				{
					if (PasswordProtector.TryUnprotect(server.Password, out var plaintext))
					{
						server.Password = plaintext;
						continue;
					}
					Plugin.Logger.LogWarning((object)("Could not decrypt saved password for " + Describe(server.Name, server.Address, server.Key) + " (wrong Windows user, or file copied from another PC). Row ignored."));
					server.Password = "";
				}
			}
		}

		private static StoreFile NewEmptyStore()
		{
			return new StoreFile
			{
				Version = 2,
				Protected = true,
				Servers = new List<StoredServer>()
			};
		}

		internal static string Describe(string name, string address, string key = null)
		{
			if (!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(address))
			{
				return $"'{name}' ({address})";
			}
			if (!string.IsNullOrWhiteSpace(address))
			{
				return address;
			}
			if (!string.IsNullOrWhiteSpace(key))
			{
				return key;
			}
			if (!string.IsNullOrWhiteSpace(name))
			{
				return "'" + name + "' (name only, not used as a key)";
			}
			return "(unknown server)";
		}
	}
	[BepInPlugin("fangly.RememberPassword", "RememberPassword", "1.1.0")]
	[BepInProcess("VRising.exe")]
	public class Plugin : BasePlugin
	{
		internal const string GUID = "fangly.RememberPassword";

		internal const string NAME = "RememberPassword";

		internal const string VERSION = "1.1.0";

		private Harmony _harmony;

		internal static Plugin Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		public override void Load()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			Instance = this;
			Logger = ((BasePlugin)this).Log;
			if (Application.productName == "VRisingServer")
			{
				((BasePlugin)this).Log.LogInfo((object)"RememberPassword is a client-only plugin; not loading on VRisingServer.");
				return;
			}
			PasswordStore.Initialize();
			_harmony = new Harmony("fangly.RememberPassword");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(74, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("RememberPassword ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.1.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded (client). Passwords are never written to the log.");
			}
			log.LogInfo(val);
		}

		public override bool Unload()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			return true;
		}
	}
	internal static class PluginInfo
	{
		public const string GUID = "fangly.RememberPassword";

		public const string Name = "RememberPassword";

		public const string Version = "1.1.0";
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "fangly.RememberPassword";

		public const string PLUGIN_NAME = "RememberPassword";

		public const string PLUGIN_VERSION = "1.1.0";
	}
}
namespace RememberPassword.Patches
{
	internal readonly struct PendingPasswordBind
	{
		internal readonly string Address;

		internal readonly string Name;

		internal readonly string Password;

		internal PendingPasswordBind(string address, string name, string password)
		{
			Address = address ?? "";
			Name = name ?? "";
			Password = password ?? "";
		}

		internal bool BelongsTo(string addressOrKey)
		{
			if (!string.IsNullOrEmpty(Password))
			{
				return AddressKey.Equivalent(Address, addressOrKey);
			}
			return false;
		}
	}
	internal static class JoinContext
	{
		internal static string Key;

		internal static string Name;

		internal static string Address;

		internal static PendingPasswordBind? Pending;

		internal static bool FromServerBrowser;

		internal static string FilledForKey;

		internal static int FilledInstanceId;

		internal static void RememberIdentity(string key, string name, string address, bool fromBrowser)
		{
			string text = (string.IsNullOrWhiteSpace(key) ? "" : key.Trim());
			string name2 = (string.IsNullOrWhiteSpace(name) ? "" : name.Trim());
			string obj = (string.IsNullOrWhiteSpace(address) ? "" : address.Trim());
			if (!AddressKey.Equivalent(obj, Address) && !AddressKey.Equivalent(text, Key))
			{
				FilledForKey = null;
				FilledInstanceId = 0;
			}
			Key = text;
			Name = name2;
			Address = obj;
			FromServerBrowser = fromBrowser;
		}

		internal static void RememberPendingPassword(string password, string address, string name)
		{
			if (!string.IsNullOrEmpty(password))
			{
				string text = AddressUtil.Normalize(address);
				if (!string.IsNullOrWhiteSpace(text))
				{
					Pending = new PendingPasswordBind(text, name, password);
				}
			}
		}

		internal static void ClearPending()
		{
			Pending = null;
		}

		internal static void ClearIdentity()
		{
			Key = "";
			Name = "";
			Address = "";
			FromServerBrowser = false;
			FilledForKey = null;
			FilledInstanceId = 0;
		}

		internal static void ClearJoin()
		{
			ClearPending();
			ClearIdentity();
		}
	}
	internal static class AddressUtil
	{
		internal unsafe static string Format(ConnectAddress address)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string text = ((object)(*(ConnectAddress*)(&address))/*cast due to .constrained prefix*/).ToString();
				if (!string.IsNullOrWhiteSpace(text) && text != "0.0.0.0:0" && text != "SteamIPv4://0.0.0.0:0")
				{
					return text.Trim();
				}
			}
			catch
			{
			}
			try
			{
				string text2 = SafeFixed(address.Address);
				if (!string.IsNullOrWhiteSpace(text2))
				{
					return AddressKey.Canonicalize(text2 + ":" + address.Port);
				}
				if (address.TargetSteamId != 0L)
				{
					return "SteamP2P://" + address.TargetSteamId;
				}
				string text3 = SafeFixed(address.TargetEosId);
				if (!string.IsNullOrWhiteSpace(text3))
				{
					return "EosP2P://" + text3;
				}
			}
			catch
			{
			}
			return "";
		}

		internal static string Normalize(string raw)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(raw))
			{
				return "";
			}
			raw = raw.Trim();
			try
			{
				ConnectAddress address = default(ConnectAddress);
				if (ConnectAddress.TryParse(raw, ref address))
				{
					string text = Format(address);
					if (!string.IsNullOrWhiteSpace(text))
					{
						return text;
					}
				}
			}
			catch
			{
			}
			return AddressKey.Canonicalize(raw);
		}

		internal static string SafeFixed(object fixedString)
		{
			if (fixedString == null)
			{
				return "";
			}
			try
			{
				string text = fixedString.ToString();
				if (string.IsNullOrWhiteSpace(text))
				{
					return "";
				}
				text = text.Trim();
				if (text.StartsWith("FixedString", StringComparison.Ordinal))
				{
					return "";
				}
				return text;
			}
			catch
			{
				return "";
			}
		}

		internal static bool ReadGameConnect(GameConnect connect, out string key, out string name, out string address)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			address = Normalize(Format(connect.ConnectAddress));
			if (string.IsNullOrWhiteSpace(address))
			{
				address = Normalize(SafeFixed(connect.HostAddress));
			}
			name = SafeFixed(connect.ServerSaveName);
			key = address;
			return !string.IsNullOrWhiteSpace(address);
		}

		internal static void FromGameConnect(GameConnect connect, bool fromBrowser, out string key, out string name, out string address)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (ReadGameConnect(connect, out key, out name, out address))
			{
				JoinContext.RememberIdentity(key, name, address, fromBrowser);
				return;
			}
			key = "";
			name = "";
			address = "";
		}
	}
	[HarmonyPatch(typeof(GameHelper), "LaunchPasswordProtectedGame")]
	internal static class LaunchPasswordProtectedGamePatch
	{
		[HarmonyPrefix]
		private static void Prefix(PasswordGameConnect launchData)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				AddressUtil.FromGameConnect(launchData.ConnectData, launchData.FromServerBrowser, out var _, out var _, out var _);
				Plugin.Logger.LogInfo((object)("Password prompt opening for " + PasswordStore.Describe(JoinContext.Name, JoinContext.Address, JoinContext.Key) + (launchData.FromServerBrowser ? " [server browser]" : " [direct/other]")));
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("LaunchPasswordProtectedGame prefix failed: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(Join_PasswordView))]
	internal static class JoinPasswordViewPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPostfix(Join_PasswordView __instance)
		{
			TryFill(__instance);
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(Join_PasswordView __instance)
		{
			TryFill(__instance);
		}

		[HarmonyPatch("OnButtonClick_Connect")]
		[HarmonyPrefix]
		private static void ConnectClickedPrefix(Join_PasswordView __instance)
		{
			try
			{
				ResolveViewIdentity(__instance, out var _, out var name, out var address);
				string text = ReadInput(__instance);
				if (!string.IsNullOrEmpty(text))
				{
					JoinContext.RememberPendingPassword(text, address, name);
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("Join_PasswordView connect click failed: " + ex.Message));
			}
		}

		[HarmonyPatch("OnButtonClick_Cancel")]
		[HarmonyPrefix]
		private static void CancelClickedPrefix()
		{
			try
			{
				Plugin.Logger.LogInfo((object)"Password dialog cancelled; pending password and identity cleared.");
				JoinContext.ClearJoin();
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("Join_PasswordView cancel failed: " + ex.Message));
			}
		}

		private static void TryFill(Join_PasswordView view)
		{
			try
			{
				if ((Object)(object)view == (Object)null || !Object.op_Implicit((Object)(object)view))
				{
					return;
				}
				TMP_InputField passwordInput = view.PasswordInput;
				if ((Object)(object)passwordInput == (Object)null || !Object.op_Implicit((Object)(object)passwordInput))
				{
					return;
				}
				ResolveViewIdentity(view, out var key, out var name, out var address);
				if (string.IsNullOrWhiteSpace(address) && string.IsNullOrWhiteSpace(key))
				{
					return;
				}
				string text = ((!string.IsNullOrWhiteSpace(address)) ? address : key);
				int instanceID = ((Object)view).GetInstanceID();
				if ((JoinContext.FilledInstanceId != instanceID || !(JoinContext.FilledForKey == text)) && string.IsNullOrEmpty(passwordInput.text) && PasswordStore.TryGet(text, out var password))
				{
					try
					{
						passwordInput.SetText(password, true);
					}
					catch
					{
						passwordInput.text = password;
					}
					JoinContext.FilledForKey = text;
					JoinContext.FilledInstanceId = instanceID;
					Plugin.Logger.LogInfo((object)("Autofilled saved password for " + PasswordStore.Describe(name, address, key)));
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("Join_PasswordView autofill failed: " + ex.Message));
			}
		}

		private static void ResolveViewIdentity(Join_PasswordView view, out string key, out string name, out string address)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			key = "";
			name = "";
			address = "";
			try
			{
				if ((Object)(object)view != (Object)null)
				{
					Nullable_Unboxed<PasswordGameConnect> passwordGameConnect = view._PasswordGameConnect;
					if (passwordGameConnect.HasValue)
					{
						PasswordGameConnect value = passwordGameConnect.Value;
						if (AddressUtil.ReadGameConnect(value.ConnectData, out key, out name, out address))
						{
							JoinContext.RememberIdentity(key, name, address, value.FromServerBrowser);
							return;
						}
					}
				}
			}
			catch
			{
			}
			key = JoinContext.Key;
			name = JoinContext.Name;
			address = JoinContext.Address;
		}

		private static string ReadInput(Join_PasswordView view)
		{
			TMP_InputField val = (((Object)(object)view != (Object)null) ? view.PasswordInput : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			return val.text;
		}
	}
	[HarmonyPatch(typeof(ClientBootstrapSystem), "Connect")]
	internal static class ClientBootstrapConnectPatch
	{
		[HarmonyPrefix]
		private static void Prefix(ConnectAddress connectAddress, ref string password)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string text = AddressUtil.Normalize(AddressUtil.Format(connectAddress));
				if (!string.IsNullOrWhiteSpace(text))
				{
					bool flag = AddressKey.Equivalent(text, JoinContext.Address);
					string name = (flag ? JoinContext.Name : "");
					JoinContext.RememberIdentity(text, name, text, flag && JoinContext.FromServerBrowser);
					if (string.IsNullOrEmpty(password) && PasswordStore.TryGet(text, out var password2))
					{
						password = password2;
						JoinContext.RememberPendingPassword(password2, text, name);
						Plugin.Logger.LogInfo((object)("Injected saved password into Connect for " + PasswordStore.Describe(name, text, text)));
					}
					else if (!string.IsNullOrEmpty(password))
					{
						JoinContext.RememberPendingPassword(password, text, name);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("ClientBootstrapSystem.Connect prefix failed: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(ClientBootstrapSystem), "OnStatusChangedEvent")]
	internal static class ClientBootstrapStatusPatch
	{
		[HarmonyPostfix]
		private unsafe static void Postfix(ClientBootstrapSystem __instance, StatusChangedEvent statusChangedEvent)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ClientConnectState status = statusChangedEvent.Status;
				if ((int)status == 4)
				{
					TrySaveOnConnected(__instance);
				}
				else if (IsTerminalFailure(status, __instance.DisconnectChangeReason))
				{
					ConnectionStatusChangeReason disconnectChangeReason = __instance.DisconnectChangeReason;
					Plugin.Logger.LogInfo((object)("Join ended (" + ((object)(*(ClientConnectState*)(&status))/*cast due to .constrained prefix*/).ToString() + "/" + ((object)(*(ConnectionStatusChangeReason*)(&disconnectChangeReason))/*cast due to .constrained prefix*/).ToString() + ") for " + PasswordStore.Describe(JoinContext.Name, JoinContext.Address, JoinContext.Key) + "; pending password and identity cleared."));
					JoinContext.ClearJoin();
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("OnStatusChangedEvent postfix failed: " + ex.Message));
			}
		}

		private static void TrySaveOnConnected(ClientBootstrapSystem instance)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			string text = "";
			try
			{
				text = AddressUtil.Normalize(AddressUtil.Format(instance._LastConnectData.ConnectAddress));
				if (!string.IsNullOrWhiteSpace(text))
				{
					string name = (AddressKey.Equivalent(text, JoinContext.Address) ? JoinContext.Name : "");
					if (JoinContext.Pending.HasValue && !string.IsNullOrWhiteSpace(JoinContext.Pending.Value.Name))
					{
						name = JoinContext.Pending.Value.Name;
					}
					JoinContext.RememberIdentity(text, name, text, JoinContext.FromServerBrowser);
				}
			}
			catch
			{
			}
			if (JoinContext.Pending.HasValue)
			{
				PendingPasswordBind value = JoinContext.Pending.Value;
				if (!string.IsNullOrWhiteSpace(text) && value.BelongsTo(text))
				{
					PasswordStore.Save(text, value.Name, value.Password);
				}
				else if (!string.IsNullOrWhiteSpace(text))
				{
					Plugin.Logger.LogInfo((object)("Connected to " + text + " but pending password was bound to a different host; not saving."));
				}
				JoinContext.ClearPending();
			}
		}

		private static bool IsTerminalFailure(ClientConnectState status, ConnectionStatusChangeReason reason)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected I4, but got Unknown
			if ((int)status == 1 || (int)status == 2 || (int)status == 3 || (int)status == 4)
			{
				return false;
			}
			if ((int)status == 5 || (int)status == 0)
			{
				return true;
			}
			switch (reason - 1)
			{
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 9:
			case 10:
			case 11:
			case 12:
			case 14:
			case 15:
			case 16:
			case 17:
			case 18:
			case 19:
				return true;
			default:
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(Popup_DirectConnect), "OnButtonClick_Connect")]
	internal static class DirectConnectPatch
	{
		[HarmonyPrefix]
		private static void Prefix(Popup_DirectConnect __instance)
		{
			try
			{
				TMP_InputField serverInputField = __instance.ServerInputField;
				string text = (((Object)(object)serverInputField != (Object)null) ? serverInputField.text : null);
				if (!string.IsNullOrWhiteSpace(text))
				{
					string text2 = AddressUtil.Normalize(text);
					JoinContext.RememberIdentity(text2, "", text2, fromBrowser: false);
					Plugin.Logger.LogInfo((object)("Direct Connect submit for " + text2));
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("Popup_DirectConnect connect prefix failed: " + ex.Message));
			}
		}
	}
}

BepInEx/plugins/System.Security.Cryptography.ProtectedData.dll

Decompiled 21 hours ago
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using FxResources.System.Security.Cryptography.ProtectedData;
using Internal.Cryptography;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Security.Cryptography.ProtectedData")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: SupportedOSPlatform("windows")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides access to Windows Data Protection Api.\r\n\r\nCommonly Used Types:\r\nSystem.Security.Cryptography.DataProtectionScope\r\nSystem.Security.Cryptography.ProtectedData")]
[assembly: AssemblyFileVersion("8.0.23.53103")]
[assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Security.Cryptography.ProtectedData")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("8.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class Interop
{
	internal static class Crypt32
	{
		[Flags]
		internal enum CryptProtectDataFlags
		{
			CRYPTPROTECT_UI_FORBIDDEN = 1,
			CRYPTPROTECT_LOCAL_MACHINE = 4,
			CRYPTPROTECT_CRED_SYNC = 8,
			CRYPTPROTECT_AUDIT = 0x10,
			CRYPTPROTECT_NO_RECOVERY = 0x20,
			CRYPTPROTECT_VERIFY_PROTECTION = 0x40
		}

		internal struct DATA_BLOB
		{
			internal uint cbData;

			internal IntPtr pbData;

			internal DATA_BLOB(IntPtr handle, uint size)
			{
				cbData = size;
				pbData = handle;
			}

			internal byte[] ToByteArray()
			{
				if (cbData == 0)
				{
					return Array.Empty<byte>();
				}
				byte[] array = new byte[cbData];
				Marshal.Copy(pbData, array, 0, (int)cbData);
				return array;
			}

			internal unsafe ReadOnlySpan<byte> DangerousAsSpan()
			{
				return new ReadOnlySpan<byte>((void*)pbData, (int)cbData);
			}
		}

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		[LibraryImport("crypt32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CryptProtectData(in DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, CryptProtectDataFlags dwFlags, out DATA_BLOB pDataOut);

		[DllImport("crypt32.dll", ExactSpelling = true, SetLastError = true)]
		[LibraryImport("crypt32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CryptUnprotectData(in DATA_BLOB pDataIn, IntPtr ppszDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, CryptProtectDataFlags dwFlags, out DATA_BLOB pDataOut);
	}

	internal static class Errors
	{
		internal const int ERROR_SUCCESS = 0;

		internal const int ERROR_INVALID_FUNCTION = 1;

		internal const int ERROR_FILE_NOT_FOUND = 2;

		internal const int ERROR_PATH_NOT_FOUND = 3;

		internal const int ERROR_ACCESS_DENIED = 5;

		internal const int ERROR_INVALID_HANDLE = 6;

		internal const int ERROR_NOT_ENOUGH_MEMORY = 8;

		internal const int ERROR_INVALID_DATA = 13;

		internal const int ERROR_INVALID_DRIVE = 15;

		internal const int ERROR_NO_MORE_FILES = 18;

		internal const int ERROR_NOT_READY = 21;

		internal const int ERROR_BAD_COMMAND = 22;

		internal const int ERROR_BAD_LENGTH = 24;

		internal const int ERROR_SHARING_VIOLATION = 32;

		internal const int ERROR_LOCK_VIOLATION = 33;

		internal const int ERROR_HANDLE_EOF = 38;

		internal const int ERROR_NOT_SUPPORTED = 50;

		internal const int ERROR_BAD_NETPATH = 53;

		internal const int ERROR_NETWORK_ACCESS_DENIED = 65;

		internal const int ERROR_BAD_NET_NAME = 67;

		internal const int ERROR_FILE_EXISTS = 80;

		internal const int ERROR_INVALID_PARAMETER = 87;

		internal const int ERROR_BROKEN_PIPE = 109;

		internal const int ERROR_DISK_FULL = 112;

		internal const int ERROR_SEM_TIMEOUT = 121;

		internal const int ERROR_CALL_NOT_IMPLEMENTED = 120;

		internal const int ERROR_INSUFFICIENT_BUFFER = 122;

		internal const int ERROR_INVALID_NAME = 123;

		internal const int ERROR_MOD_NOT_FOUND = 126;

		internal const int ERROR_NEGATIVE_SEEK = 131;

		internal const int ERROR_DIR_NOT_EMPTY = 145;

		internal const int ERROR_BAD_PATHNAME = 161;

		internal const int ERROR_LOCK_FAILED = 167;

		internal const int ERROR_BUSY = 170;

		internal const int ERROR_ALREADY_EXISTS = 183;

		internal const int ERROR_BAD_EXE_FORMAT = 193;

		internal const int ERROR_ENVVAR_NOT_FOUND = 203;

		internal const int ERROR_FILENAME_EXCED_RANGE = 206;

		internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216;

		internal const int ERROR_FILE_TOO_LARGE = 223;

		internal const int ERROR_PIPE_BUSY = 231;

		internal const int ERROR_NO_DATA = 232;

		internal const int ERROR_PIPE_NOT_CONNECTED = 233;

		internal const int ERROR_MORE_DATA = 234;

		internal const int ERROR_NO_MORE_ITEMS = 259;

		internal const int ERROR_DIRECTORY = 267;

		internal const int ERROR_NOT_OWNER = 288;

		internal const int ERROR_TOO_MANY_POSTS = 298;

		internal const int ERROR_PARTIAL_COPY = 299;

		internal const int ERROR_ARITHMETIC_OVERFLOW = 534;

		internal const int ERROR_PIPE_CONNECTED = 535;

		internal const int ERROR_PIPE_LISTENING = 536;

		internal const int ERROR_MUTANT_LIMIT_EXCEEDED = 587;

		internal const int ERROR_OPERATION_ABORTED = 995;

		internal const int ERROR_IO_INCOMPLETE = 996;

		internal const int ERROR_IO_PENDING = 997;

		internal const int ERROR_NO_TOKEN = 1008;

		internal const int ERROR_SERVICE_DOES_NOT_EXIST = 1060;

		internal const int ERROR_EXCEPTION_IN_SERVICE = 1064;

		internal const int ERROR_PROCESS_ABORTED = 1067;

		internal const int ERROR_NO_UNICODE_TRANSLATION = 1113;

		internal const int ERROR_DLL_INIT_FAILED = 1114;

		internal const int ERROR_COUNTER_TIMEOUT = 1121;

		internal const int ERROR_NO_ASSOCIATION = 1155;

		internal const int ERROR_DDE_FAIL = 1156;

		internal const int ERROR_DLL_NOT_FOUND = 1157;

		internal const int ERROR_NOT_FOUND = 1168;

		internal const int ERROR_CANCELLED = 1223;

		internal const int ERROR_NETWORK_UNREACHABLE = 1231;

		internal const int ERROR_NON_ACCOUNT_SID = 1257;

		internal const int ERROR_NOT_ALL_ASSIGNED = 1300;

		internal const int ERROR_UNKNOWN_REVISION = 1305;

		internal const int ERROR_INVALID_OWNER = 1307;

		internal const int ERROR_INVALID_PRIMARY_GROUP = 1308;

		internal const int ERROR_NO_SUCH_PRIVILEGE = 1313;

		internal const int ERROR_PRIVILEGE_NOT_HELD = 1314;

		internal const int ERROR_INVALID_ACL = 1336;

		internal const int ERROR_INVALID_SECURITY_DESCR = 1338;

		internal const int ERROR_INVALID_SID = 1337;

		internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346;

		internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347;

		internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350;

		internal const int ERROR_CANNOT_IMPERSONATE = 1368;

		internal const int ERROR_CLASS_ALREADY_EXISTS = 1410;

		internal const int ERROR_NO_SYSTEM_RESOURCES = 1450;

		internal const int ERROR_TIMEOUT = 1460;

		internal const int ERROR_EVENTLOG_FILE_CHANGED = 1503;

		internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;

		internal const int ERROR_RESOURCE_TYPE_NOT_FOUND = 1813;

		internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815;

		internal const int RPC_S_CALL_CANCELED = 1818;

		internal const int ERROR_NOT_A_REPARSE_POINT = 4390;

		internal const int ERROR_EVT_QUERY_RESULT_STALE = 15011;

		internal const int ERROR_EVT_QUERY_RESULT_INVALID_POSITION = 15012;

		internal const int ERROR_EVT_INVALID_EVENT_DATA = 15005;

		internal const int ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND = 15002;

		internal const int ERROR_EVT_CHANNEL_NOT_FOUND = 15007;

		internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;

		internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028;

		internal const int ERROR_EVT_PUBLISHER_DISABLED = 15037;
	}

	internal static class Kernel32
	{
		private const int FORMAT_MESSAGE_IGNORE_INSERTS = 512;

		private const int FORMAT_MESSAGE_FROM_HMODULE = 2048;

		private const int FORMAT_MESSAGE_FROM_SYSTEM = 4096;

		private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192;

		private const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 256;

		private const int ERROR_INSUFFICIENT_BUFFER = 122;

		[LibraryImport("kernel32.dll", EntryPoint = "FormatMessageW", SetLastError = true)]
		[GeneratedCode("Microsoft.Interop.LibraryImportGenerator", "8.0.9.3103")]
		[SkipLocalsInit]
		private unsafe static int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, void* lpBuffer, int nSize, IntPtr arguments)
		{
			Marshal.SetLastSystemError(0);
			int result = __PInvoke(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, arguments);
			int lastSystemError = Marshal.GetLastSystemError();
			Marshal.SetLastPInvokeError(lastSystemError);
			return result;
			[DllImport("kernel32.dll", EntryPoint = "FormatMessageW", ExactSpelling = true)]
			static extern unsafe int __PInvoke(int __dwFlags_native, IntPtr __lpSource_native, uint __dwMessageId_native, int __dwLanguageId_native, void* __lpBuffer_native, int __nSize_native, IntPtr __arguments_native);
		}

		internal static string GetMessage(int errorCode)
		{
			return GetMessage(errorCode, IntPtr.Zero);
		}

		internal unsafe static string GetMessage(int errorCode, IntPtr moduleHandle)
		{
			int num = 12800;
			if (moduleHandle != IntPtr.Zero)
			{
				num |= 0x800;
			}
			Span<char> span = stackalloc char[256];
			fixed (char* lpBuffer = span)
			{
				int num2 = FormatMessage(num, moduleHandle, (uint)errorCode, 0, lpBuffer, span.Length, IntPtr.Zero);
				if (num2 > 0)
				{
					return GetAndTrimString(span.Slice(0, num2));
				}
			}
			if (Marshal.GetLastWin32Error() == 122)
			{
				IntPtr intPtr = default(IntPtr);
				try
				{
					int num3 = FormatMessage(num | 0x100, moduleHandle, (uint)errorCode, 0, &intPtr, 0, IntPtr.Zero);
					if (num3 > 0)
					{
						return GetAndTrimString(new Span<char>((void*)intPtr, num3));
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
			}
			return $"Unknown error (0x{errorCode:x})";
		}

		private static string GetAndTrimString(Span<char> buffer)
		{
			int num = buffer.Length;
			while (num > 0 && buffer[num - 1] <= ' ')
			{
				num--;
			}
			return buffer.Slice(0, num).ToString();
		}
	}

	internal static class Libraries
	{
		internal const string Activeds = "activeds.dll";

		internal const string Advapi32 = "advapi32.dll";

		internal const string Authz = "authz.dll";

		internal const string BCrypt = "BCrypt.dll";

		internal const string Credui = "credui.dll";

		internal const string Crypt32 = "crypt32.dll";

		internal const string CryptUI = "cryptui.dll";

		internal const string Dnsapi = "dnsapi.dll";

		internal const string Dsrole = "dsrole.dll";

		internal const string Gdi32 = "gdi32.dll";

		internal const string HttpApi = "httpapi.dll";

		internal const string IpHlpApi = "iphlpapi.dll";

		internal const string Kernel32 = "kernel32.dll";

		internal const string Logoncli = "logoncli.dll";

		internal const string Mswsock = "mswsock.dll";

		internal const string NCrypt = "ncrypt.dll";

		internal const string Netapi32 = "netapi32.dll";

		internal const string Netutils = "netutils.dll";

		internal const string NtDll = "ntdll.dll";

		internal const string Odbc32 = "odbc32.dll";

		internal const string Ole32 = "ole32.dll";

		internal const string OleAut32 = "oleaut32.dll";

		internal const string Pdh = "pdh.dll";

		internal const string Secur32 = "secur32.dll";

		internal const string Shell32 = "shell32.dll";

		internal const string SspiCli = "sspicli.dll";

		internal const string User32 = "user32.dll";

		internal const string Version = "version.dll";

		internal const string WebSocket = "websocket.dll";

		internal const string Wevtapi = "wevtapi.dll";

		internal const string WinHttp = "winhttp.dll";

		internal const string WinMM = "winmm.dll";

		internal const string Wkscli = "wkscli.dll";

		internal const string Wldap32 = "wldap32.dll";

		internal const string Ws2_32 = "ws2_32.dll";

		internal const string Wtsapi32 = "wtsapi32.dll";

		internal const string CompressionNative = "System.IO.Compression.Native";

		internal const string GlobalizationNative = "System.Globalization.Native";

		internal const string MsQuic = "msquic.dll";

		internal const string HostPolicy = "hostpolicy";

		internal const string Ucrtbase = "ucrtbase.dll";

		internal const string Xolehlp = "xolehlp.dll";

		internal const string Comdlg32 = "comdlg32.dll";

		internal const string Gdiplus = "gdiplus.dll";

		internal const string Oleaut32 = "oleaut32.dll";

		internal const string Winspool = "winspool.drv";
	}
}
namespace FxResources.System.Security.Cryptography.ProtectedData
{
	internal static class SR
	{
	}
}
namespace Internal.Cryptography
{
	internal static class CryptoThrowHelper
	{
		public static CryptographicException ToCryptographicException(this int hr)
		{
			string message = global::Interop.Kernel32.GetMessage(hr);
			if (hr >= 0)
			{
				hr = (hr & 0xFFFF) | -2147024896;
			}
			return new CryptographicException(message)
			{
				HResult = hr
			};
		}
	}
}
namespace System
{
	internal static class HResults
	{
		internal const int S_OK = 0;

		internal const int S_FALSE = 1;

		internal const int COR_E_ABANDONEDMUTEX = -2146233043;

		internal const int COR_E_AMBIGUOUSIMPLEMENTATION = -2146234262;

		internal const int COR_E_AMBIGUOUSMATCH = -2147475171;

		internal const int COR_E_APPDOMAINUNLOADED = -2146234348;

		internal const int COR_E_APPLICATION = -2146232832;

		internal const int COR_E_ARGUMENT = -2147024809;

		internal const int COR_E_ARGUMENTOUTOFRANGE = -2146233086;

		internal const int COR_E_ARITHMETIC = -2147024362;

		internal const int COR_E_ARRAYTYPEMISMATCH = -2146233085;

		internal const int COR_E_BADEXEFORMAT = -2147024703;

		internal const int COR_E_BADIMAGEFORMAT = -2147024885;

		internal const int COR_E_CANNOTUNLOADAPPDOMAIN = -2146234347;

		internal const int COR_E_CODECONTRACTFAILED = -2146233022;

		internal const int COR_E_CONTEXTMARSHAL = -2146233084;

		internal const int COR_E_CUSTOMATTRIBUTEFORMAT = -2146232827;

		internal const int COR_E_DATAMISALIGNED = -2146233023;

		internal const int COR_E_DIRECTORYNOTFOUND = -2147024893;

		internal const int COR_E_DIVIDEBYZERO = -2147352558;

		internal const int COR_E_DLLNOTFOUND = -2146233052;

		internal const int COR_E_DUPLICATEWAITOBJECT = -2146233047;

		internal const int COR_E_ENDOFSTREAM = -2147024858;

		internal const int COR_E_ENTRYPOINTNOTFOUND = -2146233053;

		internal const int COR_E_EXCEPTION = -2146233088;

		internal const int COR_E_EXECUTIONENGINE = -2146233082;

		internal const int COR_E_FAILFAST = -2146232797;

		internal const int COR_E_FIELDACCESS = -2146233081;

		internal const int COR_E_FILELOAD = -2146232799;

		internal const int COR_E_FILENOTFOUND = -2147024894;

		internal const int COR_E_FORMAT = -2146233033;

		internal const int COR_E_INDEXOUTOFRANGE = -2146233080;

		internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = -2146232968;

		internal const int COR_E_INSUFFICIENTMEMORY = -2146233027;

		internal const int COR_E_INVALIDCAST = -2147467262;

		internal const int COR_E_INVALIDCOMOBJECT = -2146233049;

		internal const int COR_E_INVALIDFILTERCRITERIA = -2146232831;

		internal const int COR_E_INVALIDOLEVARIANTTYPE = -2146233039;

		internal const int COR_E_INVALIDOPERATION = -2146233079;

		internal const int COR_E_INVALIDPROGRAM = -2146233030;

		internal const int COR_E_IO = -2146232800;

		internal const int COR_E_KEYNOTFOUND = -2146232969;

		internal const int COR_E_MARSHALDIRECTIVE = -2146233035;

		internal const int COR_E_MEMBERACCESS = -2146233062;

		internal const int COR_E_METHODACCESS = -2146233072;

		internal const int COR_E_MISSINGFIELD = -2146233071;

		internal const int COR_E_MISSINGMANIFESTRESOURCE = -2146233038;

		internal const int COR_E_MISSINGMEMBER = -2146233070;

		internal const int COR_E_MISSINGMETHOD = -2146233069;

		internal const int COR_E_MISSINGSATELLITEASSEMBLY = -2146233034;

		internal const int COR_E_MULTICASTNOTSUPPORTED = -2146233068;

		internal const int COR_E_NOTFINITENUMBER = -2146233048;

		internal const int COR_E_NOTSUPPORTED = -2146233067;

		internal const int COR_E_OBJECTDISPOSED = -2146232798;

		internal const int COR_E_OPERATIONCANCELED = -2146233029;

		internal const int COR_E_OUTOFMEMORY = -2147024882;

		internal const int COR_E_OVERFLOW = -2146233066;

		internal const int COR_E_PATHTOOLONG = -2147024690;

		internal const int COR_E_PLATFORMNOTSUPPORTED = -2146233031;

		internal const int COR_E_RANK = -2146233065;

		internal const int COR_E_REFLECTIONTYPELOAD = -2146232830;

		internal const int COR_E_RUNTIMEWRAPPED = -2146233026;

		internal const int COR_E_SAFEARRAYRANKMISMATCH = -2146233032;

		internal const int COR_E_SAFEARRAYTYPEMISMATCH = -2146233037;

		internal const int COR_E_SECURITY = -2146233078;

		internal const int COR_E_SERIALIZATION = -2146233076;

		internal const int COR_E_STACKOVERFLOW = -2147023895;

		internal const int COR_E_SYNCHRONIZATIONLOCK = -2146233064;

		internal const int COR_E_SYSTEM = -2146233087;

		internal const int COR_E_TARGET = -2146232829;

		internal const int COR_E_TARGETINVOCATION = -2146232828;

		internal const int COR_E_TARGETPARAMCOUNT = -2147352562;

		internal const int COR_E_THREADABORTED = -2146233040;

		internal const int COR_E_THREADINTERRUPTED = -2146233063;

		internal const int COR_E_THREADSTART = -2146233051;

		internal const int COR_E_THREADSTATE = -2146233056;

		internal const int COR_E_TIMEOUT = -2146233083;

		internal const int COR_E_TYPEACCESS = -2146233021;

		internal const int COR_E_TYPEINITIALIZATION = -2146233036;

		internal const int COR_E_TYPELOAD = -2146233054;

		internal const int COR_E_TYPEUNLOADED = -2146234349;

		internal const int COR_E_UNAUTHORIZEDACCESS = -2147024891;

		internal const int COR_E_VERIFICATION = -2146233075;

		internal const int COR_E_WAITHANDLECANNOTBEOPENED = -2146233044;

		internal const int CO_E_NOTINITIALIZED = -2147221008;

		internal const int DISP_E_OVERFLOW = -2147352566;

		internal const int E_BOUNDS = -2147483637;

		internal const int E_CHANGED_STATE = -2147483636;

		internal const int E_FILENOTFOUND = -2147024894;

		internal const int E_FAIL = -2147467259;

		internal const int E_HANDLE = -2147024890;

		internal const int E_INVALIDARG = -2147024809;

		internal const int E_NOTIMPL = -2147467263;

		internal const int E_POINTER = -2147467261;

		internal const int ERROR_MRM_MAP_NOT_FOUND = -2147009761;

		internal const int ERROR_TIMEOUT = -2147023436;

		internal const int RO_E_CLOSED = -2147483629;

		internal const int RPC_E_CHANGED_MODE = -2147417850;

		internal const int TYPE_E_TYPEMISMATCH = -2147316576;

		internal const int STG_E_PATHNOTFOUND = -2147287037;

		internal const int CTL_E_PATHNOTFOUND = -2146828212;

		internal const int CTL_E_FILENOTFOUND = -2146828235;

		internal const int FUSION_E_INVALID_NAME = -2146234297;

		internal const int FUSION_E_PRIVATE_ASM_DISALLOWED = -2146234300;

		internal const int FUSION_E_REF_DEF_MISMATCH = -2146234304;

		internal const int ERROR_TOO_MANY_OPEN_FILES = -2147024892;

		internal const int ERROR_SHARING_VIOLATION = -2147024864;

		internal const int ERROR_LOCK_VIOLATION = -2147024863;

		internal const int ERROR_OPEN_FAILED = -2147024786;

		internal const int ERROR_DISK_CORRUPT = -2147023503;

		internal const int ERROR_UNRECOGNIZED_VOLUME = -2147023891;

		internal const int ERROR_DLL_INIT_FAILED = -2147023782;

		internal const int MSEE_E_ASSEMBLYLOADINPROGRESS = -2146234346;

		internal const int ERROR_FILE_INVALID = -2147023890;
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Cryptography_DpApi_ProfileMayNotBeLoaded => GetResourceString("Cryptography_DpApi_ProfileMayNotBeLoaded");

		internal static string PlatformNotSupported_CryptographyProtectedData => GetResourceString("PlatformNotSupported_CryptographyProtectedData");

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Security.Cryptography
{
	public enum DataProtectionScope
	{
		CurrentUser,
		LocalMachine
	}
	public static class ProtectedData
	{
		private static readonly byte[] s_nonEmpty = new byte[1];

		public static byte[] Protect(byte[] userData, byte[]? optionalEntropy, DataProtectionScope scope)
		{
			CheckPlatformSupport();
			if (userData == null)
			{
				throw new ArgumentNullException("userData");
			}
			return ProtectOrUnprotect(userData, optionalEntropy, scope, protect: true);
		}

		public static byte[] Unprotect(byte[] encryptedData, byte[]? optionalEntropy, DataProtectionScope scope)
		{
			CheckPlatformSupport();
			if (encryptedData == null)
			{
				throw new ArgumentNullException("encryptedData");
			}
			return ProtectOrUnprotect(encryptedData, optionalEntropy, scope, protect: false);
		}

		private unsafe static byte[] ProtectOrUnprotect(byte[] inputData, byte[] optionalEntropy, DataProtectionScope scope, bool protect)
		{
			fixed (byte* ptr = ((inputData.Length == 0) ? s_nonEmpty : inputData))
			{
				fixed (byte* ptr2 = optionalEntropy)
				{
					global::Interop.Crypt32.DATA_BLOB pDataIn = new global::Interop.Crypt32.DATA_BLOB((IntPtr)ptr, (uint)inputData.Length);
					global::Interop.Crypt32.DATA_BLOB pOptionalEntropy = default(global::Interop.Crypt32.DATA_BLOB);
					if (optionalEntropy != null)
					{
						pOptionalEntropy = new global::Interop.Crypt32.DATA_BLOB((IntPtr)ptr2, (uint)optionalEntropy.Length);
					}
					global::Interop.Crypt32.CryptProtectDataFlags cryptProtectDataFlags = global::Interop.Crypt32.CryptProtectDataFlags.CRYPTPROTECT_UI_FORBIDDEN;
					if (scope == DataProtectionScope.LocalMachine)
					{
						cryptProtectDataFlags |= global::Interop.Crypt32.CryptProtectDataFlags.CRYPTPROTECT_LOCAL_MACHINE;
					}
					global::Interop.Crypt32.DATA_BLOB pDataOut = default(global::Interop.Crypt32.DATA_BLOB);
					try
					{
						if (!(protect ? global::Interop.Crypt32.CryptProtectData(in pDataIn, null, ref pOptionalEntropy, IntPtr.Zero, IntPtr.Zero, cryptProtectDataFlags, out pDataOut) : global::Interop.Crypt32.CryptUnprotectData(in pDataIn, IntPtr.Zero, ref pOptionalEntropy, IntPtr.Zero, IntPtr.Zero, cryptProtectDataFlags, out pDataOut)))
						{
							int lastPInvokeError = Marshal.GetLastPInvokeError();
							if (protect && ErrorMayBeCausedByUnloadedProfile(lastPInvokeError))
							{
								throw new CryptographicException(System.SR.Cryptography_DpApi_ProfileMayNotBeLoaded);
							}
							throw lastPInvokeError.ToCryptographicException();
						}
						if (pDataOut.pbData == IntPtr.Zero)
						{
							throw new OutOfMemoryException();
						}
						int cbData = (int)pDataOut.cbData;
						byte[] array = new byte[cbData];
						Marshal.Copy(pDataOut.pbData, array, 0, cbData);
						return array;
					}
					finally
					{
						if (pDataOut.pbData != IntPtr.Zero)
						{
							int cbData2 = (int)pDataOut.cbData;
							byte* ptr3 = (byte*)(void*)pDataOut.pbData;
							for (int i = 0; i < cbData2; i++)
							{
								ptr3[i] = 0;
							}
							Marshal.FreeHGlobal(pDataOut.pbData);
						}
					}
				}
			}
		}

		private static bool ErrorMayBeCausedByUnloadedProfile(int errorCode)
		{
			if (errorCode != -2147024894)
			{
				return errorCode == 2;
			}
			return true;
		}

		private static void CheckPlatformSupport()
		{
			if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				throw new PlatformNotSupportedException();
			}
		}
	}
}