Skip to content

Commit 80f98db

Browse files
[p2p] - protect data using Aes256
1 parent 20d00c9 commit 80f98db

File tree

10 files changed

+213
-5
lines changed

10 files changed

+213
-5
lines changed

img/p2p-connection.png

100644100755
File mode changed.

img/p2p-exe.png

100644100755
File mode changed.

img/p2p-logic.png

100644100755
File mode changed.

img/p2p-remote-desktop.png

100644100755
File mode changed.

p2pconn/Cryptography/Aes256.cs

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
using System;
2+
using System.IO;
3+
using System.Security.Cryptography;
4+
using System.Text;
5+
6+
namespace Cryptography
7+
{
8+
#region " Aes256"
9+
public class Aes256
10+
{
11+
private const int KeyLength = 32;
12+
private const int AuthKeyLength = 64;
13+
private const int IvLength = 16;
14+
private const int HmacSha256Length = 32;
15+
private readonly byte[] _key;
16+
private readonly byte[] _authKey;
17+
18+
private static readonly byte[] Salt =
19+
{
20+
0xBF, 0xEB, 0x1E, 0x56, 0xFB, 0xCD, 0x97, 0x3B, 0xB2, 0x19, 0x2, 0x24, 0x30, 0xA5, 0x78, 0x43, 0x0, 0x3D, 0x56,
21+
0x44, 0xD2, 0x1E, 0x62, 0xB9, 0xD4, 0xF1, 0x80, 0xE7, 0xE6, 0xC3, 0x39, 0x41
22+
};
23+
24+
public Aes256(string masterKey)
25+
{
26+
if (string.IsNullOrEmpty(masterKey))
27+
throw new ArgumentException($"{nameof(masterKey)} can not be null or empty.");
28+
29+
using (Rfc2898DeriveBytes derive = new Rfc2898DeriveBytes(masterKey, Salt, 5000))
30+
{
31+
_key = derive.GetBytes(KeyLength);
32+
_authKey = derive.GetBytes(AuthKeyLength);
33+
}
34+
}
35+
36+
public string Encrypt(string input)
37+
{
38+
return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(input)));
39+
}
40+
41+
/* FORMAT
42+
* ----------------------------------------
43+
* | HMAC | IV | CIPHERTEXT |
44+
* ----------------------------------------
45+
* 32 bytes 16 bytes
46+
*/
47+
public byte[] Encrypt(byte[] input)
48+
{
49+
if (input == null)
50+
throw new ArgumentNullException($"{nameof(input)} can not be null.");
51+
52+
using (var ms = new MemoryStream())
53+
{
54+
ms.Position = HmacSha256Length; // reserve first 32 bytes for HMAC
55+
using (var aesProvider = new AesCryptoServiceProvider())
56+
{
57+
aesProvider.KeySize = 256;
58+
aesProvider.BlockSize = 128;
59+
aesProvider.Mode = CipherMode.CBC;
60+
aesProvider.Padding = PaddingMode.PKCS7;
61+
aesProvider.Key = _key;
62+
aesProvider.GenerateIV();
63+
64+
using (var cs = new CryptoStream(ms, aesProvider.CreateEncryptor(), CryptoStreamMode.Write))
65+
{
66+
ms.Write(aesProvider.IV, 0, aesProvider.IV.Length); // write next 16 bytes the IV, followed by ciphertext
67+
cs.Write(input, 0, input.Length);
68+
cs.FlushFinalBlock();
69+
70+
using (var hmac = new HMACSHA256(_authKey))
71+
{
72+
byte[] hash = hmac.ComputeHash(ms.ToArray(), HmacSha256Length, ms.ToArray().Length - HmacSha256Length); // compute the HMAC of IV and ciphertext
73+
ms.Position = 0; // write hash at beginning
74+
ms.Write(hash, 0, hash.Length);
75+
}
76+
}
77+
}
78+
79+
return ms.ToArray();
80+
}
81+
}
82+
83+
public string Decrypt(string input)
84+
{
85+
return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(input)));
86+
}
87+
88+
public byte[] Decrypt(byte[] input)
89+
{
90+
if (input == null)
91+
throw new ArgumentNullException($"{nameof(input)} can not be null.");
92+
93+
using (var ms = new MemoryStream(input))
94+
{
95+
using (var aesProvider = new AesCryptoServiceProvider())
96+
{
97+
aesProvider.KeySize = 256;
98+
aesProvider.BlockSize = 128;
99+
aesProvider.Mode = CipherMode.CBC;
100+
aesProvider.Padding = PaddingMode.PKCS7;
101+
aesProvider.Key = _key;
102+
103+
// read first 32 bytes for HMAC
104+
using (var hmac = new HMACSHA256(_authKey))
105+
{
106+
var hash = hmac.ComputeHash(ms.ToArray(), HmacSha256Length, ms.ToArray().Length - HmacSha256Length);
107+
byte[] receivedHash = new byte[HmacSha256Length];
108+
ms.Read(receivedHash, 0, receivedHash.Length);
109+
110+
if (!SafeComparison.AreEqual(hash, receivedHash))
111+
throw new CryptographicException("Invalid message authentication code (MAC).");
112+
}
113+
114+
byte[] iv = new byte[IvLength];
115+
ms.Read(iv, 0, IvLength); // read next 16 bytes for IV, followed by ciphertext
116+
aesProvider.IV = iv;
117+
118+
using (var cs = new CryptoStream(ms, aesProvider.CreateDecryptor(), CryptoStreamMode.Read))
119+
{
120+
byte[] temp = new byte[ms.Length - IvLength + 1];
121+
byte[] data = new byte[cs.Read(temp, 0, temp.Length)];
122+
Buffer.BlockCopy(temp, 0, data, 0, data.Length);
123+
return data;
124+
}
125+
}
126+
}
127+
}
128+
}
129+
#endregion
130+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using System.Runtime.CompilerServices;
2+
3+
namespace Cryptography
4+
{
5+
#region " safe comparsion"
6+
public class SafeComparison
7+
{
8+
/// <summary>
9+
/// Compares two byte arrays for equality.
10+
/// </summary>
11+
/// <param name="a1">Byte array to compare</param>
12+
/// <param name="a2">Byte array to compare</param>
13+
/// <returns>True if equal, else false</returns>
14+
/// <remarks>
15+
/// Assumes that the byte arrays have the same length.
16+
/// This method is safe against timing attacks.
17+
/// </remarks>
18+
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
19+
public static bool AreEqual(byte[] a1, byte[] a2)
20+
{
21+
bool result = true;
22+
for (int i = 0; i < a1.Length; ++i)
23+
{
24+
if (a1[i] != a2[i])
25+
result = false;
26+
}
27+
return result;
28+
}
29+
}
30+
#endregion
31+
}

