Files
RAGECOOP-V/Client/Scripts/Security.cs

53 lines
1.5 KiB
C#
Raw Normal View History

2022-10-23 19:02:39 +08:00
using System.IO;
2022-07-20 17:50:01 +08:00
using System.Security.Cryptography;
2022-10-23 19:02:39 +08:00
using RageCoop.Core;
2022-06-24 10:33:36 +08:00
namespace RageCoop.Client
{
internal class Security
{
2022-10-23 19:02:39 +08:00
2023-02-13 20:44:50 +08:00
public Security()
2022-06-24 10:33:36 +08:00
{
ClientAes.GenerateKey();
ClientAes.GenerateIV();
}
2022-10-23 19:02:39 +08:00
public RSA ServerRSA { get; set; }
public Aes ClientAes { get; set; } = Aes.Create();
2022-07-20 17:50:01 +08:00
public void GetSymmetricKeysCrypted(out byte[] cryptedKey, out byte[] cryptedIV)
2022-06-24 10:33:36 +08:00
{
// Logger?.Debug($"Aes.Key:{ClientAes.Key.Dump()}, Aes.IV:{ClientAes.IV.Dump()}");
2022-09-06 21:46:35 +08:00
cryptedKey = ServerRSA.Encrypt(ClientAes.Key, RSAEncryptionPadding.Pkcs1);
cryptedIV = ServerRSA.Encrypt(ClientAes.IV, RSAEncryptionPadding.Pkcs1);
2022-06-24 10:33:36 +08:00
}
2022-10-23 19:02:39 +08:00
2022-06-24 10:33:36 +08:00
public byte[] Encrypt(byte[] data)
{
2022-10-23 19:02:39 +08:00
return new CryptoStream(new MemoryStream(data), ClientAes.CreateEncryptor(), CryptoStreamMode.Read)
.ReadToEnd();
2022-06-24 10:33:36 +08:00
}
2022-10-23 19:02:39 +08:00
2022-07-29 18:17:45 +08:00
public byte[] Decrypt(byte[] data)
{
2022-10-23 19:02:39 +08:00
return new CryptoStream(new MemoryStream(data), ClientAes.CreateDecryptor(), CryptoStreamMode.Read)
.ReadToEnd();
2022-07-29 18:17:45 +08:00
}
2022-10-23 19:02:39 +08:00
2022-07-20 17:50:01 +08:00
public void SetServerPublicKey(byte[] modulus, byte[] exponent)
2022-06-24 10:33:36 +08:00
{
var para = new RSAParameters();
para.Modulus = modulus;
para.Exponent = exponent;
2022-09-06 21:46:35 +08:00
ServerRSA = RSA.Create(para);
2022-06-24 10:33:36 +08:00
}
2022-10-23 19:02:39 +08:00
2022-06-27 13:02:31 +08:00
public void Regen()
{
2022-09-06 21:46:35 +08:00
ClientAes = Aes.Create();
2022-06-27 13:02:31 +08:00
ClientAes.GenerateKey();
ClientAes.GenerateIV();
}
2022-06-24 10:33:36 +08:00
}
2022-10-23 19:02:39 +08:00
}