merge reactive username with encode

This commit is contained in:
Patrick Hellebrand
2021-09-23 14:03:29 +02:00
6 changed files with 159 additions and 53 deletions

View File

@@ -8,9 +8,11 @@ using PolyChat.Models;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System; using System;
using System.Text.Json;
using System.Text; using System.Text;
using System.Security.Cryptography; using System.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;
namespace PolyChat namespace PolyChat
{ {
@@ -37,8 +39,8 @@ namespace PolyChat
{ {
UIController = uiController; UIController = uiController;
OwnIP = getIP(); OwnIP = getIP();
//loadChats(); loadChats();
//SaveChats("10", "{das ist ein test}"); encode("test");
Serve(); Serve();
// test // test
@@ -79,6 +81,7 @@ namespace PolyChat
{ {
Debug.WriteLine("--- initial packet received ---"); Debug.WriteLine("--- initial packet received ---");
string ForeignIp = data[0].ToString(); string ForeignIp = data[0].ToString();
Debug.WriteLine($"--- this ip was in the inital packet: {ForeignIp} ---"); Debug.WriteLine($"--- this ip was in the inital packet: {ForeignIp} ---");
if (isInConnections(ForeignIp)) if (isInConnections(ForeignIp))
{ {
@@ -174,10 +177,13 @@ namespace PolyChat
/// <summary> /// <summary>
/// sends chatlogs as json array to uiController wit corrosponding ip /// sends chatlogs as json array to uiController wit corrosponding ip
///
/// in ui when chat is clicked connection gets established
/// </summary> /// </summary>
/// <param name="ip"></param> /// <param name="ip"></param>
public void loadChats() public void loadChats()
{ {
//TODO: also load chatlogs when user tries to connect
//load dir and create if non existant //load dir and create if non existant
if (Directory.Exists("U:\\PolyChat\\Saves")) if (Directory.Exists("U:\\PolyChat\\Saves"))
{ {
@@ -206,7 +212,6 @@ namespace PolyChat
UIController.OnIncomingMessages(ip, jsonArr); UIController.OnIncomingMessages(ip, jsonArr);
} }
} }
} }
/// <summary> /// <summary>
@@ -221,6 +226,14 @@ namespace PolyChat
//writing flag setzen oder auch in der datei selbst ne flag setzen //writing flag setzen oder auch in der datei selbst ne flag setzen
new Thread(() => new Thread(() =>
{ {
//breaking if namechange
JObject obj = JObject.Parse(json);
if (!obj["type"].ToString().Equals("username"))
{
//adding timestamp
obj = JObject.Parse(json);
obj.Add(new JProperty("timestamp", timeStamp));
json = obj.ToString();
if (File.Exists($"U:\\PolyChat\\Saves\\{ip}.txt")) if (File.Exists($"U:\\PolyChat\\Saves\\{ip}.txt"))
{ {
Debug.WriteLine("--File allready exists--"); Debug.WriteLine("--File allready exists--");
@@ -231,7 +244,6 @@ namespace PolyChat
{ {
Debug.WriteLine("--adding new chatmessage--"); Debug.WriteLine("--adding new chatmessage--");
//structure intact //structure intact
JObject obj = JObject.Parse(json);
//save new chat //save new chat
String saved = output.Substring(0, output.Length - 1); String saved = output.Substring(0, output.Length - 1);
output = saved + ", " + json + " ]"; output = saved + ", " + json + " ]";
@@ -254,20 +266,15 @@ namespace PolyChat
//setup file //setup file
File.WriteAllText($"U:\\PolyChat\\Saves\\{ip}.txt", $"[ {json} ]"); File.WriteAllText($"U:\\PolyChat\\Saves\\{ip}.txt", $"[ {json} ]");
} }
}
}).Start(); }).Start();
} }
private void encode(string json) private void encode(string json)
{ {
byte[] plaintext = Encoding.UTF8.GetBytes(json); String ecryptetText = FileManager.encrypt(json);
byte[] entropy = new byte[20]; Debug.WriteLine(ecryptetText);
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) //Debug.WriteLine(FileManager.decrypt(ecryptetText));
{
rng.GetBytes(entropy);
}
/*byte[] ciphertext = ProtectedData.Protect(plaintext, entropy,
DataProtectionScope.CurrentUser);*/
} }
} }
} }

View File

@@ -7,11 +7,11 @@ using System.Collections.ObjectModel;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using Windows.Foundation;
using Windows.UI.Core; using Windows.UI.Core;
using Windows.UI.Xaml; using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
@@ -90,7 +90,7 @@ namespace PolyChat
DateTime.Now DateTime.Now
); );
NewChatDialog dialog = new NewChatDialog(); NewChatDialog dialog = new NewChatDialog();
var result = await dialog.ShowAsync(); var result = await SafelyOpenDialog(dialog);
if (result == ContentDialogResult.Primary) if (result == ContentDialogResult.Primary)
{ {
string ip = IP.GetIPFromCode(dialog.getValue()); string ip = IP.GetIPFromCode(dialog.getValue());
@@ -106,7 +106,7 @@ namespace PolyChat
public async void OnOpenEditUsernameDialog(object sender = null, RoutedEventArgs e = null) public async void OnOpenEditUsernameDialog(object sender = null, RoutedEventArgs e = null)
{ {
EditUsernameDialog dialog = new EditUsernameDialog(username); EditUsernameDialog dialog = new EditUsernameDialog(username);
var result = await dialog.ShowAsync(); var result = await SafelyOpenDialog(dialog);
if (result == ContentDialogResult.Primary) if (result == ContentDialogResult.Primary)
{ {
username = dialog.getValue(); username = dialog.getValue();
@@ -216,6 +216,27 @@ namespace PolyChat
} }
} }
public static IAsyncOperation<ContentDialogResult> SafelyOpenDialog(Dialog d)
{
if(VisualTreeHelper.GetOpenPopups(Window.Current).Count == 0)
return d.ShowAsync();
return null;
}
public static IAsyncOperation<ContentDialogResult> SafelyOpenDialog(NewChatDialog d)
{
if (VisualTreeHelper.GetOpenPopups(Window.Current).Count == 0)
return d.ShowAsync();
return null;
}
public static IAsyncOperation<ContentDialogResult> SafelyOpenDialog(EditUsernameDialog d)
{
if (VisualTreeHelper.GetOpenPopups(Window.Current).Count == 0)
return d.ShowAsync();
return null;
}
// UPDATE FUNCTIONS FOR UI PLACEHOLDERS // UPDATE FUNCTIONS FOR UI PLACEHOLDERS
private void updateNoChatsPlaceholder() private void updateNoChatsPlaceholder()

View File

@@ -12,11 +12,6 @@ namespace PolyChat.Models
public DateTime TimeStamp; public DateTime TimeStamp;
public readonly bool Foreign; public readonly bool Foreign;
public ChatMessage()
{
}
/// <summary> /// <summary>
/// Create own Message (directly sent) /// Create own Message (directly sent)
/// </summary> /// </summary>

View File

@@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.Cryptography;
namespace PolyChat.Models
{
class FileManager
{
public static String encrypt(String toEncrypt)
{
try {
string textToEncrypt = toEncrypt;
string ToReturn = "";
string publickey = "santhosh";
string secretkey = "engineer";
byte[] secretkeyByte = { };
secretkeyByte = System.Text.Encoding.UTF8.GetBytes(secretkey);
byte[] publickeybyte = { };
publickeybyte = System.Text.Encoding.UTF8.GetBytes(publickey);
MemoryStream ms = null;
CryptoStream cs = null;
byte[] inputbyteArray = System.Text.Encoding.UTF8.GetBytes(textToEncrypt);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
ms = new MemoryStream();
cs = new CryptoStream(ms, des.CreateEncryptor(publickeybyte, secretkeyByte), CryptoStreamMode.Write);
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
cs.FlushFinalBlock();
ToReturn = Convert.ToBase64String(ms.ToArray());
}
return ToReturn;
} catch (Exception ex)
{
throw new Exception(ex.Message, ex.InnerException);
}
}
public static String decrypt(String toDecrypt)
{
try
{
string textToDecrypt = toDecrypt;
string ToReturn = "";
string publickey = "santhosh";
string privatekey = "engineer";
byte[] privatekeyByte = { };
privatekeyByte = System.Text.Encoding.UTF8.GetBytes(privatekey);
byte[] publickeybyte = { };
publickeybyte = System.Text.Encoding.UTF8.GetBytes(publickey);
MemoryStream ms = null;
CryptoStream cs = null;
byte[] inputbyteArray = new byte[textToDecrypt.Replace(" ", "+").Length];
inputbyteArray = Convert.FromBase64String(textToDecrypt.Replace(" ", "+"));
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
ms = new MemoryStream();
cs = new CryptoStream(ms, des.CreateDecryptor(publickeybyte, privatekeyByte), CryptoStreamMode.Write);
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
ToReturn = encoding.GetString(ms.ToArray());
}
return ToReturn;
}
catch (Exception ae)
{
throw new Exception(ae.Message, ae.InnerException);
}
}
}
}

