using System.Net.Sockets; using System.Net; using System.Text; using System; using System.Security.Cryptography; namespace Naloga { class Server { const int STD_PORT = 1234; const string STD_IP = "127.0.0.1"; const int STD_BUFF = 256; static void Main() { TcpListener listener = new TcpListener(IPAddress.Parse(STD_IP), STD_PORT); listener.Start(); TcpClient client = listener.AcceptTcpClient(); NetworkStream tcpStream = client.GetStream(); FileStream fileStream = new FileStream("video.mp4", FileMode.OpenOrCreate); int bufferCount = Convert.ToInt32(Math.Ceiling((double)fileStream.Length / (double)STD_BUFF)); byte[] size = BitConverter.GetBytes(bufferCount); tcpStream.Write(size, 0, size.Length); using (ECDiffieHellmanCng eCDiffieHellmanCng = new ECDiffieHellmanCng()) { eCDiffieHellmanCng.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; eCDiffieHellmanCng.HashAlgorithm = CngAlgorithm.Sha256; byte[] myPublicKey = eCDiffieHellmanCng.PublicKey.ToByteArray(); tcpStream.Write(myPublicKey, 0, myPublicKey.Length); byte[] therePublicKey = new byte[myPublicKey.Length]; int retLenght = tcpStream.Read(therePublicKey, 0, therePublicKey.Length); CngKey thereKey = CngKey.Import(therePublicKey, CngKeyBlobFormat.EccPublicBlob); byte[] myKey = eCDiffieHellmanCng.DeriveKeyMaterial(thereKey); using (Aes aes = Aes.Create()) { aes.Key = myKey; aes.IV = Encoding.UTF8.GetBytes("sestnajst1616161"); ; //tcpStream.Write(aes.IV, 0, aes.IV.Length); //Console.WriteLine(Encoding.UTF8.GetString(aes.IV)); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; // Encrypt the message using (CryptoStream cs = new CryptoStream(fileStream, aes.CreateEncryptor(), CryptoStreamMode.Read)) { for(int i = 0; i < bufferCount+1; i++) { byte[] buffer = new byte[STD_BUFF]; int readBytes = cs.Read(buffer, 0, buffer.Length); tcpStream.Write(buffer, 0, readBytes); } cs.Close(); } aes.Dispose(); } eCDiffieHellmanCng.Dispose(); } Console.WriteLine("Finished"); fileStream.Close(); tcpStream.Close(); client.Close(); listener.Stop(); Console.ReadKey(); } } }