Files
RAGECOOP-V/Server/Security.cs

71 lines
2.0 KiB
C#
Raw Normal View History

2022-10-23 19:02:39 +08:00
using System.IO;
2022-09-08 12:41:56 -07:00
using System.Net;
2022-06-24 10:33:36 +08:00
using System.Security.Cryptography;
2022-10-23 19:02:39 +08:00
using RageCoop.Core;
namespace RageCoop.Server;
internal class Security
2022-06-24 10:33:36 +08:00
{
2022-10-23 19:02:39 +08:00
private readonly Logger Logger;
private readonly Dictionary<IPEndPoint, Aes> SecuredConnections = new();
public RSA RSA = RSA.Create(2048);
public Security(Logger logger)
2022-06-24 10:33:36 +08:00
{
2022-10-23 19:02:39 +08:00
Logger = logger;
}
2022-06-24 10:33:36 +08:00
2022-10-23 19:02:39 +08:00
public bool HasSecuredConnection(IPEndPoint target)
{
return SecuredConnections.ContainsKey(target);
}
2022-06-24 10:33:36 +08:00
2022-10-23 19:02:39 +08:00
public byte[] Encrypt(byte[] data, IPEndPoint target)
{
var ms = new MemoryStream();
using (var cs = new CryptoStream(ms, SecuredConnections[target].CreateEncryptor(), CryptoStreamMode.Write))
2022-06-24 10:33:36 +08:00
{
2022-10-23 19:02:39 +08:00
cs.Write(data, 0, data.Length);
2022-06-24 10:33:36 +08:00
}
2022-10-23 19:02:39 +08:00
return ms.ToArray();
}
2022-09-08 12:41:56 -07:00
2022-10-23 19:02:39 +08:00
public byte[] Decrypt(byte[] data, IPEndPoint target)
{
return new CryptoStream(new MemoryStream(data), SecuredConnections[target].CreateDecryptor(),
CryptoStreamMode.Read).ReadToEnd();
}
public void AddConnection(IPEndPoint endpoint, byte[] cryptedKey, byte[] cryptedIV)
{
var key = RSA.Decrypt(cryptedKey, RSAEncryptionPadding.Pkcs1);
var iv = RSA.Decrypt(cryptedIV, RSAEncryptionPadding.Pkcs1);
// Logger?.Debug($"key:{key.Dump()}, iv:{iv.Dump()}");
var conAes = Aes.Create();
conAes.Key = key;
conAes.IV = iv;
if (!SecuredConnections.ContainsKey(endpoint))
SecuredConnections.Add(endpoint, conAes);
else
SecuredConnections[endpoint] = conAes;
}
public void RemoveConnection(IPEndPoint ep)
{
if (SecuredConnections.ContainsKey(ep)) SecuredConnections.Remove(ep);
}
public void GetPublicKey(out byte[] modulus, out byte[] exponent)
{
var key = RSA.ExportParameters(false);
modulus = key.Modulus;
exponent = key.Exponent;
}
public void ClearConnections()
{
SecuredConnections.Clear();
2022-06-24 10:33:36 +08:00
}
2022-10-23 19:02:39 +08:00
}