Luski.Net/Luski.net/ServerEncryption.cs

70 lines
2.3 KiB
C#
Raw Normal View History

using System;
using System.Security.Cryptography;
using JacobTechEncryption;
using Luski.net.Enums;
namespace Luski.net;
public class ServerEncryption
{
internal bool Generating, Generated;
internal string ServerPublicKey = "", MyPublicKey = "", myPrivateKey = "", OfflinePrivateKey = "", OfflinePublicKey = "";
internal byte[] Hash = default!;
internal ServerEncryption(string Domain, string API_Version, ServerStorage Storage)
{
this.Storage = Storage;
//TODO Get server p key
}
public string GetChannelKey(long Channel)
{
return Storage.GetResourceKey(StorageDirectory.ChannelKeys, Channel.ToString(), 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);
}
}