using System; using System.Net.Http; using System.Security.Cryptography; using JacobTechEncryption; using JacobTechEncryption.Enums; using Luski.net.Enums; using Luski.net.Structures; namespace Luski.net; public class ServerEncryption { internal bool Generating, Generated; internal string ServerPublicKey = "", MyPublicKey = "", myPrivateKey = "", OfflinePrivateKey = "", OfflinePublicKey = ""; internal byte[] Hash = default!; internal ServerEncryption(ServerStorage Storage) { this.Storage = Storage; } public string GetChannelKey(long Channel) { return Storage.GetResourceKeyRaw(StorageDirectory.ChannelKeys, Channel.ToString(), Hash); } public LocalKeyInfo GetKey(long Key) { return Storage.GetResourceKey(StorageDirectory.ServerKeys, Key.ToString(), Hash); } public void SetKey(long Key, LocalKeyInfo Info) { Storage.SetResourceKey(StorageDirectory.ServerKeys, Key.ToString(), Info, Hash); } public void SetChannelKey(long Channel, string Key) { Storage.SetResourceKey(StorageDirectory.ChannelKeys, Channel.ToString(), Hash, Key); } private ServerStorage Storage { get; } internal int PasswordVersion = 0; internal byte[] LocalPasswordEncrypt(byte[] Password) => LocalPasswordEncrypt(Password, PasswordVersion); internal string RemotePasswordEncrypt(byte[] Password) => RemotePasswordEncrypt(Password, PasswordVersion); internal byte[] LocalPasswordEncrypt(byte[] Password, int PasswordVersion) { return PasswordVersion switch { 0 => SHA256.Create().ComputeHash(Password), _ => throw new ArgumentException("The value provided was not accepted", nameof(PasswordVersion)), }; } internal string RemotePasswordEncrypt(byte[] Password, int PasswordVersion) { return PasswordVersion switch { 0 => Convert.ToBase64String(Encryption.RSA.Encrypt(LocalPasswordEncrypt(Password, PasswordVersion), ServerPublicKey)), _ => throw new ArgumentException("The value provided was not accepted", nameof(PasswordVersion)), }; } public void GenerateKeys() { if (!Generating) { Generating = true; GenerateNewKeys(out MyPublicKey, out myPrivateKey); GenerateNewKeys(out OfflinePublicKey, out OfflinePrivateKey); Generated = true; } } public static void GenerateNewKeys(out string Public, out string Private, int KeySize = 4096) { using RSACryptoServiceProvider r = new(KeySize); Private = r.ToXmlString(true); Public = r.ToXmlString(false); } }