Secured Chat application in C# Final Report – spring 2006 By: Eyal Madar Mikael Cohen mazaldar@gmail.com mikael.cohen@gmail.com Supervisor: Viktor Kulikov Septembre, 2006 1 Spring 2006 Secured Chat application in C# Contents I. Introduction ............................................................ 4 A. OVERVIEW .................................................................................................................... 4 B. BENEFITS OF SECURED APPLICATION ............................................................................. 4 C. WHAT IS .NET REMOTING? .......................................................................................... 4 II. Remoting ............................................................ 5 A. INTRODUCTION ............................................................................................................. 5 B. REMOTE OBJECT ........................................................................................................... 6 C. SERVER ......................................................................................................................... 8 D. CLIENT .......................................................................................................................... 9 E. CONCLUSION ............................................................................................................... 10 III. User interface design .......................................................... 11 A. OVERVIEW .................................................................................................................. 11 B. SERVER DESCRIPTION .................................................................................................. 11 C. CLIENT DESCRIPTION .................................................................................................. 12 IV. Programming Design A. .......................................................... 20 CHAT ARCHITECTURE ................................................................................................. 20 21 B. SERVER FORM ............................................................................................................. 21 C. SERVER REMOTE ......................................................................................................... 22 D. CLIENT FORM .............................................................................................................. 25 1. Public Chat .......................................................................................................... 25 2. Private Chat ......................................................................................................... 27 3. File Transfer ........................................................................................................ 29 E. CLIENT REMOTE.......................................................................................................... 35 F. SUMMARY ................................................................................................................... 36 V. Security A. .......................................................... 38 RSA PRINCIPLE ........................................................................................................... 38 1. Intuition ................................................................................................................ 38 2. Key generation ..................................................................................................... 38 3. Encrypting messages ............................................................................................ 40 2 Spring 2006 4. B. Secured Chat application in C# Decrypting messages............................................................................................ 40 ENCRYPTION DESIGN ................................................................................................... 41 VI. Conclusion .......................................................... 42 A. ACHIEVEMENTS .......................................................................................................... 42 B. POSSIBLE FUTURE DEVELOPMENT ............................................................................... 42 3 Spring 2006 Secured Chat application in C# I. Introduction A. Overview The Internet allows computer users to connect to other computers and information to be shared easily, wherever they may be across the world. Instant messaging typically boosts communication and allows easy collaboration. In contrast to e-mails or phone, the parties know whether the peer is available. On the other hand, people are not forced to reply immediately to incoming messages. This way, communication via instant messaging can be less intrusive than communication via phone, which is partly a reason why instant messaging is becoming more and more important in corporate environments. Moreover, we may do this with use of security, authentication and encryption technologies, depending on the requirements. B. Benefits of secured application Secured chat and file transfer is encouraging new ways of working from home, collaboration and information sharing in many industries. An accountant sitting at home can audit the books of a company based in another country, on a server situated in a third country that is remotely maintained in a fourth, while not fearing from industrial espionage. C. What is .NET Remoting? .NET Remoting is an enabler for application communication. It is a generic system for different applications to use to communicate with one another. .NET objects are exposed to remote processes, thus allowing interprocess communication. The applications can be located on the same computer, different computers on the same network, or even computers across separate networks. 4 Spring 2006 Secured Chat application in C# II. Remoting A. Introduction There are several ways to execute a process on other computers or other application domains which are related to each other through a network (LAN or Internet). Remote executing means running a process in another computer without using any resource or CPU load in the local computer. Using a client/server application is the only solution for doing so. We can create and use such applications in a wide range of platforms and methodologies by using .NET Remoting which is built on the .NET Framework technology. A managed object can be accessed by a remote client. When a client makes a call to an object of the server program, a proxy object grabs the call first. The proxy object behaves like the remote object, except that the proxy object is running locally. Remoting allows calling methods and passing objects across Application Domains. We need to create our own method of cross-application communication. We have an object that needs to accept calls from client applications across HTTP. First, we'd need to define our object’s location as a URL of some kind. Then we would need to choose a port that the object should listen to. We would also need some way of publishing the interface of our object so that clients would know what methods are available to call, and we would need a method of describing the interface and handling the messaging between objects. The creators of the .NET Framework have done just that and have exposed the remoting functionality as a powerful way for programmers to start getting their applications to communicate. 5 Spring 2006 Secured Chat application in C# B. Remote Object The methods that will be called from the client are implemented in a remote object class. In Fig 1, we can see an instance of this class as the Remote Object. Because this remote object runs inside a process that is different from the client process – usually also on a different system – the client can't call it directly. Instead the client uses a proxy. For the client, the proxy looks like the real object with the same public methods. When the methods of the proxy are called, messages will be created. These are serialized using a formatter class, and are sent into a client channel. The client channel communicates with the server part of the channel to transfer the message across the network. The server channel uses a formatter to deserialize the message, so that the methods can be dispatched to the remote object: Figure 1: Remote Object In the simplest case, we have to create a remote object class and instantiate a channel for a .NET Remoting application. The formatter 6 Spring 2006 Secured Chat application in C# and the proxy will be supplied automatically. The architecture is very flexible in that different formatters and channels can be used. A remote object is implemented in a class that derives from System.MarshalByRefObject. MarshalByRefObject defines methods for lifetime services that will be described later when we use the leasing features. A remote object is confined to the application domain where it is created. A client doesn't call the methods directly; instead a proxy object is used to invoke methods on the remote object. Every public method that we define in the remote object class is available to be called from clients. The following code sample shows a simple remote object class. The method Hello() is declared public to make it available for a remoting client: // MyRemoteObject.cs using System; namespace Chat { public class MyRemoteObject : System.MarshalByRefObject { public MyRemoteObject() { Console.WriteLine("Constructor called"); } public string Hello() { Console.WriteLine("Hello called"); } } } 7 Spring 2006 Secured Chat application in C# C. Server The remote object needs a server process where it will be instantiated. This server has to create a channel and put it into listening mode so that clients can connect to this channel. When the client connects to the remote object it needs to know the URI of the object, that is, the name of the host where the remote object is running, the protocol and port number to connect to, the name of the server, and the name of the remote object. Such a connection string can look like this: tcp://localhost:9000/SimpleServer/MyRemoteObject The server is implemented in a console application. RemotingConfiguration configure the server and activate the channel. The creation of the remote object and communication with the client is done by the remoting infrastructure; we just have to make sure that the process doesn't end. We do this with Console.ReadLine() that will end the process when the user enters the return key: // ChatServer.cs class ChatServer { [STAThread] static void Main(string[] args) { TcpChannel chan = new TcpChannel( 9000 ); ChannelServices.RegisterChannel( chan ); RemotingConfiguration.RegisterWellKnownServiceType( typeof(ChatApplication.ChatServerObject), "ChatServer", WellKnownObjectMode.Singleton ); System.Console.WriteLine( "Hit <enter> to exit..." ); System.Console.ReadLine(); } } 8 Spring 2006 Secured Chat application in C# D. Client The client specify the URL of the server using tcp://hostname:port/application. In this example,the server runs on localhost with the port number 9000. The application name of the server is defined with the name attribute of the <application> element in the server configuration file. The <wellknown> element specifies the remote object we want to access. The type attribute defines the type of the remote object and the assembly. The url attribute defines the path to the remote object. As in the server, we can activate the client channel. Next we call the method Hello() of this object: using using using using System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Tcp; namespace RemotingSamples { public class Client { public static void Main(string[] args) { ChannelServices.RegisterChannel(new TcpChannel()); RemoteHello obj = (HelloServer)Activator.GetObject( typeof(RemotingSamples.RemoteHello), "tcp:// localhost:9000/RemoteHello"); Console.WriteLine(obj.Hello()); } } } 9 Spring 2006 Secured Chat application in C# E. Conclusion We present in this chapter, a very simple of remoting application. Fig 2 summarizes remoting concept. Figure 2: Remoting Concept We can now build a Client/Server chat application based on remoting. The chat must be very intuitive for the users and allows secured file transfer in private chat. 10 Spring 2006 Secured Chat application in C# III. User interface design A. Overview Our application comports the following main sides: One single server One or several clients (users) Both client and server are GUI (graphic user interface) applications. When a client sends a message, the message is routed to the server, and the server broadcasts the message to all of the connected clients. B. Server description a) The Graphic user interface The GUI is a windows form, which allows performing the two following simple operations: 11 Spring 2006 Secured Chat application in C# (1) Connecting Opens and registers a Tcp Channel, and prepares the infrastructure to manage the clients (2) Disconnecting Kicks all the users, and close the Tcp channel C. Client description a) An elegant form As you can see on the illustration below, the user interface for the client is an elegant form: The frame around it is matched with the windows style. 12 Spring 2006 Secured Chat application in C# The different tabs which open appear with a pretty gray relief. The utilization is clear and intuitive. By double-clicking on the top bar, you can easily put it in full screen. b) Connecting to the server In order to connect to the server, the user has to perform 3 simple operations: (1) Typing the IP address of the server (2) Choosing a Nickname (3) Then, to press "Logon" 13 Spring 2006 Secured Chat application in C# Notify that until you have been successfully connected to the server, the buttons "send" and "logoff" stay disabled. If the Nickname is already taken, the connection is refused, and the user is (politely) invited to pick another one. When another user joins the forum, every participant is alerted by the message: "<your friend nickname> has logged in the " and his name disappears from the participant list. (4) You are connected! (5) The list off all the participants to the chat room is sent by the server, and each one appears on the right side of the screen. c) Disconnecting from the server In order to disconnect from the server, you may perform one of the two actions: (1) Click on "Logoff" (2) Click on the windows top right cross (3) Every participant is alerted by the message: "<your nickname> has logged out" and your name disappears from their participant lists. 14 Spring 2006 Secured Chat application in C# Clicking on the windows top right cross is conform, and the disconnection is totally proper. d) Chatting in the public forum In order to post a message, you have to: (1) Type it in the bottom text box. (2) Press "enter" or click on the button "Send". (3) The message appears on the forum at all the participant, preceded by "<your nickname> says:" 15 Spring 2006 Secured Chat application in C# e) Perform a secured private Chat In order to open a private conversation with "Bobby": (1) Double click on "Bobby" on the right frame (2) Bobby receives an alert: "Do you want to start a private chat with <your nick name>?" (3) Bobby clicks on the button "Ok" (4) You are connected! (5) A "Bobby" tab appears near the one of the Forum (6) Click on it, and converse with Bobby in a total and secured privacy 16 Spring 2006 Secured Chat application in C# f) Quit the private chat To quit the private chat, simply close the tab by clicking on the cross, Bobby is alerted. 17 Spring 2006 Secured Chat application in C# On the Bobby side, the buttons "Send" and "Send file" are disabled, and Bobby can't send anything anymore. g) Sending a file When you converse in a private chat, you have the option of sending files to Bobby, in a total secured way. (1) Press on Send file (2) Pick the file to send (3) Click on "Open" (4) Bobby choose the destination folder he wants to receipt the file (5) The transfer is performed, and Bobby receives a notification 18 Spring 2006 Secured Chat application in C# 19 Spring 2006 IV. Secured Chat application in C# Programming Design A. Chat Architecture The solution consists of four projects: ServerConsole ServerInterface ClientApp ClientInterface We made this separation for the sake of reusability. ServerConsole is a console application. ServerInterface holds the necessary interfaces (IServer, UserData) for the ServerConsole (where we can found the ServerForm and ServerRemote classes). ClientApp is a Windows Form, and it implements IClientApp and IPrivateApp. ClientInterface holds the necessary interfaces (IClientApp, IClient, IPrivateApp, and IPrivate) for the ClientApp and ClientRemote. Fig 3 shows a diagram explaining the chat architecture: 20 Spring 2006 Secured Chat application in C# Figure 3: Chat Architecture B. Server Form Executing the Server.exe file opens a windows form "Server". It also creates a server remote class object, registers it and links the form with the created server remote. When the user clicks on the connect button of the server application, it will open a server Tcp channel. 21 Spring 2006 Secured Chat application in C# BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider(); serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider(); IDictionary props = new Hashtable(); props["port"] = 9001; props["name"] = ""; TcpChannel channel = new TcpChannel(props, clientProv, serverProv); ChannelServices.RegisterChannel(channel); Now, the server remote is communicating with the server form and is marshaled. The Server Form implements the Server Interface function: int Login(string machinename, string portno, string username); void Logoff(string username); void SendMsg(string sendermachine, string senderusername, string receiverusername, string msgString); int GetPortNo(); bool UserNameExists(string username); int AskForPrivate(string his_nickname, string my_nickname); string GetIpFromUser(string user); The Server can also disconnect all users with the disconnect button. C. Server Remote A form cannot be marshalling. In order to make remoting possible, we have to create a class linked to the form. This class (Server Remote) will be marshaled and this object will be available through the network. Our Server chat application is then composed of the elements: Server Form and Server remote. Server Remote class implements the server Interface public class ServerRemote : MarshalByRefObject, ServerSpace.IServer 22 Spring 2006 Secured Chat application in C# Server Remote also keeps a variable: private IServerApp theServer = null; Setting variable values as follows will help us to link the client form or the private chat user control to the client remote class. public IServerApp theMainServer { set { theServer = value; } } In Fig. 4, one can see the different functions that the server can use on the clients. Figure 4: Client Interface for Server 23 Spring 2006 Secured Chat application in C# When the Client calls a Server function, it will call a Server Remote function. The Server Remote class will transfer the demand to the Server Form. Figure 5: Server Form accessible via Server Remote 24 Spring 2006 Secured Chat application in C# D. Client Form As we have seen in the above subsection, a form cannot be marshalled. In order to make remoting possible, we have to create a class linked to the form. This class (client Remote) will be marshaled and this object will be available through the network. Our client chat application is then composed of the elements: Client Form and Client remote. Client Remote class implements the private and main chat interfaces. 1. Public Chat Executing the Client.exe file opens a windows form "Chat Secure". It also creates a client remote class object, registers it and links the form with the created client remote. Now, the client class is communicating with the client form and then is marshaling itself throught the network. ClientClass = new ClientRemote(); ObjRef obj = RemotingServices.Marshal(ClientClass, "Client"); // Create apllications MainForm ClientApp frmMain = new ClientApp(); ClientClass.theMainClient = (IClientApp)frmMain; Application.Run(frmMain); The user can now log on. Clicking on the LogOn button launches a thread LogonDlg. If the server is available, the client will create an instance of server remote on the client machine. ServerObj = (ServerSpace.IServer)Activator.GetObject(typeof(ServerSpace.ISe rver), "tcp://" + serverName.Text + ":9001/Server"); 25 Spring 2006 Secured Chat application in C# The client can use a number of functions of the Server given by IServer interface: int Login(string machinename, string portno, string username); void Logoff(string username); void SendMsg(string sendermachine, string senderusername, string receiverusername, string msgString); int GetPortNo(); bool UserNameExists(string username); int AskForPrivate(string his_nickname, string my_nickname); string GetIpFromUser(string user); On the logging, the client calls the GetPortNo function. The server sends to the client a valid port number. The client opens a client tcp connection: TcpChannel channel = new TcpChannel(props, clientProv, serverProv); ChannelServices.RegisterChannel(channel); The user is connected to the chat room with an updated user list. He can send a message or start a private chat. In Fig. 6, one can see the different functions that the server provides to clients. 26 Spring 2006 Secured Chat application in C# Figure 6: Server Interface for Client 2. Private Chat As it was already noted above, users may chat in a private way, i.e. no one, even the server, can see what is said in the private chat or which files are being downloaded. The Server will just know that these two users are chatting in a private room. User A has to click on the desired user B for a private chat. A thread is launched. User A asks to User B for a private chat via the If User B accepts as, he will send him a port for private chatting. int newPort = Server.AskForPrivate(user, userName.Text); If the port is good then User A creates a Tabpage containing a UserControl responsible of the private chat application. 27 Spring 2006 Secured Chat application in C# TabPage objTabPage = new TabPage(); UserControl1 pc = new UserControl1(); objTabPage.Controls.Add(pc); this.tabControl1.TabPages.Add(objTabPage); pc.Dock = DockStyle.Fill; pc.port = newPort; pc.ip = his_ip; objTabPage.Text = user; pc.his_nickname = user; pc.my_nickname = userName.Text; pc.MainClientPort = portno; pc.ClientName = "PrivateClient" + newPort.ToString(); ClientRemote PrivateClient = new ClientRemote(); PrivateClient.thePrivateApp = (IPrivateApp)pc; ObjRef obj1 = RemotingServices.Marshal(PrivateClient, "PrivateClient" + newPort.ToString()); TcpChannel channel = new TcpChannel(props, clientProv, serverProv); ChannelServices.RegisterChannel(channel); More than one private chat may be simultaneous open, each one with a different user. Figure 7: Launching a Private Chat A PrivateChat interface is given to the users: 28 Spring 2006 Secured Chat application in C# public interface IPrivate { void UpdateClientPrivate(string msg); void UserLeft(); void DoYouWantToDownload(string path, string fn, string his_nickname, int his_port); void DownloadFile(string serverFullFilePath, string localFullFilePath); } By using UpdateClientPrivate, User A will append his message to User B message box. If a user wants to leave the private, he has to alert the other user. When the user closes the private chat, UserLeft function will be launched and will alert that the user is not here anymore. PrivateClient = (ClientSpace.IPrivate)Activator.GetObject(typeof(ClientSpace. IPrivate), "tcp://" + ip + ":" + port.ToString() + "/" + ClientName); PrivateClient.UserLeft(); Both users may use these private chat functions. 3. File Transfer a) Overview Our transfer file function allows sending any type of file to a specified user, using functions from framework 2.0 b) Server side The main object used in our assembly is the class TcpListener TcpListener allows providing simple methods that listen and accept (or refuse) connections on given port and Tcp address. First, the client has to start the TcpListener, by executing Start: 29 Spring 2006 Secured Chat application in C# public void Start(Int32 port, String iPAddress) { try { ListenerTcp = new TcpListener(localAddr, port); ListenerTcp.Start(); this.StartListenToTcpClient(); this.isStarted = true; } catch (SocketException e) { throw e; } } Now our Listener is capable of receiving client flow. We have now to treat the demand, and send a response back. This is done through the object NetworkStream. Here, we will catch the client flow that will give us the order to execute. The orders are simple: Asking authorization to connect Asking to transfer a file 30 Spring 2006 Secured Chat application in C# NetworkStream stream = client.GetStream(); Int32 i = stream.Read(bytes, 0, bytes.Length); data = System.Text.Encoding.UTF8.GetString(bytes, 0, i); tabArgs = data.Split(new char[] { '|' }); if (data.StartsWith("Request", StringComparison.CurrentCultureIgnoreCase)) { this.CheckForAutorisations(tabArgs, stream, server); } else { this.SendFile(tabArgs, stream, server); } client.Close(); Once the flow is received, it stays to use our network flow open by the client to send back the answer. FilePath = tabArgs[1]; if (!System.IO.File.Exists(FilePath)) { throw new System.IO.FileNotFoundException("Bewise Peer to Peer : Fichier non trouv sur le serveur", FilePath); } System.IO.FileInfo fileInfo = new System.IO.FileInfo(FilePath); fs = new FileStream(fileInfo.FullName, FileMode.Open); br = new BinaryReader(fs, Encoding.UTF8); Byte[] bb = new Byte[1024]; while (br.Read(bb, 0, bb.Length) != 0) { networkStream.Write(bb, 0, bb.Length); } c) Client side Our Client will have two main functions: (1) Request authorization to connect to the server 31 Spring 2006 Secured Chat application in C# (2) Send the name of the file to download and save it Here we used the class TcpClient, witch allows connecting to a server. One connected to the server, the TcpClient returns the flow on the port to the address. The authorization is simply done by sending text data. TcpClient client = new TcpClient(iPAddress, port); NetworkStream networkStream = client.GetStream(); string request = string.Format("Request|{0}", Client.GetHostAddress()); Byte[] requestByte = Encoding.UTF8.GetBytes(request); networkStream.Write(requestByte, 0, requestByte.Length); Byte[] bytes = new Byte[256]; Int32 i = networkStream.Read(bytes, 0, bytes.Length); String data = System.Text.Encoding.UTF8.GetString(bytes, 0, i); String[] tabArgs = data.Split(new char[] { '|' }); isConnected = Convert.ToBoolean(tabArgs[1]); Reception - In order to start downloading, we have to create an asynchrone download delegate 32 Spring 2006 Secured Chat application in C# public delegate void AsynchroneDownloadDelegate(BinaryWriter w, FileStream fs, NetworkStream ns); private AsynchroneDownloadDelegate threadStart; public void DownloadFile(string serverFullFilePath, string localFullFilePath) { try { threadStart = new AsynchroneDownloadDelegate(AsynchroneBeginDownload); AsyncCallback asyncCallback = new AsyncCallback(AsynchroneEndDownload); threadStart.BeginInvoke(w, fs, networkStream, asyncCallback, threadStart); } } private void AsynchroneBeginDownload(BinaryWriter w, FileStream fs, NetworkStream ns) { } private void AsynchroneEndDownload(IAsyncResult ar) { AsynchroneDownloadDelegate threadStart = (AsynchroneDownloadDelegate)ar.AsyncState; threadStart.EndInvoke(ar); } The remote downloading of the file is done quite simply, a request with the name of the input file, and the reception of the file in answer. It is then enough to open a flow file (in writing mode!) and to take delivery of flow network given by our TcpClient 33 Spring 2006 Secured Chat application in C# TcpClient client = new TcpClient(this.ipAddress, this.port); NetworkStream networkStream = client.GetStream(); string request = string.Format("Download|{0}", serverFullFilePath.ToString()); Byte[] b = Encoding.UTF8.GetBytes(request); networkStream.Write(b, 0, b.Length); FileStream fs = new FileStream(localFullFilePath, FileMode.OpenOrCreate); BinaryWriter w = new BinaryWriter(fs); threadStart = new AsynchroneDownloadDelegate(AsynchroneBeginDownload); AsyncCallback asyncCallback = new AsyncCallback(AsynchroneEndDownload); threadStart.BeginInvoke(w, fs, networkStream, asyncCallback, threadStart); 34 Spring 2006 Secured Chat application in C# E. Client Remote A form cannot be marshalled. In order to make remoting possible, we have to create a class linked to the form. This class (client Remote) will be marshaled and this object will be available through the network. Our client chat application is then composed of the elements: Client Form and Client remote. Client Remote class implements the private and main chat interfaces. public class ClientRemote : MarshalByRefObject, ClientSpace.IClient, ClientSpace.IPrivate Client Remote also keeps two variables: private IClientApp theClient = null; private IPrivateApp thePrivateClient = null; Setting variable values as follows will help us to link the client form or the private chat user control to the client remote class. public IClientApp theMainClient { set { theClient = value; } } public IPrivateApp thePrivateApp { set { thePrivateClient = value; } } 35 Spring 2006 Secured Chat application in C# When the Server calls a Client function, it will call a Client Remote function. The Client Remote class will transfer the demand to the Client Form. Figure 8: Chating via Client Remote F. Summary We have implemented a chat using .Net especially C# and Remoting. The chat allows peer to peer private chat between users and a secured transfer files and chat is possible. By using Windows form, we have implemented an easy-to-use and intuitive chat interface. The code has been written carefully so it will deal with exception. The Fig. 9 summarizes the chat application architecture. 36 Spring 2006 Secured Chat application in C# Figure 9: Chat Diagram 37 Spring 2006 Secured Chat application in C# V. Security A. RSA Principle 1. Intuition RSA involves two keys: public key and private key (a key is a constant number later used in the encryption formula.) The public key can be known to everyone and is used to encrypt messages. These messages can only be decrypted by use of the private key. In other words, anybody can encrypt a message, but only the holder of a private key can actually decrypt the message and read it. Intuitive example: Bob wants to send Alice a secret message that only she can read. To do this, Alice sends Bob a box with an open lock, for which only Alice has the key. Bob receives the box, he writes the message in plain English, puts it in the box and locks it with Alice's lock (now Bob can no longer read the message.) Bob sends the box to Alice and she opens it with her key. In this example, the box with the lock is Alice's public key, and the key to the lock is her private key. 2. Key generation Suppose Alice and Bob are communicating over an insecure (open) channel, and Alice wants Bob to send her a private (or secure) message. Using RSA, Alice will take the following steps to generate a public key and a private key: Choose two large prime numbers and such that , randomly and independently of each other. Compute . Compute the quotient . For the public exponent e choose an integer e > 1 that is coprime to . I.e., . 38 Spring 2006 Secured Chat application in C# Compute the private exponent d such that the congruence relation is satisfied. The prime numbers can be probabilistically tested for primality. A popular choice for the public exponents is e=216+1=65537. Some applications choose smaller values such as e = 3,5, or 35 instead. This is done in order to make implementations on small devices (e.g. smart cards) easier, i.e. encryption and signature verification are faster. But choosing small public exponents may lead to greater security risks. Steps 4 and 5 can be performed with the extended Euclidean algorithm; see modular arithmetic. Step 3 changed in PKCS#1 v2.0 to instead of . The public key consists of n, the modulus, and e, the public exponent (sometimes encryption exponent). The private key consists of n, the modulus, which is public and appears in the public key, and d, the private exponent (sometimes decryption exponent), which must be kept secret. For reasons of efficiency sometimes a different form of the private key (including CRT parameters) is stored: p and q, the primes from the key generation, d mod (p-1) and d mod (q-1) (often known as dmp1 and dmq1) (1/q) mod p (often known as iqmp) Though this form allows faster decryption and signing using the Chinese Remainder Theorem (CRT), it considerably lowers the security. In this form, all of the parts of the private key must be kept secret. Yet, it is a bad idea to use it, since it enables side channel attacks in particular if implemented on smart cards, which would most benefit from the efficiency 39 Spring 2006 Secured Chat application in C# win. (Start with y = xemodn and let the card decrypt that. So it computes yd(mod p) or yd(mod q) whose results give some value z. Now, induce an error in one of the computations. Then gcd(z − x,n) will reveal p or q.) Alice transmits the public key to Bob, and keeps the private key secret. p and q are sensitive since they are the factors of n, and allow computation of d given e. If p and q are not stored in the CRT form of the private key, they are securely deleted along with the other intermediate values from the key generation. 3. Encrypting messages Suppose Bob wishes to send a message M to Alice. He turns M into a number m < n, using some previously agreed-upon reversible protocol known as a padding scheme. Bob now has m, and knows n and e, which Alice has announced. He then computes the ciphertext c corresponding to m: This can be done quickly using the method of exponentiation by squaring. Bob then transmits c to Alice. 4. Decrypting messages Alice receives c from Bob, and knows her private key d. She can recover m from c by the following procedure: Given m, she can recover the original message M. The decryption procedure works because . Now, since ed ≡ 1 (mod p-1) and ed ≡ 1 (mod q-1), Fermat's little theorem yields and 40 Spring 2006 Secured Chat application in C# Since p and q are distinct prime numbers, applying the Chinese remainder theorem to these two congruencies yields . Thus, . B. Encryption design In our private chat, the system of encryption is relatively simple. Immediately after the private connection is opened, both users exchange their public keys, and keep it the whole time. After the sender receives the request of transfer, he has to encrypt the file with the key of the receiver, and then, send the encrypted file. After downloading, the receiver has to decrypt the file with its private key. 41 Spring 2006 VI. Secured Chat application in C# Conclusion A. Achievements The project was successful, and the goals globally reached. Using C# and .Net Remoting, we could build an intuitive chat, which allows public, private, secured discussions, and secured transfer files. The application is robust, and designed to answer to many exception cases. The code is relatively clear and allows easily eventual other programmers to enter into it to design new developments. B. Possible future development Programmers may be interested by adding two major functionalities to our chat: Voice conversation Video conference Both of these may ideally be designed for multi users, to allow conferences with several users. 42