p2pconn/Cryptography/Sha256.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System.Security.Cryptography;
2+
using System.Text;
3+
4+
namespace Cryptography
5+
{
6+
#region " Sha256 check"
7+
public static class Sha256
8+
{
9+
public static string ComputeHash(string input)
10+
{
11+
byte[] data = Encoding.UTF8.GetBytes(input);
12+
13+
using (SHA256Managed sha = new SHA256Managed())
14+
{
15+
data = sha.ComputeHash(data);
16+
}
17+
18+
StringBuilder hash = new StringBuilder();
19+
20+
foreach (byte _byte in data)
21+
hash.Append(_byte.ToString("X2"));
22+
23+
return hash.ToString().ToUpper();
24+
}
25+
26+
public static byte[] ComputeHash(byte[] input)
27+
{
28+
using (SHA256Managed sha = new SHA256Managed())
29+
{
30+
return sha.ComputeHash(input);
31+
}
32+
}
33+
}
34+
#endregion
35+
}

p2pconn/Form1.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ private void button4_Click(object sender, EventArgs e)
283283
if(bConnected == true)
284284
{
285285
Writetxtchatrom("Blue", txtnsg.Text);
286-
SenderReceiver.SendMessage("c|" + Functions.Base64Encode(txtnsg.Text));
286+
SenderReceiver.SendMessage("c|" + txtnsg.Text);
287287
txtnsg.Text = "";
288288
}
289289
else

p2pconn/SenderReceiver.cs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Runtime.InteropServices;
77
using System.Windows.Forms;
88
using UdtSharp;
9+
using Cryptography;
910

1011
namespace p2pcopy
1112
{
@@ -24,6 +25,8 @@ public static class SenderReceiver
2425
private static Stopwatch RenderSW = Stopwatch.StartNew();
2526
[DllImport("user32.dll")]
2627
private static extern uint MapVirtualKey(uint uCode, uint uMapType);
28+
private static string ENCRYPTIONKEY = "SPXGPU3UPSIWSX5NLKFTIVN5RHXZW1F2H8CC2ORE";
29+
static readonly Aes256 aes = new Aes256(ENCRYPTIONKEY);
2730
#endregion
2831

2932
#region "recive data <======"
@@ -44,11 +47,15 @@ static internal void Run(Object conn)
4447
{
4548
try
4649
{
47-
string messagge = sreader.ReadString(); // err
48-
if (messagge != null && messagge.Length > 0)
50+
string message = sreader.ReadString(); // err
51+
52+
// aes 256 bit decode
53+
message = aes.Decrypt(message);
54+
55+
if (message != null && message.Length > 0)
4956
{
5057

51-
string[] words = messagge.Split('|');
58+
string[] words = message.Split('|');
5259
switch (words[0])
5360
{
5461
case "peer":
@@ -59,7 +66,7 @@ static internal void Run(Object conn)
5966
break;
6067

6168
case "c":
62-
GlobalVariables.Root.Writetxtchatrom("Green", Functions.Base64Decode(words[1]));
69+
GlobalVariables.Root.Writetxtchatrom("Green", words[1]);
6370
break;
6471

6572
case "openp2pDesktop":
@@ -223,6 +230,8 @@ static internal void SendMessage(string message)
223230
{
224231
if (isConnected && netStream.CanWrite)
225232
{
233+
// aes 256 bit encode
234+
message = aes.Encrypt(message);
226235
swriter = new BinaryWriter(netStream);
227236
swriter.Write(message);
228237
swriter.Flush();

p2pconn/p2pconn.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@
9393
<Reference Include="System.Xml" />
9494
</ItemGroup>
9595
<ItemGroup>
96+
<Compile Include="Cryptography\Aes256.cs" />
97+
<Compile Include="Cryptography\SafeComparison.cs" />
98+
<Compile Include="Cryptography\Sha256.cs" />
9699
<Compile Include="Form1.cs">
97100
<SubType>Form</SubType>
98101
</Compile>

0 commit comments

Comments
 (0)