Created
February 13, 2018 07:54
-
-
Save MattiaPezzanoAiv/0760faadceaf8d3ced37c2f43553eb5f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Numerics; | |
namespace WireSharkLesson | |
{ | |
public struct Datas | |
{ | |
public BigInteger p; | |
public BigInteger g; | |
public BigInteger message; | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); | |
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 5555); | |
socket.Bind(ep); | |
Dictionary<IPEndPoint, BigInteger> clients = new Dictionary<IPEndPoint, BigInteger>(); | |
Random r = new Random(); | |
//read p, read g, read alice message SHORT PREFIX | |
while (true) | |
{ | |
byte[] buffer = new byte[1024]; | |
EndPoint clientEP = new IPEndPoint(IPAddress.Any, 2000); | |
int dataReceived = socket.ReceiveFrom(buffer, ref clientEP); | |
if (dataReceived < 0) continue; | |
if (!clients.ContainsKey((IPEndPoint)clientEP)) | |
{ | |
Datas d = new Datas(); | |
short pLength = BitConverter.ToInt16(buffer, 0); | |
byte[] p = new byte[pLength]; | |
Buffer.BlockCopy(buffer, 2, p, 0, pLength); | |
d.p = new BigInteger(p); | |
d.g = buffer[2 + pLength]; | |
short messageLength = BitConverter.ToInt16(buffer, 3 + pLength); | |
byte[] message = new byte[messageLength]; | |
Buffer.BlockCopy(buffer, 5 + pLength, message, 0, messageLength); | |
d.message = new BigInteger(message); | |
int myRandom = r.Next(); //bob secret number | |
BigInteger secretKey = BigInteger.ModPow(d.message, myRandom, d.p); | |
clients.Add((IPEndPoint)clientEP, secretKey); | |
BigInteger myMessage = (BigInteger.ModPow(d.g, myRandom, d.p)); | |
List<byte> toSend = new List<byte>(); | |
toSend.AddRange(BitConverter.GetBytes((short)myMessage.ToByteArray().Length)); | |
toSend.AddRange(myMessage.ToByteArray()); | |
socket.SendTo(toSend.ToArray(), clientEP); | |
Console.WriteLine("data received "+ myMessage); | |
} | |
else | |
{ | |
List<byte> decriptedData = new List<byte>(); | |
byte[] clientKey = clients[(IPEndPoint)clientEP].ToByteArray(); | |
for (int i = 0; i < dataReceived; i++) | |
{ | |
decriptedData.Add(buffer[i] ^= clientKey[i]); | |
} | |
string text = Encoding.ASCII.GetString(decriptedData.ToArray()); | |
Console.WriteLine(text); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment