public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.m_currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); string incoming = szData.Substring(0, szData.Length - 1); if (incoming.StartsWith("/chg")) { #if _SHOWMSG MessageBox.Show("Mode Change Code recieved"); #endif string mode = incoming.Substring(4, 1); cryptor.rijn.Mode = (CipherMode)Convert.ToInt32(mode); tb_currentMode.Text = cryptor.rijn.Mode.ToString(); } else if (incoming.StartsWith("/sIV")) { #if _SHOWMSG MessageBox.Show("New IV recieved"); #endif string iv = incoming.Substring(4); cryptor.rijn.IV = ToByteArray(iv); tb_IV.Text = BytesToHex(cryptor.rijn.IV); } else if (incoming.StartsWith("/rsaS")) { #if _SHOWMSG MessageBox.Show("RSA public key received"); #endif string rsaKey = incoming.Substring(5); rsaserver = new RSACryptoServiceProvider(2048); rsaserver.FromXmlString(rsaKey); RSAParameters rsap = rsaserver.ExportParameters(false); tb_RsaPublicKey.Text = BytesToHex(rsap.Modulus); tb_RsaPublicKeyExpo.Text = BytesToHex(rsap.Exponent); // do not need begin cryptor.rijn.GenerateKey(); tb_aesKey.Text = BytesToHex(cryptor.rijn.Key); byte[] rsaEncData = rsaserver.Encrypt(cryptor.rijn.Key, true); string encKeyHex = BytesToHex(rsaEncData).Replace(" ", ""); tb_encKey.Text = encKeyHex; //do not need end string newKeyMsg = "/rsaC" + GetIP() + " " + myport + " " + rsa.ToXmlString(false); try { Object objData = newKeyMsg; byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString()); if (m_clientSocket != null) { m_clientSocket.Send(byData); } } catch (SocketException se) { MessageBox.Show(se.Message); } } else if (incoming.StartsWith("/tck")) { //recieved tickets //receive tickets and import them to a arraylist. mytickets tickets = new mytickets(); List<client> clientlist = new List<client>(); tickets.DecodeFromString(incoming.Substring(4)); int dest_count = tickets.GetClientCount(); for (int i = 0; i < dest_count; i++) { if ((!rsaserver.VerifyData(tickets.ticketlist[i].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signFirst)) || (!rsaserver.VerifyData(tickets.ticketlist[i].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signSecond))) { MessageBox.Show("AS is not authentic!"); } else { ASCIIEncoding ByteConverter = new ASCIIEncoding(); string originalData = ByteConverter.GetString(tickets.ticketlist[i].origFirst); string[] origfields = originalData.Split(' '); if (!rsa.ToXmlString(false).Equals(origfields[2])) { MessageBox.Show("This ticket is not mine!"); } else { string destData = ByteConverter.GetString(tickets.ticketlist[i].origSecond); string[] destfields = destData.Split(' '); client tempclient = new client(); tempclient.ip = destfields[0]; tempclient.port = destfields[1]; tempclient.publicKey = destfields[2]; tempclient.ticket = tickets.ExportSingleTicket(i); clientlist.Add(tempclient); } } } int numParts = dest_count - 1; //because the final part is the parity int lengthofEachPart = (int)(data.Length / numParts) + 1;//pad the last one //hash = BitConverter.ToString(cryptoTransformSHA1.ComputeHash()).Replace("-", ""); List<byte[]> parts = new List<byte[]>(); for (int i = 0; i < numParts; i++) { byte[] temp = new byte[lengthofEachPart]; for (int j = 0; j < lengthofEachPart; j++) { if (i == numParts - 1 && i * lengthofEachPart + j >= data.Length) //padding { temp[j] = 0x00000000; } else { temp[j] = data[i * lengthofEachPart + j]; } } parts.Add(temp); } //we have the parts, calculate the parity part byte[] parityPart = new byte[lengthofEachPart]; for (int j = 0; j < lengthofEachPart; j++) { byte xor = new byte(); xor = 0 ^ 0; for (int i = 0; i < numParts; i++) { byte[] temp = (byte[])parts[i]; xor ^= temp[j]; } parityPart[j] = xor; } parts.Add(parityPart); //encrypt all parts with per file key Random rand = new Random(); long randomNumToGenerateKey = rand.Next() % 25000; byte[] randomNumToGenerateKeyByteEquivalent = new ASCIIEncoding().GetBytes(randomNumToGenerateKey.ToString()); perFileKey = cryptoTransformSHA1.ComputeHash(randomNumToGenerateKeyByteEquivalent); byte[] reducedperfilekey = new byte[16]; for (int k = 0; k < 16; k++) { reducedperfilekey[k] = perFileKey[k]; } cryptor.rijn.Key = reducedperfilekey; for (int i = 0; i < numParts+1; i++) { string tempPart = cryptor.EncryptMessage(BytesToHex(parts[i]).Replace(" ", "")); parts[i] = new ASCIIEncoding().GetBytes(tempPart); } //create the key and, secret share it with (n-1,n) threshold scheme. ShamirSS sham = new ShamirSS((uint)parts.Count, (uint)parts.Count - 1, 25000);//burasý oldu lakin, reconstruct etmek c*k zor. GF(2^8) kullanmak lazým en azýndan SharedData[] shamirOut = sham.ShareData(randomNumToGenerateKey); //connect to each ticket granted user to send its assigned part //out of scope // TODO ticketlarý gönder herkese //rsapeer = new RSACryptoServiceProvider(2048); for (int i = 0; i < dest_count; i++) { try { UpdateControls(false); // Create the socket instance m_peerSockets[m_peerCount] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Cet the remote IP address IPAddress ip = IPAddress.Parse(clientlist[i].ip); int iPortNo = System.Convert.ToInt16(clientlist[i].port); // Create the end point IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo); // Connect to the remote host m_peerSockets[m_peerCount].Connect(ipEnd); if (m_peerSockets[m_peerCount].Connected) { UpdateControls(true); //Wait for data asynchronously WaitForPeerData(m_peerSockets[m_peerCount]);//???? m_peerCount++; } } catch (SocketException se) { string str; str = "\nConnection failed, is the peer online?\n" + se.Message; MessageBox.Show(str); UpdateControls(false); } if (m_peerSockets[m_peerCount - 1].Connected) { try { string functionID = "/req"; string request = functionID + clientlist[i].ticket; //Object objData = request; byte[] byData = System.Text.Encoding.ASCII.GetBytes(request); if (m_peerSockets[m_peerCount - 1] != null) { m_peerSockets[m_peerCount - 1].Send(byData); } } catch (SocketException se) { MessageBox.Show(se.Message); } } else MessageBox.Show("shit load"); // TODO: Ks yarat encrypt et yolla cryptor.rijn.GenerateKey(); client temp = new client(); temp = clientlist[i]; temp.sessionkey = cryptor.rijn.Key; clientlist[i] = temp; tb_aesKey.Text = BytesToHex(cryptor.rijn.Key); rsapeer.FromXmlString(clientlist[i].publicKey); byte[] rsaEncData = rsapeer.Encrypt(cryptor.rijn.Key, true); byte[] rsaSigned; rsaSigned = rsa.SignData(rsaEncData, new SHA1CryptoServiceProvider()); string rsaSignedEncHex = BytesToHex(rsaEncData).Replace(" ", "") + " " + BytesToHex(rsaSigned).Replace(" ", ""); tb_encKey.Text = rsaSignedEncHex; try { string functionID = "/key"; string request = functionID + rsaSignedEncHex; //Object objData = request; byte[] byData = System.Text.Encoding.ASCII.GetBytes(request); if (m_peerSockets[m_peerCount - 1] != null) { m_peerSockets[m_peerCount - 1].Send(byData); } } catch (SocketException se) { MessageBox.Show(se.Message); } System.Threading.Thread.Sleep(50); try { MessageBox.Show("sending file parts"); string functionID = "/file"; string filepart = hash + " " + data.Length.ToString() + " " + BytesToHex(parts[i]).Replace(" ", ""); filepart += " " + shamirOut[i].xi.ToString() + " " + shamirOut[i].yi.ToString(); string filemsg = cryptor.EncryptMessage(filepart); string request = functionID + filemsg; //Object objData = request; byte[] byData = System.Text.Encoding.ASCII.GetBytes(request); if (m_peerSockets[m_peerCount - 1] != null) { m_peerSockets[m_peerCount - 1].Send(byData); } } catch (SocketException se) { MessageBox.Show(se.Message); } } } else if (incoming.StartsWith("/rectck")) { //recieved tickets //receive tickets and import them to a arraylist. mytickets tickets = new mytickets(); List<client> clientlist = new List<client>(); tickets.DecodeFromString(incoming.Substring(7)); int dest_count = tickets.GetClientCount(); enoughParts = dest_count; for (int i = 0; i < dest_count; i++) { if ((!rsaserver.VerifyData(tickets.ticketlist[i].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signFirst)) || (!rsaserver.VerifyData(tickets.ticketlist[i].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signSecond))) { MessageBox.Show("AS is not authentic!"); } else { ASCIIEncoding ByteConverter = new ASCIIEncoding(); string originalData = ByteConverter.GetString(tickets.ticketlist[i].origFirst); string[] origfields = originalData.Split(' '); if (!rsa.ToXmlString(false).Equals(origfields[2])) { MessageBox.Show("This ticket is not mine!"); } else { string destData = ByteConverter.GetString(tickets.ticketlist[i].origSecond); string[] destfields = destData.Split(' '); client tempclient = new client(); tempclient.ip = destfields[0]; tempclient.port = destfields[1]; tempclient.publicKey = destfields[2]; tempclient.ticket = tickets.ExportSingleTicket(i); clientlist.Add(tempclient); } } } //partsFromOthers = new List<byte[]>(); for (int i = 0; i < clientlist.Count; i++) { //send tickets //generate and send key //send me the file // TODO ticketlarý gönder herkese try { UpdateControls(false); // Create the socket instance m_peerSockets[m_peerCount] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Cet the remote IP address IPAddress ip = IPAddress.Parse(clientlist[i].ip); int iPortNo = System.Convert.ToInt16(clientlist[i].port); // Create the end point IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo); // Connect to the remote host m_peerSockets[m_peerCount].Connect(ipEnd); if (m_peerSockets[m_peerCount].Connected) { UpdateControls(true); //Wait for data asynchronously WaitForPeerData(m_peerSockets[m_peerCount]);//???? m_peerCount++; } } catch (SocketException se) { string str; str = "\nConnection failed, is the peer online?\n" + se.Message; MessageBox.Show(str); UpdateControls(false); } if (m_peerSockets[m_peerCount - 1].Connected) { try { string functionID = "/sndreq"; string request = functionID + clientlist[i].ticket + " " + hash; //Object objData = request; byte[] byData = System.Text.Encoding.ASCII.GetBytes(request); if (m_peerSockets[m_peerCount - 1] != null) { m_peerSockets[m_peerCount - 1].Send(byData); } } catch (SocketException se) { MessageBox.Show(se.Message); } } else MessageBox.Show("shit load"); } } else { //decrypt message tb_encRecv.Enabled = true; tb_encRecv.Text = BytesToHex(Convert.FromBase64String(szData.Substring(0, szData.Length - 1))); string decryptedText = cryptor.DecryptMessage(szData.Substring(0, szData.Length - 1)); richTextRxMessage.Text = decryptedText + "\n" + richTextRxMessage.Text; } WaitForData(); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } }
public void Reconstruct() { ShamirSS sham1 = new ShamirSS((uint)(enoughParts + 1), (uint)enoughParts, (long)(25000)); SharedData[] shares = new SharedData[enoughParts]; List<byte[]> finalParts = new List<byte[]>(); for (int i = 0; i < enoughParts; i++) { shares[i] = secretsFromOthers[i]; } long keygen = sham1.ReconstructData(shares); //decrypt parts byte[] reducedperfilekey = new byte[16]; for (int k = 0; k < 16; k++) { reducedperfilekey[k] = perFileKey[k]; } cryptor.rijn.Key = reducedperfilekey; //cryptor.rijn.Key = perFileKey; for (int i = 0; i < enoughParts; i++) { string tempString = new ASCIIEncoding().GetString(partsFromOthers[i]); string decrpytedHex = cryptor.DecryptMessage(tempString); finalParts.Add(ToByteArray(decrpytedHex)); } bool[] foundParts = new bool[enoughParts + 1]; for (int i = 0; i < enoughParts + 1; i++) { foundParts[i] = false; } for (int i = 0; i < enoughParts; i++) { foundParts[(uint)(shares[i].xi - 1)] = true; } byte[] finalFileData = new byte[finalParts[0].Length * enoughParts]; if (foundParts[enoughParts]) { //we have the parity part, xor to find the missing one //byte[] parityPart = new byte[finalParts[0].Length]; //for (int j = 0; j < finalParts[0].Length; j++) //{ // byte xor = new byte(); // xor = 0 ^ 0; // for (int i = 0; i < enoughParts; i++) // { // byte[] temp = (byte[])finalParts[i]; // xor ^= temp[j]; // } // parityPart[j] = xor; //} //for (int i = 0; i < enoughParts+1; i++) //{ // int partNum = 0; // //search Shamir // for (int j = 0; j < enoughParts; j++) // { // if (shares[j].xi == i + 1) // partNum = j; // } // finalParts[partNum].CopyTo(finalFileData, partNum * finalParts[0].Length); //} } else { //concatanate all for (int i = 0; i < enoughParts; i++) { int partNum = 0; //search Shamir for (int j = 0; j < enoughParts; j++) { if (shares[j].xi == i + 1) partNum = j; } finalParts[partNum].CopyTo(finalFileData, partNum * finalParts[0].Length); } } string filename = reconstructedFileName; FileStream fStream = new FileStream(filename, FileMode.CreateNew); BinaryWriter bw = new BinaryWriter(fStream); bw.Write(finalFileData); bw.Close(); fStream.Close(); }