Click here to Skip to main content
15,891,905 members
Articles / Programming Languages / C#
Tip/Trick

Secure way to send any file

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
20 Aug 2013CPOL1 min read 14K   551   10   3
Sending files securely to another user by exchanging secret key.

639712/SendingFile.png

Trusted way to exchange secret key between client/server

This tip describes a trusted way to encrypt a file and send it from client to server and decrypt it at server.

Secure transfer for files  

Sending files securely to another user by exchanging secret key

The idea is as following

First I send the file's name and its signature which is signing with my private key to the other user, then he will verify it by my public key, if it right he will generate half secret key, encrypt it with my public key and send it me back with first character is 1 to inform me that the signature is true or 0 if wrong, then I generate the other half of secret key and encrypt it with his public key and send it to him. Now we both have the full secret key. I encrypt the file with the full secret key and send it to him and he will encrypt it with the same secret key.

How to run the application

Run server code then choose from the interface where to save the received file. Choose folder to save the server public and private keys, run the client code and choose file to send. Press the Exchange button and choose folder to save the client public and private keys, then choose the server public key and client public key. Press Send to send encrypted file at client interface, then press decrypt file at server interface.

Here is the code for starting the server:

C#
//
#region StartServer
public void StartServer()
{
    generateKeyPair();

    try
    {
        timer1.Start();
       
        socket.Bind(IPEnd);
        socket.Listen(100);
        Socket accept = socket.Accept();
        byte[] clientData = new byte[1024 * 5000];
        int receivedBytesLen = accept.Receive(clientData);
        serverStatus.Text = "Receiving ...";
        int fileNameLen = BitConverter.ToInt32(clientData, 0);
        fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
        byte[] realData = getRealData(clientData, receivedBytesLen);
        byte[] sign = new byte[realData.Length - 4 - fileNameLen];
        System.Buffer.BlockCopy(realData, 4 + fileNameLen, sign, 0, realData.Length - 4 - fileNameLen);
        if (checkSigniture(fileName, sign))
        {
            //genrate sekret key and send it to client with ok begining
            ServerKey = Cryptographer.Key;
            string encr= EncryptSecretKey(ServerKey, 1024, clientPublicKey);
            byte[] ServerKey1 = Encoding.ASCII.GetBytes(encr);
            byte[] replay = new byte[ServerKey1.Length + 1];
            replay[0] = 1;
            System.Buffer.BlockCopy(ServerKey1, 0, replay, 1, ServerKey1.Length);
            accept.Send(replay);
            reciveKeyFromClient(accept);
        }
        else
        {
            serverStatus.Text = "UnMatching Sugniture";
        }
       

        serverStatus.Text = "Saving file...";

       // accept.Close();
        serverStatus.Text = "Reeived & Saved file; Server Stopped.";
    }
    catch (Exception ex)
    {
        serverStatus.Text = "File Receving error.";
    }
}
#endregion
...

Code for sending file from the client:

C#
public  void SendFile(string fileName)
{
    try
    {
     
        string filePath = "";

        fileName = fileName.Replace("\\", "/");
        while (fileName.IndexOf("/") > -1)
        {
            filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
            fileName = fileName.Substring(fileName.IndexOf("/") + 1);
        }
        byte[]byte[] signValue = Signature(fileName);
        byte[] byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
        if (fileNameByte.Length > 850 * 1024)
        {
            clientstatus = "Too big file.";
            return;
        }

        #region send Signiture
        byte[] filenameBuffer = Encoding.ASCII.GetBytes(fileName);
        int filenameLength = fileName.Length;
        byte[] filenameByte = BitConverter.GetBytes(filenameLength);
        byte[] dataToSend = new byte[filenameBuffer.Length + signValue.Length + filenameByte.Length];
        System.Buffer.BlockCopy(filenameByte, 0, dataToSend, 0, filenameByte.Length);
        System.Buffer.BlockCopy(filenameBuffer, 0, dataToSend, filenameByte.Length, filenameBuffer.Length);
        System.Buffer.BlockCopy(signValue, 0, dataToSend, 
               filenameByte.Length + filenameBuffer.Length, signValue.Length);
        clientSock.Connect(remoteEP);
        clientstatus = "File sending...";
                
        clientSock.Send(dataToSend);
        #endregion

        reciveServerSecretKey(clientSock);
        GenrateSecretKey();

        clientstatus = "key has been exchanged successfuly...";

    }
    catch (Exception ex)
    {
        if (ex.Message == "No connection could be made because the target machine actively refused it")
            clientstatus = "File Sending fail. Because server not running.";
        else
            clientstatus = "File Sending fail." + ex.Message;
    }
}
#endregion

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Syrian Arab Republic Syrian Arab Republic
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow to access ClientPublicKey in server Pin
Member 1164741226-May-15 20:52
Member 1164741226-May-15 20:52 
QuestionSending secret key Pin
clement_durand28-Aug-13 20:09
clement_durand28-Aug-13 20:09 
Maybe im way out of my depths here but why dont you just send a private key that you create yourself?
AnswerRe: Sending secret key Pin
mousaab.orabi5-Jul-14 17:03
mousaab.orabi5-Jul-14 17:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.