View File

@@ -137,6 +137,7 @@
<Compile Include="Models\ChatPartner.cs" /> <Compile Include="Models\ChatPartner.cs" />
<Compile Include="Models\Exceptions\MessageTimedOutException.cs" /> <Compile Include="Models\Exceptions\MessageTimedOutException.cs" />
<Compile Include="Models\Exceptions\ConnectionFailedException.cs" /> <Compile Include="Models\Exceptions\ConnectionFailedException.cs" />
<Compile Include="Models\FileManager.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Util\IP.cs" /> <Compile Include="Util\IP.cs" />
<Compile Include="Views\Dialog.xaml.cs"> <Compile Include="Views\Dialog.xaml.cs">
@@ -203,9 +204,6 @@
<Version>5.0.2</Version> <Version>5.0.2</Version>
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="PolyChat_TemporaryKey.pfx" />
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' "> <PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion> <VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup> </PropertyGroup>

View File

@@ -3,6 +3,7 @@ using PolyChat.Util;
using System; using System;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using System.Threading;
using Windows.Foundation; using Windows.Foundation;
using Windows.UI.Core; using Windows.UI.Core;
using Windows.UI.Popups; using Windows.UI.Popups;
@@ -34,7 +35,7 @@ namespace PolyChat.Views
Primary = primary.Action; Primary = primary.Action;
Secondary = secondary.Action; Secondary = secondary.Action;
// show // show
ShowDialogAsync(); MainPage.SafelyOpenDialog(this);
} }
private void setType(string type, string message) private void setType(string type, string message)