Creating a Public and Private Key using C#

public private keys

Following is a full sample (coding and details) on how to create both a public and a private key to an XML file using C#.


  • Folder named “Keys”
  • New Class named “PrivatePublicKey.cs”
  • An ASPX page with any name

Class PrivatePublicKey Imports

using System.IO;
using System.Security.Cryptography;

Class PrivatePublicKey Methods

public void CreateKeyPairs(string publicprivatepath, string publicpath)

FileStream filekeypair = new FileStream(publicprivatepath, FileMode.Create);
FileStream filepublickey = new FileStream(publicpath, FileMode.Create);

StreamWriter sw = new StreamWriter(filekeypair);
StreamWriter sw2 = new StreamWriter(filepublickey);

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

string publicPrivateKeyXML = rsa.ToXmlString(true);

string publicOnlyKeyXML = rsa.ToXmlString(false);



Create a new Folder named “Keys”

Create a new ASPX page and name as wished

Add an input field such as: <asp:TextBox ID=”txt_username” runat=”server”></asp:TextBox>

Insert the following code where desired, preferably on Register Click Button Event:

string Username = txt_username.Text;

PrivatePublicKey pp = new PrivatePublicKey();

string keyPair = “../Keys/” + Username + “pair.xml”;        //Creating an XML file with both the Private and Public Key

string keyPublic = “../Keys/” + Username + “public.xml”;      //Creating an XML file with only the Public Key to be shared

pp.CreateKeyPairs(Server.MapPath(keyPair), Server.MapPath(keyPublic));

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s