yo, i only need to do login (and printing stuff) and im done!

This commit is contained in:
Rusty Striker 2025-01-01 19:42:20 +02:00
parent 145e77e437
commit 04a4f7ece8
Signed by: RustyStriker
GPG key ID: 87E4D691632DFF15
5 changed files with 124 additions and 54 deletions

View file

@ -27,8 +27,8 @@ public class Message
Id = BitConverter.ToUInt32(bytes, 0);
Sender = Utils.BytesToNumber(bytes[4..12]);
IsAck = bytes[12] != 0;
Content = Encoding.UTF8.GetString(bytes[13..(bytes.Length - 32)]);
Signature = bytes[(bytes.Length - 32)..];
Content = Encoding.UTF8.GetString(bytes[13..bytes.Length]);
Signature = [];
}
public Message(uint Id, string Sender, bool IsAck, string Content)
@ -42,15 +42,15 @@ public class Message
public void CalculateSignature(RSA key)
{
Signature = key.SignData(Bytes(false), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
Signature = key.SignData(Bytes(), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
public bool IsSignatureValid(RSA key)
{
return key.VerifyData(Bytes(false), Signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return key.VerifyData(Bytes(), Signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
public byte[] Bytes(bool IncludeSignature = true)
public byte[] Bytes()
{
List<byte> msg = [];
// 0..4
@ -61,11 +61,6 @@ public class Message
msg.Add((byte)(IsAck ? 1 : 0));
// 13..(len - 32)
msg.AddRange(Encoding.UTF8.GetBytes(Content));
// (len - 32)..
if (IncludeSignature) // we dont want to include the signature when we sign/verify the data
{
msg.AddRange(Signature);
}
return [0, .. msg];
}

View file

@ -1,12 +1,14 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using client;
using lib;
namespace Client;
@ -14,10 +16,12 @@ namespace Client;
public class Program
{
static byte counter = 0;
static string User = "";
static readonly Random Rand = new();
static async Task Main(string[] args)
{
string user = args
User = args
.SkipWhile(a => !new[] { "-p", "--phone" }.Contains(a)) // search for the option
.Skip(1) // skip the `-u/--user` itself to get the value
.FirstOrDefault() ?? "0000"; // get the value or deafult if it doesnt exist
@ -25,10 +29,10 @@ public class Program
// On boot, check if a key is available
RSA? serverKey = LoadRSAFromFile("server_key.pem");
if (serverKey == null) { Console.WriteLine("Could not find server key, please run server before clients!"); return; }
RSA pubKey = LoadRSAFromFile($"pubkey_{user}.pem") ?? RSA.Create(2048);
RSA privKey = LoadRSAFromFile($"privkey_{user}.pem") ?? pubKey;
RSA pubKey = LoadRSAFromFile($"pubkey_{User}.pem") ?? RSA.Create(2048);
RSA privKey = LoadRSAFromFile($"privkey_{User}.pem") ?? pubKey;
SaveRSAKeys(user, pubKey, privKey);
SaveRSAKeys(User, pubKey, privKey);
using TcpClient client = new("127.0.0.1", 12345);
var stream = client.GetStream();
@ -40,7 +44,7 @@ public class Program
{
try
{
await RegisterClient(user, pubKey, privKey, serverKey, sk, stream);
await RegisterClient(User, pubKey, privKey, serverKey, sk, stream);
}
catch (Exception ex)
{
@ -212,8 +216,10 @@ public class Program
}
else if (publicKeys.TryGetValue(currentChat!, out RSA? key))
{
// TODO: add signature and origin please yes thank you
byte[] userMsg = key.Encrypt(Encoding.UTF8.GetBytes(input), RSAEncryptionPadding.OaepSHA256);
// Pick the id as a random uint, good enough for the sake of testing
Message m = new((uint)Rand.Next(), User, false, input);
m.CalculateSignature(privKey);
byte[] userMsg = [.. key.Encrypt(m.Bytes(), RSAEncryptionPadding.OaepSHA256), .. m.Signature];
byte[] req = Request.CreateRequest(
RequestType.SendMessage,
ref counter,
@ -257,31 +263,64 @@ public class Program
byte[] req = Request.CreateRequest(RequestType.GetMessages, ref counter, []);
req = sk.EncryptCfb(req, sk.IV, PaddingMode.None); // no need for padding this is exactly 128 bytes
await stream.WriteAsync(req);
byte[] buffer = new byte[1024];
byte[] buffer = new byte[4096];
int len = await stream.ReadAsync(buffer);
byte[] lengths = buffer[..16];
lengths = sk.DecryptCfb(lengths, sk.IV, PaddingMode.None);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"Got messages: {string.Join(", ", lengths)}");
Console.ResetColor();
byte[] msg = new byte[1024]; // msg buffer
int start = 16; // skip the first 16 bytes since its the lengths message
foreach (byte l in lengths.Take(15))
for (int i = 0; i < lengths.Length - 1; i += 2)
{
int l = (lengths[i] << 8) | (lengths[i + 1]);
Console.WriteLine($"got message of length: {l}");
if (l == 0) { break; } // a 0 means we are done actually, as empty messages shouldn't be allowed
// get the msg
int end = start + l;
if (end > len)
{
// we need to read more as there was use of more than 1024 overall
// todo for now
// TODO: read more incoming bytes when messages exceed the 1024 buffer
// TODO: properly handle it as a buffered stream and properly buffer it
}
Console.WriteLine($"got ecnryped message: {Convert.ToBase64String(buffer[start..end])}");
WriteColor($"got ecnryped message: {Convert.ToBase64String(buffer[start..end])}", ConsoleColor.Green);
// decrypt the message
if (privKey.TryDecrypt(buffer.AsSpan()[start..end], msg, RSAEncryptionPadding.OaepSHA256, out int written))
int msgLen = privKey.KeySize / 8;
if (privKey.TryDecrypt(buffer.AsSpan()[start..(msgLen + start)], msg, RSAEncryptionPadding.OaepSHA256, out int written))
{
byte[] dec = msg[..written];
Console.WriteLine($"decrypted message: {Convert.ToBase64String(dec)}");
Console.WriteLine($"Message: {Encoding.UTF8.GetString(dec)}");
Message m = new(dec)
{
Signature = buffer[(start + msgLen)..end]
};
bool sigValid = false;
if (publicKeys.TryGetValue(m.Sender, out RSA? pk) || (pk = await GetPublicKey(stream, sk, m.Sender)) != null)
{
publicKeys[m.Sender] = pk; // update the key value stored in case it was requested for in GetPublicKey
sigValid = m.IsSignatureValid(pk);
}
else
{
Console.WriteLine("Failed getting sender's public key");
}
WriteColor($"decrypted message: {Convert.ToBase64String(dec)}", ConsoleColor.Green);
Console.WriteLine($"Got message from {m.Sender} (id: {m.Id}) (valid: {sigValid}): " + (m.IsAck ? "ACK" : m.Content));
// if the signature is valid we also want to send back a message ack for the same id :)
if (sigValid)
{
Message mAck = new(m.Id, User, true, "");
mAck.CalculateSignature(privKey);
byte[] userMsg = [.. publicKeys[m.Sender].Encrypt(mAck.Bytes(), RSAEncryptionPadding.OaepSHA256), .. mAck.Signature];
byte[] reqAck = Request.CreateRequest(
RequestType.SendMessage,
ref counter,
[.. Utils.NumberToBytes(m.Sender), .. BitConverter.GetBytes(userMsg.Length)]);
reqAck = sk.EncryptCfb(reqAck, sk.IV);
stream.Write([.. reqAck, .. userMsg]);
}
}
else
{
@ -292,9 +331,19 @@ public class Program
// supposedly the sender will notice the lack of response and send it again
Console.WriteLine("Incoming message failed to decrypt, unknown sender");
}
start = end;
}
bool hasMoreMessages = lengths[15] != 0;
Console.WriteLine($"hasMoreMessages: {hasMoreMessages}");
}
}
static void WriteColor(string Line, ConsoleColor Color, ConsoleColor Background = ConsoleColor.Black)
{
Console.ForegroundColor = Color;
Console.BackgroundColor = Background;
Console.WriteLine(Line);
Console.ResetColor();
}
}