Francesco
Francesco

Reputation: 77

Encrypt a file and send it through

I need to encrypt a file with AES 192 and send it to a client via socket. I'm using this code to encrypt the file:

string outputFile = "crypted";

            //Confidentiality
            RijndaelManaged AES192Confidentiality = new RijndaelManaged();
            AES192Confidentiality.KeySize = 192;
            AES192Confidentiality.BlockSize = 192;
            AES192Confidentiality.IV = ConfIV;
            AES192Confidentiality.Key = ConfKey;
            AES192Confidentiality.Mode = CipherMode.CBC;
            FileStream inputFileStream = new FileStream(par.GetFilePath(), FileMode.Open, FileAccess.Read);
            FileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
            byte[] inputFileData = new byte[(int)inputFileStream.Length];
            inputFileStream.Read(inputFileData, 0, (int)inputFileStream.Length);
            CryptoStream encryptStream = new CryptoStream(outputFileStream, AES192Confidentiality.CreateEncryptor(), CryptoStreamMode.Write);
            encryptStream.Write(inputFileData, 0, (int)inputFileStream.Length);
            encryptStream.FlushFinalBlock();
            encryptStream.Close();

I'm wondering how I can now send this encrypted temporary file through the socket, so that the receiver can reconstruct the file and decrypt it. Can someone give me some tutorial or guide ? Thank you all in advance

Upvotes: 2

Views: 1534

Answers (2)

Steve
Steve

Reputation: 7271

Consider using TcpClient to connect to the server and send the data. I'm not going to write a full answer as you've indicated this is school work, but look at how the example writes data:

// Get a client stream for reading and writing. 
NetworkStream networkStream = client.GetStream();

// Send the message to the connected TcpServer. 
networkStream.Write(data, 0, data.Length);

You might want to avoid tweak it slightly to use CopyTo to write the data directly from the crypto stream onto the network stream.

This assumes you don't have to solve the problem of secure key exchange.

Upvotes: 1

dkozl
dkozl

Reputation: 33394

you can create instance of NetworkStream for a socket and then call encryptStream.CopyTo(myNetworkStream);

Upvotes: 1

Related Questions